-
Notifications
You must be signed in to change notification settings - Fork 0
/
destplanner.py
744 lines (659 loc) · 23.4 KB
/
destplanner.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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
import random
import string
import os
import json
import sys
import geocoder
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask import jsonify
from flask import url_for
from flask import flash
from flask import Response
from flask import make_response
from flask import session
from sqlalchemy import create_engine
from sqlalchemy import distinct
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.exc import MultipleResultsFound
from models import Base
from models import Country
from models import DestSpot
from models import User
# 3rd party library for authorization
from flask_oauthlib.client import OAuth
geocoder_key = "AIzaSyDIJaj7bbDWpnlzaATnmuupdqyR_l5WhVw"
app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
app.secret_key = "UV9lQOnAJFVwy6td5r6tOcFF"
with open('client_secret.json') as json_file:
data = json.load(json_file)
app.config['GOOGLE_ID'] = data['GOOGLE_ID']
app.config['GOOGLE_SECRET'] = data['GOOGLE_SECRET']
# create an oauth object for this application
oauth = OAuth(app)
# configuration for authentication request
google = oauth.remote_app(
'google',
consumer_key=app.config.get('GOOGLE_ID'),
consumer_secret=app.config.get('GOOGLE_SECRET'),
request_token_params={
'scope': 'email'
},
base_url='https://www.googleapis.com/oauth2/v1/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
)
engine = create_engine(
'sqlite:///countrydestinations.db?check_same_thread=False'
)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
dbsession = DBSession()
# for API Endpoints for destinations
# call the method to view specific destination
@app.route('/apidestinations', methods=['GET', 'POST'])
def apiDestFunction():
'''
for get and post methods
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
me = google.get('userinfo')
userdata = me.data
user_id = getUserId(userdata["email"])
if request.method == 'GET':
return apiGetAllDestinations(user_id)
if request.method == 'POST':
name = request.args.get('name', '')
description = request.args.get('description', '')
return apiMakeDestination(user_id, name, description)
@app.route("/apidestinations/<int:id>", methods=['GET', 'PUT', 'DELETE'])
def destFunction(id):
'''
check method and call relevant function
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
me = google.get('userinfo')
userdata = me.data
user_id = getUserId(userdata["email"])
if request.method == 'GET':
return apiGetDestination(user_id, id)
elif request.method == 'PUT':
name = request.args.get('name', '')
description = request.args.get('description', '')
return apiUpdateDestination(user_id, id, name, description)
elif request.method == 'DELETE':
return apiDeleteDestination(user_id, id)
def apiGetAllDestinations(user_id):
'''
return all destinations as JSON
'''
try:
dests = dbsession.query(DestSpot).filter_by(user_id=user_id).all()
return jsonify(Dests=[i.serialize for i in dests])
except NoResultFound:
message = {'Status': 'No Results Found'}
return jsonify(message)
def apiGetDestination(user_id, id):
'''
returns one destination with an id
'''
try:
destination = (dbsession.query(DestSpot)
.filter_by(id=id, user_id=user_id)
.one())
return jsonify(destination=destination.serialize)
except NoResultFound:
message = {'Status': 'No Results Found'}
return jsonify(message)
def apiMakeDestination(user_id, name, description):
'''
make a new destination through api call
'''
try:
dest = DestSpot(user_id=user_id,
name=name, destdescription=description)
dbsession.add(dest)
dbsession.commit()
return jsonify(Puppy=dest.serialize)
except NoResultFound:
message = {'Status': 'No Results Found'}
return jsonify(message)
def apiUpdateDestination(user_id, id, name, description):
'''
update a destination with given info
'''
try:
dest = (dbsession.query(DestSpot)
.filter_by(user_id=user_id, id=id)
.one())
dest.destdescription = description
dbsession.add(dest)
dbsession.commit()
return "Updated a dest with id %s " % id
except NoResultFound:
message = {'Status': 'No Results Found'}
return jsonify(message)
def apiDeleteDestination(user_id, id):
'''
delete a destination through api call
'''
try:
dest = (dbsession.query(DestSpot)
.filter_by(user_id=user_id, id=id)
.one())
dbsession.delete(dest)
dbsession.commit()
return "removed a dest with id %s " % id
except NoResultFound:
message = {'Status': 'No Results Found'}
return jsonify(message)
# ********end API functionality ********#
def createUser(userdata):
'''
Creates a new user and returns id from userdata dict
'''
newUser = User(email=userdata["email"], picture=userdata["picture"])
dbsession.add(newUser)
dbsession.commit()
user = dbsession.query(User).filter_by(email=userdata["email"]).one()
return user.id
def getUserInfo(user_id):
'''
returns a user from an id
'''
user = dbsession.query(User).filter_by(id=user_id).one()
return user
def getUserId(email):
'''
returns a userid if the user email exists
'''
try:
user = dbsession.query(User).filter_by(email=email).one()
return user.id
except BaseException:
return None
@app.route('/')
@app.route('/index')
def index():
'''
If logged in: sends user data to home page
userdata object will be a python dictionary
If not logged in: render public page
'''
destinations = (dbsession.query(Country)
.distinct(Country.name)
.group_by(Country.name)
.limit(5))
if 'google_token' in session:
me = google.get('userinfo') # returns a oauthlib object
userdata = me.data # we just need the data from me object
return render_template(
'home.html',
userdata=userdata,
destinations=destinations)
else:
return render_template('pubhome.html', destinations=destinations)
@app.route('/login')
def login():
'''
if not already logged in, take user to login page
'''
if 'google_token' in session:
return redirect(url_for('index'))
else:
return render_template('login.html')
@app.route('/logout')
def logout():
'''
Remove the google_token from session object
'''
if 'google_token' not in session:
return redirect(url_for('index'))
session.pop('google_token', None)
message = 'Successfully logged out'
flash(message)
return redirect(url_for('index'))
@app.route('/callauthorize')
def callauthorize():
'''
This function initiates the google authentication if not logged in
'''
if 'google_token' in session:
return redirect(url_for('index'))
return google.authorize(callback=url_for('authorized', _external=True))
@app.route('/showlogin')
def showlogin():
'''
Show login page if not already logged in
'''
if 'google_token' in session:
return redirect(url_for('index'))
return render_template('login.html')
@app.route('/authorized')
def authorized():
'''
Carries out the authentication process and returns a token
'''
if 'google_token' in session:
return redirect(url_for('index'))
resp = google.authorized_response()
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error_reason'],
request.args['error_description']
)
session['google_token'] = (resp['access_token'], '')
me = google.get('userinfo')
userdata = me.data
users = dbsession.query(User).all()
check_user_id = getUserId(userdata["email"])
if not check_user_id:
check_user_id = createUser(userdata)
userdata["user_id"] = check_user_id
return redirect(url_for('index'))
@google.tokengetter
def get_google_oauth_token():
return session.get('google_token')
@app.route('/addcountry', methods=['GET', 'POST'])
def addcountry():
'''
Handles new country after logging in
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
if request.method == 'POST':
newcountry = Country(
name=request.form['countrySelect'],
user_id=curr_user_id)
checkcountry = dbsession.query(
Country).filter_by(user_id=curr_user_id).all()
exists = False
for item in checkcountry:
if newcountry.name == item.name:
exists = True
if not exists:
dbsession.add(newcountry)
dbsession.commit()
message = ''
message += newcountry.name
message += ' added to your country list!'
flash(message)
else:
message = 'This country is already in your list!'
flash(message)
return redirect(url_for('addcountry'))
else:
allcountrycoors = []
allcountrynames = []
listcountries = dbsession.query(
Country).filter_by(user_id=curr_user_id).all()
listlen = len(listcountries)
for i in range(listlen):
g = geocoder.google(listcountries[i].name, key=geocoder_key)
countrycoors = g.latlng
countryname = listcountries[i].name
allcountrycoors.append(countrycoors)
allcountrynames.append(countryname)
# print(allcountrynames, file=sys.stderr)
return render_template(
'addcountry.html',
coors=allcountrycoors,
allcountries=allcountrynames,
countries=listcountries)
@app.route('/viewcountries', methods=['GET', 'POST'])
def viewcountries():
'''
See the list of selected countries
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
countries = dbsession.query(Country).filter_by(
user_id=curr_user_id).order_by(
Country.name).all()
return render_template('viewcountries.html', countries=countries)
@app.route('/viewcountry/<int:countryid>', methods=['GET', 'POST'])
def viewcountry(countryid):
'''
renders each country page
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
try:
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
try:
country = dbsession.query(Country).filter(
Country.id == countryid, Country.user_id == curr_user_id).one()
except BaseException:
message = 'You are not allowed to access that resource'
flash(message)
return redirect(url_for('index'))
gresponse = geocoder.google(country.name, key=geocoder_key)
countrycoors = gresponse.latlng
destinations = dbsession.query(DestSpot).filter(
DestSpot.user_id == curr_user_id,
DestSpot.country_id == countryid).all()
print(destinations, file=sys.stderr)
return render_template(
'viewcountry.html',
country=country,
coors=countrycoors,
destinations=destinations)
except NoResultFound:
message = 'country with id: '
message += str(countryid)
message += ' not in record!'
flash(message)
return render_template('home.html')
@app.route('/deletecountry/<int:countryid>', methods=['GET', 'POST'])
def deletecountry(countryid):
'''
This method deletes the country with given id
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
try:
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
try:
countrydelete = dbsession.query(Country).filter(
Country.id == countryid, Country.user_id == curr_user_id).one()
except BaseException:
message = 'You are not allowed to access that resource'
flash(message)
return redirect(url_for('index'))
except NoResultFound:
message = 'country with id: '
message += str(countryid)
message += ' not in record!'
flash(message)
return redirect(url_for('viewcountries'))
if request.method == 'POST':
ctdname = countrydelete.name
dbsession.delete(countrydelete)
dbsession.commit()
message = 'The following country was deleted: '
message += ctdname
flash(message)
return redirect(url_for('viewcountries'))
else:
return render_template('deletecountry.html', country=countrydelete)
@app.route(
'/deletedestination/<int:countryid>/<int:destid>',
methods=[
'GET',
'POST'])
def deletedestination(countryid, destid):
'''
This method deletes the destination with given id
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
try:
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
try:
countrydd = dbsession.query(Country).filter(
Country.id == countryid, Country.user_id == curr_user_id).one()
destdelete = dbsession.query(DestSpot).filter(
DestSpot.id == destid, DestSpot.user_id == curr_user_id).one()
except BaseException:
message = 'You are not allowed to access that resource'
flash(message)
return redirect(url_for('index'))
except NoResultFound:
message = 'Destination with id: '
message += str(destid)
message += ' for country with id: '
message += str(countryid)
message += ' not in record!'
flash(message)
return redirect(
url_for(
'viewdestination',
countryid=countryid,
destid=destid))
if request.method == 'POST':
dtdname = destdelete.name
dbsession.delete(destdelete)
dbsession.commit()
message = 'The following destination was deleted: '
message += dtdname
flash(message)
return redirect(url_for('viewcountry', countryid=countryid))
else:
return render_template(
'deletedestination.html',
country=countrydd,
dest=destdelete)
@app.route('/adddestination/<int:countryid>', methods=['GET', 'POST'])
def adddestination(countryid):
'''
renders the page for adding a new location within a country
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
try:
country = dbsession.query(Country).filter(
Country.id == countryid, Country.user_id == curr_user_id).one()
except BaseException:
message = 'Access denied or no resource found'
flash(message)
return redirect(url_for('index'))
return render_template('adddestination.html', country=country)
@app.route('/destinationadded', methods=['POST'])
def destinationadded():
'''
handles the ajax post request from adddestination.html
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
lat = request.form['lat']
lng = request.form['lng']
countryid = request.form['countryid']
address = request.form['address']
# check if destination is already in db
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
respstr = ''
try:
checkDest = dbsession.query(DestSpot).filter(
DestSpot.name == address, DestSpot.user_id == curr_user_id).one()
respstr += address
respstr += '-- already exists in your list'
except NoResultFound:
defdes = ''
newdest = DestSpot(
name=address,
destlat=lat,
destlng=lng,
user_id=curr_user_id,
country_id=countryid,
destdescription=defdes)
dbsession.add(newdest)
dbsession.commit()
respstr += 'Success! '
respstr += address
respstr += ' was added to your list'
resp = make_response(json.dumps(respstr))
return resp
@app.route('/viewdestination/<int:countryid>/<int:destid>', methods=['GET'])
def viewdestination(countryid, destid):
'''
view each destination within a given country
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
try:
country = dbsession.query(Country).filter(
Country.id == countryid, Country.user_id == curr_user_id).one()
dest = dbsession.query(DestSpot).filter(
DestSpot.id == destid, DestSpot.user_id == curr_user_id).one()
except BaseException:
message = 'Resource does not exist or permission denied'
flash(message)
return redirect(url_for('index'))
return render_template('viewdestination.html', country=country, dest=dest)
@app.route(
'/adddescription/<int:countryid>/<int:destid>',
methods=[
'GET',
'POST'])
def adddescription(countryid, destid):
'''
handles description for destination
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
try:
dest = dbsession.query(DestSpot).filter(
DestSpot.id == destid, DestSpot.user_id == curr_user_id).one()
except BaseException:
message = 'Resource does not exist or permission denied'
flash(message)
return redirect(url_for('index'))
if request.method == 'POST':
newdescription = request.form['newDesc']
dest.destdescription = newdescription
dbsession.add(dest)
dbsession.commit()
updatemessage = 'Description added!'
flash(updatemessage)
return redirect(
url_for(
'viewdestination',
countryid=countryid,
destid=destid))
else:
return render_template(
'adddescription.html',
countryid=countryid,
dest=dest)
@app.route(
'/modifydescription/<int:countryid>/<int:destid>',
methods=[
'GET',
'POST'])
def modifydescription(countryid, destid):
'''
modification of description
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
try:
dest = dbsession.query(DestSpot).filter(
DestSpot.id == destid, DestSpot.user_id == curr_user_id).one()
except BaseException:
message = 'Resource does not exist or permission denied'
flash(message)
return redirect(url_for('index'))
if request.method == 'POST':
newdescription = request.form['newDesc']
dest.destdescription = newdescription
dbsession.add(dest)
dbsession.commit()
updatemessage = 'Description updated!'
flash(updatemessage)
return redirect(
url_for(
'viewdestination',
countryid=countryid,
destid=destid))
else:
return render_template(
'modifydescription.html',
countryid=countryid,
dest=dest)
@app.route('/modifyspot/<int:countryid>/<int:destid>', methods=['GET', 'POST'])
def modifyspot(countryid, destid):
'''
modification of a city name would not make sense but whatever! :)
'''
if 'google_token' not in session:
message = 'Login to access the resource'
flash(message)
return redirect(url_for('index'))
user_info_oauth = google.get('userinfo') # returns a oauthlib object
userdata = user_info_oauth.data # we just need the data from me object
curr_user_id = getUserId(userdata["email"])
try:
dest = dbsession.query(DestSpot).filter(
DestSpot.id == destid, DestSpot.user_id == curr_user_id).one()
except BaseException:
message = 'Resource does not exist or permission denied'
flash(message)
return redirect(url_for('index'))
if request.method == 'POST':
newname = request.form['newname']
dest.name = newname
dbsession.add(dest)
dbsession.commit()
updatemessage = 'Location name updated!'
flash(updatemessage)
return redirect(
url_for(
'viewdestination',
countryid=countryid,
destid=destid))
else:
return render_template(
'modifyspot.html',
countryid=countryid,
dest=dest)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)