Advertisement
Guest User

Untitled

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