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