-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
585 lines (504 loc) · 19.6 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import json
import math
import random
import string
import time
from datetime import datetime
import httplib2
import requests
from flask import Flask, render_template, request, flash, redirect, url_for
from flask import make_response, jsonify
from flask import session as login_session
from oauth2client.client import flow_from_clientsecrets, FlowExchangeError
from sqlalchemy import create_engine, asc, desc
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Category, Item, User
# Flask Init
app = Flask(__name__)
app.secret_key = "SECRET_KEY"
app.debug = True
# SQLAlchemy Init
engine = create_engine('sqlite:///catalog.db?check_same_thread=False')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
# Load up the client id from the client_secrets.json
CLIENT_ID = json.loads(
open('client_secrets.json', 'r').read()
)['web']['client_id']
# The current user object. Stores a dummy user if no one is logged in.
user = None
# Flask Routes
# Displays a list of all the categories
@app.route('/', methods=['GET', 'POST'])
@app.route('/catalog', methods=['GET', 'POST'])
def displayCatalog():
global user
if request.method == 'GET':
if user is None or (user and user.id == 999):
flash("<strong>"
"You may <a href='{}'>sign in</a> to edit, create or delete "
"items and categories."
"</strong>"
.format(url_for('showLogin')))
categories = session.query(Category).order_by(asc(Category.name)).all()
return render_template('catalog.html',
categories=categories,
user=user)
elif request.method == 'POST':
# Check if the current user is not the dummy user
if user is not None and user.id != 999:
if login_session.get('credentials') is not None:
category_name = request.form['name']
if request.form['picuri']:
picuri = request.form['picuri']
else:
picuri = url_for('static',
filename='img/'
'athlete-'
'beach-bodybuilder-305239.jpg')
userLocal = session \
.query(User) \
.filter_by(email=user.email) \
.one()
session.add(Category(
name=category_name, picture=picuri, user=userLocal)
)
session.commit()
return redirect(url_for('displayCatalog'))
else:
flash(
"<big>"
"Bummer! "
"There's authentication error. "
"Please try refreshing/logging in again.</big>")
return redirect(url_for('displayCatalog'))
else:
flash(
"<strong class='flash-message'>"
"You are currently unauthorized to do this."
" Please <a href='{}'>sign in</a> to continue."
"</strong>".format(
url_for('showLogin')
)
)
return redirect(url_for('displayCatalog'))
# Displays the items of each category
@app.route('/catalog/<string:catalog_name>/', methods=['GET', 'POST'])
def displayCategoryContents(catalog_name):
if request.method == 'POST':
global user
# Check if the current user is not the dummy user
if user is not None and user.id != 999:
newItem = Item(
creationtime=datetime.now(),
category=session
.query(Category)
.filter_by(name=catalog_name)
.one(),
user=user)
if request.form['name']:
newItem.name = request.form['name']
else:
flash("Cannot create an item without a name."
" Please try again.")
return redirect(url_for('displayCategoryContents',
catalog_name=catalog_name))
if request.form['description']:
newItem.description = request.form['description']
else:
newItem.description = "No description provided."
if request.form['picuri']:
newItem.picture = request.form['picuri']
else:
newItem.picture = url_for('static',
filename='img/'
'athlete-'
'beach-'
'bodybuilder-305239.jpg')
session.add(newItem)
session.commit()
flash("Item {} created.".format(newItem.name))
else:
flash(
"<strong class='flash-message'>"
"You are currently unauthorized to do this."
" Please <a href='{}'>sign in</a> to continue."
"</strong>"
.format(url_for('showLogin')))
flash(" If you already logged in,"
" try logging out, logging in again.")
return redirect(
url_for('displayCategoryContents',
catalog_name=catalog_name)
)
else:
category = session.query(Category).filter_by(name=catalog_name).one()
items = session.query(Item).filter_by(category=category).all()
return render_template(
'itemslist.html',
items=items,
catalog_name=catalog_name,
user=user
)
# Displays the details of an item in a category
@app.route('/catalog/<string:catalog_name>/<string:item_name>/',
methods=['GET', 'POST'])
def displayItemDetails(catalog_name, item_name):
if request.method == 'POST':
category = session \
.query(Category) \
.filter_by(name=catalog_name) \
.one()
itemToEdit = session.query(Item) \
.filter_by(category=category, name=item_name) \
.one()
# Check if the current user is not the dummy user
if user is not None and user.id != itemToEdit.user.id:
flash("Error. You can't edit the items you didn't create.")
return redirect(url_for('displayItemDetails',
catalog_name=catalog_name,
item_name=item_name
))
if user is not None and user.id != 999:
editedItemCategory = session \
.query(Category) \
.filter_by(name=catalog_name) \
.one()
editedItem = session \
.query(Item) \
.filter_by(category=editedItemCategory, name=item_name) \
.one()
if request.form['name']:
editedItem.name = request.form['name']
if request.form['description']:
editedItem.description = request.form['description']
if request.form['category']:
category = session \
.query(Category) \
.filter_by(id=request.form['category']) \
.one()
editedItem.category = category
session.add(editedItem)
session.commit()
flash('{} Successfully Edited'.format(editedItem.name))
return redirect(url_for(
'displayCategoryContents',
catalog_name=catalog_name,
user=user
))
else:
flash(
"<big>Authentication error occurred. "
"Try refreshing the page/logging in again.</big>"
)
flash(
" If you already logged in, try logging out, logging in again."
)
return redirect(url_for(
'displayCategoryContents',
catalog_name=catalog_name
))
else:
# Categories needed for editing the item details and
# displaying in drop down menu
categories = session.query(Category).all()
catalog = session. \
query(Category). \
filter_by(name=catalog_name) \
.one()
item = session.query(Item) \
.filter_by(name=item_name, category=catalog) \
.one()
itemslist = session.query(Item).filter_by(category=catalog)
return render_template(
'itemdetail.html',
categories=categories,
category=catalog,
current_item=item,
items=itemslist,
user=user
)
# Displays the most recently added items
@app.route('/recents/')
def displayRecents():
categories = session.query(Category).order_by(asc(Category.name))
recents = session.query(Item).order_by(desc(Item.creationtime))
return render_template(
'recent.html',
categories=categories,
recents=recents,
current_time=datetime.now(),
user=user
)
# Route to delete a particular item in a category
@app.route('/<string:category_name>/<string:item_name>/delete',
methods=['GET', 'POST'])
def deleteItem(category_name, item_name):
if request.method == 'POST':
category = session \
.query(Category) \
.filter_by(name=category_name) \
.one()
item = session \
.query(Item) \
.filter_by(name=item_name, category=category) \
.one()
# Check if the current user is not the dummy user
if user is not None and user.id != item.user.id:
flash(
"<strong class='flash-message'>Error."
" Cannot delete items you didn't create.</strong>")
return redirect(url_for(
'displayItemDetails',
catalog_name=category_name,
item_name=item_name,
user=user
))
elif user is not None and user.id != 999:
session.delete(item)
session.commit()
flash("Item '{}' deleted successfully".format(item_name))
return redirect(
url_for('displayCategoryContents', catalog_name=category_name))
else:
flash(
"<strong class='flash-message'>"
"You are currently unauthorized to do this. "
"Please <a href='{}'>sign in</a> to continue.</strong>"
.format(url_for('showLogin')))
flash(
" If you already logged in, try logging out, logging in again."
)
return redirect(url_for(
'displayItemDetails',
catalog_name=category_name,
item_name=item_name
))
else:
return "Sorry! We don't accept 'GET' requests. :/"
# Route to delete a category and it's contents
@app.route('/<string:category_name>/delete', methods=['POST', 'GET'])
def deleteCategory(category_name):
if request.method == 'POST':
# Check if the current user is not the dummy user
category = session \
.query(Category) \
.filter_by(name=category_name) \
.one()
if user is not None and user.id != category.user.id:
flash(
"<strong>"
"You can't delete the category you didn't create."
"</strong>")
return redirect(url_for('displayCatalog'))
elif user is not None and user.id != 999:
for item in session.query(Item).filter_by(category=category).all():
session.delete(item)
session.delete(category)
session.commit()
else:
flash(
"<strong class='flash-message'>"
"You are currently unauthorized to do this. "
"Please <a href='{}'>sign in</a> to continue."
"</strong>"
.format(url_for('showLogin')))
flash(
" If you already logged in, try logging out, logging in again."
)
return redirect(url_for('displayCatalog'))
else:
return "Sorry! We don't accept 'GET' requests. :/"
# ====Authentication====
# Opens the profile page
@app.route('/login')
def showLogin():
updateUser()
# Create a random state key to pass in the login.html
state = ''.join(random.choice(string.ascii_uppercase + string.digits)
for x in range(32)
)
login_session['state'] = state
return render_template('login.html', STATE=state, user=user)
@app.route('/gconnect', methods=['POST'])
def gconnect():
# Check for invalid session state
if request.args.get('state') != login_session['state']:
response = make_response(json.dumps('Invalid State Parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
code = request.data
try:
oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
oauth_flow.redirect_uri = 'postmessage'
credentials = oauth_flow.step2_exchange(code)
except FlowExchangeError:
response = make_response(json.dumps(
'Failed to upgrade the authorization code.'), 401
)
response.headers['Content-Type'] = 'application/json'
return response
access_token = credentials.access_token
url = (
'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
% access_token
)
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
# Response if error occurred.
if result.get('error') is not None:
response = make_response(json.dumps(result.get('error')), 501)
response.headers['Content-Type'] = 'application/json'
# Token's user ID doesn't match given user ID
gplus_id = credentials.id_token['sub']
if result['user_id'] != gplus_id:
response = make_response(json.dumps(
"Token's user ID doesn't match given user ID"), 401
)
response.headers['Content-Type'] = 'application/json'
return response
if result['issued_to'] != CLIENT_ID:
response = make_response(
json.dumps("Token's client ID does not match app's."), 401)
print("Token's client ID does not match app's.")
response.headers['Content-Type'] = 'application/json'
return response
stored_credentials = login_session.get('credentials')
stored_gplus_id = login_session.get('gplus_id')
if stored_credentials is not None and gplus_id == stored_gplus_id:
response = make_response(json.dumps(
'Current user is already connected.'), 200
)
response.headers['Content-Type'] = 'application/json'
login_session['credentials'] = credentials.to_json()
login_session['gplus_id'] = gplus_id
userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
params = {'access_token': credentials.access_token, 'alt': 'json'}
answer = requests.get(userinfo_url, params=params)
data = answer.json()
login_session['username'] = data['name']
login_session['picture'] = data['picture']
login_session['email'] = data['email']
# Find the user_id
user_id = getUserID(login_session['email'])
if not user_id:
# If user isn't present, create a user object
user_id = createUser(login_session)
login_session['user_id'] = user_id
updateUser()
# flash("")
output = "<big>You are now logged in as {}</big>".format(
login_session['username'])
flash(output)
return jsonify(user=user.serialize)
@app.route('/gdisconnect')
def gdisconnect():
try:
credentials = json.loads(login_session.get('credentials'))
except:
flash("An Error Occured.")
return redirect(url_for('displayCatalog'))
access_token = credentials['access_token']
if access_token is None:
print('Access Token is None')
response = make_response(json.dumps('Current user not connected.'),
401)
response.headers['Content-Type'] = 'application/json'
return response
url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % credentials[
'access_token']
h = httplib2.Http()
result = h.request(url, 'GET')[0]
print('result is ')
print(result)
if result['status'] == '200':
del login_session['gplus_id']
del login_session['username']
del login_session['email']
del login_session['picture']
del login_session['credentials']
del login_session['user_id']
global user
user = None
flash("Successfully Logged Out.")
return redirect(url_for('displayCatalog'))
else:
response = make_response(json.dumps(
'Failed to revoke token for given user. Please open in a '
'new window and log in again.')
)
response.headers['Content-Type'] = 'application/json'
return response
# ====JSON====
# JSON of the whole catalog
@app.route('/catalog/JSON')
def catalogJSON():
categories = session.query(Category).all()
category_dict = [c.serialize for c in categories]
for c in range(len(category_dict)):
category = session \
.query(Category) \
.filter_by(name=category_dict[c]["name"]) \
.one()
items = [
i.serialize for i in session
.query(Item)
.filter_by(category=category)
.all()
]
if items:
category_dict[c]["items"] = items
return jsonify(Category=category_dict)
# JSON of a particular category
@app.route('/catalog/<string:catalog_name>/JSON')
def categoryContentsJSON(catalog_name):
category = session.query(Category).filter_by(name=catalog_name).one()
items = session.query(Item).filter_by(category=category).all()
return jsonify(items=[i.serialize for i in items])
# JSON of a particular item in a category
@app.route('/catalog/<string:category_name>/<string:item_name>/JSON')
def itemJSON(category_name, item_name):
category = session.query(Category).filter_by(name=category_name).one()
item = session.query(Item).filter_by(name=item_name,
category=category).one()
return jsonify(item=item.serialize)
# Helper Functions
# Update the current user state
def updateUser():
global user
try:
# Find user by email
user = session.query(User).filter_by(email=login_session['email']) \
.one()
except:
# Create dummy user
user = User(
id=999,
name="Please Log In",
picture=url_for('static', filename="img/profile.png")
)
# Creates a user from the login_session object
def createUser(login_session):
newUser = User(
name=login_session['username'],
email=login_session['email'],
picture=login_session['picture'])
session.add(newUser)
session.commit()
user = session.query(User).filter_by(email=login_session['email']).one()
return user.id
# Returns the user_id from the email
def getUserID(email):
try:
user = session.query(User).filter_by(email=email).one()
return user.id
except:
return None
# Returns the seconds elapsed from creation_time
def calculateTimeElapsed(creation_time):
return int(math.floor(time.time() - creation_time.timestamp()))
# Set this function as global to use in Jinja Template
app.jinja_env.globals.update(calculate_elapsed_time=calculateTimeElapsed)
if __name__ == '__main__':
app.run(debug=False)