Advertisement
lamiastella

Corrected Code

Oct 13th, 2017
645
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.70 KB | None | 0 0
  1. ######################################
  2. # author ben lawson <balawson@bu.edu>
  3. # Edited by: Baichuan Zhou (baichuan@bu.edu) and Craig Einstein <einstein@bu.edu>
  4. ######################################
  5. # Some code adapted from
  6. # CodeHandBook at http://codehandbook.org/python-web-application-development-using-flask-and-mysql/
  7. # and MaxCountryMan at https://github.com/maxcountryman/flask-login/
  8. # and Flask Offical Tutorial at  http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
  9. # see links for further understanding
  10. ###################################################
  11.  
  12. import flask
  13. from flask import Flask, Response, request, render_template, redirect, url_for
  14. from flaskext.mysql import MySQL
  15. import flask.ext.login as flask_login
  16.  
  17. # for image uploading
  18. # from werkzeug import secure_filename
  19. import os, base64
  20.  
  21. mysql = MySQL()
  22. app = Flask(__name__)
  23. app.secret_key = 'super secret string'  # Change this!
  24.  
  25. # These will need to be changed according to your creditionals
  26. app.config['MYSQL_DATABASE_USER'] = 'root'
  27. app.config['MYSQL_DATABASE_PASSWORD'] = 'hello'
  28. app.config['MYSQL_DATABASE_DB'] = 'photoshare'
  29. app.config['MYSQL_DATABASE_HOST'] = 'localhost'
  30. mysql.init_app(app)
  31.  
  32. # begin code used for login
  33. login_manager = flask_login.LoginManager()
  34. login_manager.init_app(app)
  35.  
  36. conn = mysql.connect()
  37. cursor = conn.cursor()
  38. cursor.execute("SELECT email FROM Users")
  39. users = cursor.fetchall()
  40.  
  41.  
  42. def getUserList():
  43.     cursor = conn.cursor()
  44.     cursor.execute("SELECT email FROM Users")
  45.     return cursor.fetchall()
  46.  
  47.  
  48. class User(flask_login.UserMixin):
  49.     pass
  50.  
  51.  
  52. @login_manager.user_loader
  53. def user_loader(email):
  54.     users = getUserList()
  55.     if not (email) or email not in str(users):
  56.         return
  57.     user = User()
  58.     user.id = email
  59.     return user
  60.  
  61.  
  62. @login_manager.request_loader
  63. def request_loader(request):
  64.     users = getUserList()
  65.     email = request.form.get('email')
  66.     if not (email) or email not in str(users):
  67.         return
  68.     user = User()
  69.     user.id = email
  70.     cursor = mysql.connect().cursor()
  71.     cursor.execute("SELECT password FROM Users WHERE email = '{0}'".format(email))
  72.     data = cursor.fetchall()
  73.     pwd = str(data[0][0])
  74.     user.is_authenticated = request.form['password'] == pwd
  75.     return user
  76.  
  77.  
  78. '''
  79. A new page looks like this:
  80. @app.route('new_page_name')
  81. def new_page_function():
  82.     return new_page_html
  83. '''
  84.  
  85.  
  86. @app.route('/login', methods=['GET', 'POST'])
  87. def login():
  88.     if flask.request.method == 'GET':
  89.         return '''
  90.                <form action='login' method='POST'>
  91.                 <input type='text' name='email' id='email' placeholder='email'></input>
  92.                 <input type='password' name='password' id='password' placeholder='password'></input>
  93.                 <input type='submit' name='submit'></input>
  94.                </form></br>
  95.            <a href='/'>Home</a>
  96.                '''
  97.     # The request method is POST (page is recieving data)
  98.     email = flask.request.form['email']
  99.     cursor = conn.cursor()
  100.     # check if email is registered
  101.     if cursor.execute("SELECT password FROM Users WHERE email=email"):
  102.         data = cursor.fetchall()
  103.         pwd = str(data[0][0])
  104.         if flask.request.form['password'] == pwd:
  105.             user = User()
  106.             user.id = email
  107.             flask_login.login_user(user)  # okay login in user
  108.             return flask.redirect(flask.url_for('protected'))  # protected is a function defined in this file
  109.  
  110.     # information did not match
  111.     return "<a href='/login'>Try again</a>\
  112.             </br><a href='/register'>or make an account</a>"
  113.  
  114.  
  115. @app.route('/logout')
  116. def logout():
  117.     flask_login.logout_user()
  118.     return render_template('hello.html', message='Logged out')
  119.  
  120.  
  121. @login_manager.unauthorized_handler
  122. def unauthorized_handler():
  123.     return render_template('unauth.html')
  124.  
  125.  
  126. # you can specify specific methods (GET/POST) in function header instead of inside the functions as seen earlier
  127. @app.route("/register", methods=['GET'])
  128. def register():
  129.     return render_template('register.html', supress='True')
  130.  
  131.  
  132. @app.route("/register", methods=['POST'])
  133. def register_user():
  134.     try:
  135.         email = request.form.get('email')
  136.         password = request.form.get('password')
  137.     except:
  138.         print(
  139.             "couldn't find all tokens")  # this prints to shell, end users will not see this (all print statements go to shell)
  140.         return flask.redirect(flask.url_for('register'))
  141.     cursor = conn.cursor()
  142.     test = isEmailUnique(email)
  143.     if test:
  144.         #print(cursor.execute("INSERT INTO Users (email, password) VALUES ('email', 'password')"))
  145.  
  146.         #cursor.execute("INSERT INTO Pictures (imgdata, user_id, caption) VALUES (%s, %s, %s)",
  147.         #               (photo_data, uid, caption))
  148.         print(cursor.execute("INSERT INTO Users (email, password) VALUES (%s , %s)", (email, password)))
  149.         conn.commit()
  150.         # log user in
  151.         user = User()
  152.         user.id = email
  153.         flask_login.login_user(user)
  154.         return render_template('hello.html', name=email, message='Account Created!')
  155.     else:
  156.         print("couldn't find all tokens")
  157.         return flask.redirect(flask.url_for('register'))
  158.  
  159.  
  160. def getUsersPhotos(uid):
  161.     cursor = conn.cursor()
  162.  
  163.     cursor.execute("SELECT imgdata, picture_id, caption FROM Pictures WHERE user_id = 'uid'")
  164.     return cursor.fetchall()  # NOTE list of tuples, [(imgdata, pid), ...]
  165.  
  166.  
  167. def getUserIdFromEmail(email):
  168.     cursor = conn.cursor()
  169.     cursor.execute("SELECT user_id  FROM Users WHERE email = email")
  170.     return cursor.fetchone()[0]
  171.  
  172.  
  173. def isEmailUnique(email):
  174.     # use this to check if a email has already been registered
  175.     cursor = conn.cursor()
  176.     if cursor.execute("SELECT email  FROM Users WHERE email = email"):
  177.         # this means there are greater than zero entries with that email
  178.         return False
  179.     else:
  180.         return True
  181.  
  182.  
  183. # end login code
  184.  
  185. @app.route('/profile')
  186. @flask_login.login_required
  187. def protected():
  188.     return render_template('hello.html', name=flask_login.current_user.id, message="Here's your profile")
  189.  
  190.  
  191. # begin photo uploading code
  192. # photos uploaded using base64 encoding so they can be directly embeded in HTML
  193. ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
  194.  
  195.  
  196. def allowed_file(filename):
  197.     return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
  198.  
  199.  
  200. @app.route('/upload', methods=['GET', 'POST'])
  201. @flask_login.login_required
  202. def upload_file():
  203.     if request.method == 'POST':
  204.         uid = getUserIdFromEmail(flask_login.current_user.id)
  205.         imgfile = request.files['photo']
  206.         caption = request.form.get('caption')
  207.         print(caption)
  208.         photo_data = base64.standard_b64encode(imgfile.read())
  209.         cursor = conn.cursor()
  210.         #cursor.execute(
  211.         #    "INSERT INTO Pictures (imgdata, user_id, caption) VALUES ('photo_data', 'uid', 'caption')")
  212.         cursor.execute("INSERT INTO Pictures (imgdata, user_id, caption) VALUES (%s, %s, %s)",
  213.                        (photo_data, uid, caption))
  214.         #cursor.execute("INSERT INTO Pictures (imgdata, user_id, caption) VALUES (?, ?, ?)", (photo_data, uid, caption))
  215.         conn.commit()
  216.         return render_template('hello.html', name=flask_login.current_user.id, message='Photo uploaded!',
  217.                                photos=getUsersPhotos(uid))
  218.     # The method is GET so we return a  HTML form to upload the a photo.
  219.     else:
  220.         return render_template('upload.html')
  221.  
  222.  
  223. # end photo uploading code
  224.  
  225.  
  226. # default page
  227. @app.route("/", methods=['GET'])
  228. def hello():
  229.     return render_template('hello.html', message='Welecome to Photoshare')
  230.  
  231.  
  232. if __name__ == "__main__":
  233.     # this is invoked when in the shell  you run
  234.     # $ python app.py
  235.     app.run(port=5000, debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement