-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
1628 lines (1305 loc) · 66.2 KB
/
api.py
File metadata and controls
1628 lines (1305 loc) · 66.2 KB
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json, random, time, sys, subprocess, os, shutil, copy, requests, datetime, pprint, openai
from flask import Flask, request, Blueprint, session, redirect, url_for, send_file, send_from_directory, jsonify, render_template
from main import DI, FireAuth, Universal, manageIDToken, deleteSession, Logger, Emailer, Encryption, AddonsManager, FireConn, Analytics, FolderManager, getNameAndPosition
from dotenv import load_dotenv
load_dotenv()
apiBP = Blueprint("api", __name__)
openAIClient = None
if "VerdexGPTEnabled" in os.environ and os.environ["VerdexGPTEnabled"] == "True" and "VerdexGPTSecretKey" in os.environ:
try:
openAIClient = openai.OpenAI(
api_key=os.environ["VerdexGPTSecretKey"]
)
except Exception as e:
print("API INITIALISATION ERROR: Failed to initialise OpenAI client; error: {}".format(e))
print("API: System will continue to run without OpenAI client. VerdexGPT prompts will not be available.")
Logger.log("API INITIALISATION ERROR: Failed to initialise OpenAI client (non-terminal but GPT will be disabled); error: {}".format(e))
def checkHeaders(headers):
for param in ["Content-Type", "VerdexAPIKey"]:
if param not in headers:
return "ERROR: One or more required headers not present."
if headers["Content-Type"] != "application/json":
return "ERROR: Wrong Content-Type header."
if headers["VerdexAPIKey"] != os.environ["API_KEY"]:
return "ERROR: Invalid API key."
return True
@apiBP.route('/api/sendPasswordResetKey', methods=['POST'])
def sendPasswordResetKey():
check = checkHeaders(request.headers)
if check != True:
return check
if "usernameOrEmail" not in request.json:
return "ERROR: One or more required payload parameters not present."
## Check if email / username exists
usernameOrEmail = request.json["usernameOrEmail"]
targetAccountID = None
for accountID in DI.data["accounts"]:
if DI.data["accounts"][accountID]["email"] == usernameOrEmail:
targetAccountID = accountID
break
elif DI.data["accounts"][accountID]["username"] == usernameOrEmail:
targetAccountID = accountID
break
if targetAccountID == None:
return "UERROR: Account doesnt exist."
if "googleLogin" in DI.data["accounts"][targetAccountID] and DI.data["accounts"][targetAccountID]["googleLogin"] == True:
return "UERROR: This account is linked to Google, please reset password via Google instead."
resetKeyTime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
resetKeyValue = Analytics.generateRandomID(customLength=6)
resetKey = f"{resetKeyTime}_{resetKeyValue}"
DI.data["accounts"][targetAccountID]["resetKey"] = resetKey
DI.save()
altText = f"""
Dear {DI.data["accounts"][targetAccountID]["username"]},
We received a request to recover your account. To proceed, please use the following reset key:
{resetKeyValue}
If you did not request this, please ignore this email.
Kind regards, The Verdex Team
THIS IS AN AUTOMATED MESSAGE DELIVERED TO YOU BY VERDEX. DO NOT REPLY TO THIS EMAIL.
{Universal.copyright}
"""
html = render_template(
"emails/forgetCredentialsEmail.html",
username = DI.data["accounts"][targetAccountID]["username"],
resetKey = resetKeyValue,
copyright = Universal.copyright
)
Emailer.sendEmail(DI.data["accounts"][targetAccountID]["email"], "Verdex Account Recovery", altText, html)
return "SUCCESS: Password reset key sent to your email."
@apiBP.route('/api/passwordReset', methods=['POST'])
def passwordReset():
check = checkHeaders(request.headers)
if check != True:
return check
if "resetKeyValue" not in request.json:
return "ERROR: One or more required payload parameters not present."
if "newPassword" not in request.json:
return "ERROR: One or more required payload parameters not present."
if "cfmPassword" not in request.json:
return "ERROR: One or more required payload parameters not present."
if "usernameOrEmail" not in request.json:
return "ERROR: One or more required payload parameters not present."
usernameOrEmail = request.json["usernameOrEmail"]
newPassword = request.json["newPassword"].strip()
cfmPassword = request.json["cfmPassword"].strip()
## Get user targetAccountID using usernameOrEmail
targetAccountID = None
for accountID in DI.data["accounts"]:
if DI.data["accounts"][accountID]["email"] == usernameOrEmail:
targetAccountID = accountID
break
elif DI.data["accounts"][accountID]["username"] == usernameOrEmail:
targetAccountID = accountID
break
if targetAccountID == None:
return "UERROR: No such account with that email or username."
if "googleLogin" in DI.data["accounts"][targetAccountID] and DI.data["accounts"][targetAccountID]["googleLogin"] == True:
return "UERROR: This account is linked to Google, please reset password via Google instead."
## Expire reset keys
expiredRequestingAccountsResetKey = False
for accountID in DI.data["accounts"]:
if "resetKey" in DI.data["accounts"][accountID]:
key = DI.data["accounts"][accountID]["resetKey"]
keySplit = key.split('_')
keyTimeStr = keySplit[0]
keyValue = keySplit[1]
## Check reset key value is valid
delta = datetime.datetime.now() - datetime.datetime.strptime(keyTimeStr, "%Y-%m-%dT%H:%M:%S")
if delta.total_seconds() > 900:
del DI.data["accounts"][accountID]["resetKey"]
Logger.log("ACCOUNTS PASSWORDRESET: Deleted expired reset key for account ID {}.".format(accountID))
if accountID == targetAccountID:
expiredRequestingAccountsResetKey = True
if expiredRequestingAccountsResetKey:
return "UERROR: Reset key has expired. Please refresh and try again."
## Check if reset key value is correct
if "resetKey" not in DI.data["accounts"][targetAccountID]:
return "UERROR: Please request a password reset key first."
if request.json["resetKeyValue"] != DI.data["accounts"][targetAccountID]["resetKey"].split("_")[1]:
return "UERROR: Incorrect reset key."
## Password validation
if newPassword != cfmPassword:
return "UERROR: New and confirm password fields do not match."
if len(newPassword) < 6:
return "UERROR: Password must be at least 6 characters long."
## Update password
fireAuthID = DI.data["accounts"][targetAccountID]["fireAuthID"]
response = FireAuth.updatePassword(fireAuthID=fireAuthID, newPassword=newPassword)
if response != True:
Logger.log("ACCOUNTS CHANGEPASSWORD ERROR: Failed to change password; response: {}".format(response))
return "ERROR: Failed to change password."
### Update DI
DI.data["accounts"][targetAccountID]["password"] = Encryption.encodeToSHA256(newPassword)
del DI.data["accounts"][targetAccountID]["resetKey"]
DI.save()
Logger.log("ACCOUNTS PASSWORDRESET: Password reset for account ID {} successful.".format(targetAccountID))
return "SUCCESS: Password has been reset."
@apiBP.route('/api/loginAccount', methods=['POST'])
def loginAccount():
check = checkHeaders(request.headers)
if check != True:
return check
if "password" not in request.json:
return "ERROR: One or more rquired payload parameters not present."
if "usernameOrEmail" not in request.json:
return "ERROR: One or more required payload parameters not present."
targetAccountID = None
for accountID in DI.data["accounts"]:
if DI.data["accounts"][accountID]["username"] == request.json["usernameOrEmail"]:
targetAccountID = accountID
break
elif DI.data["accounts"][accountID]["email"] == request.json["usernameOrEmail"]:
targetAccountID = accountID
break
if targetAccountID == None:
return "UERROR: Account does not exist!"
if "googleLogin" in DI.data["accounts"][targetAccountID] and DI.data["accounts"][targetAccountID]["googleLogin"] == True:
return "UERROR: This account is linked to Google, please login via Google instead."
response = FireAuth.login(email=DI.data["accounts"][targetAccountID]["email"], password=request.json["password"])
if isinstance(response, str):
return "UERROR: Incorrect email/username or password. Please try again."
DI.data["accounts"][targetAccountID]["idToken"] = response["idToken"]
DI.data["accounts"][targetAccountID]["refreshToken"] = response["refreshToken"]
DI.data["accounts"][targetAccountID]["tokenExpiry"] = (datetime.datetime.now() + datetime.timedelta(hours=1)).strftime(Universal.systemWideStringDatetimeFormat)
DI.save()
session["idToken"] = response["idToken"]
if "admin" in DI.data["accounts"][targetAccountID] and DI.data["accounts"][targetAccountID]["admin"] == True:
session["admin"] = True
Analytics.add_metrics(Analytics.EventTypes.sign_in)
if "generatedItineraryID" in session:
if session["generatedItineraryID"] in DI.data["itineraries"]:
if "admin" in session and session["admin"] == True:
## Admin accounts cannot be associated with itineraries
del DI.data["itineraries"][session["generatedItineraryID"]]
DI.save()
del session["generatedItineraryID"]
else:
## Link itinerary to account
DI.data["itineraries"][session["generatedItineraryID"]]["associatedAccountID"] = targetAccountID
DI.save()
generatedItineraryID = session["generatedItineraryID"]
del session["generatedItineraryID"]
return "SUCCESS ITINERARYREDIRECT: User logged in succesfully. Itinerary ID: {}".format(generatedItineraryID)
else:
## Invalid itinerary ID
del session["generatedItineraryID"]
return "SUCCESS: User logged in succesfully."
@apiBP.route("/api/createAccount", methods = ['POST'])
def createAccount():
check = checkHeaders(request.headers)
if check != True:
return check
if "username" not in request.json:
return "ERROR: One or more required payload parameters not present."
if not isinstance(request.json["username"], str):
return "ERROR: Invalid username provided."
if not request.json["username"].isalnum():
return "UERROR: Username can only contain alphanumeric characters."
if "email" not in request.json:
return "ERROR: One or more required payload parameters not present."
if "password" not in request.json:
return "ERROR: One or more required payload parameters not present."
# Check if the username or email is already in use
for accountID in DI.data["accounts"]:
if DI.data["accounts"][accountID]["username"] == request.json["username"]:
return "UERROR: Username is already taken."
if DI.data["accounts"][accountID]["email"] == request.json["email"]:
return "UERROR: Email is already in use."
# Check if password is min length of 6
if len(request.json["password"]) < 6:
return "UERROR: Password must be at least 6 characters long."
# Create a new account
tokenInfo = FireAuth.createUser(email=request.json["email"], password=request.json["password"])
if isinstance(tokenInfo, str):
Logger.log("ACCOUNTS CREATEACCOUNT ERROR: Account creation failed; response: {}".format(tokenInfo))
return "UERROR: Please enter a valid Email."
accID = Universal.generateUniqueID()
DI.data["accounts"][accID] = {
"id": accID,
"fireAuthID": tokenInfo["uid"],
"googleLogin": False,
"username": request.json["username"],
"email": request.json["email"],
"password": Encryption.encodeToSHA256(request.json["password"]),
"idToken": tokenInfo['idToken'],
"refreshToken": tokenInfo['refreshToken'],
"tokenExpiry": (datetime.datetime.now() + datetime.timedelta(hours=1)).strftime(Universal.systemWideStringDatetimeFormat),
"disabled": False,
"admin": False,
"forumBanned": False,
"aboutMe": "",
"reports": {}
}
Logger.log("Account with ID {} created.".format(accID))
DI.save()
verifyEmailLink = FireAuth.generateEmailVerificationLink(request.json["email"])
if verifyEmailLink.startswith("ERROR"):
Logger.log("ACCOUNTS CREATEACCOUNT ERROR: Failed to generate email verification link; response: {}".format(verifyEmailLink))
return "ERROR: Email verification link generation failed."
altText = f"""
Dear {request.json["username"]},
Thank you for Thank you for signing up with Verdex! To finish signing up, please verify your email here:
{verifyEmailLink}
If you did not request this, please ignore this email.
Kind regards, The Verdex Team
THIS IS AN AUTOMATED MESSAGE DELIVERED TO YOU BY VERDEX. DO NOT REPLY TO THIS EMAIL.
{Universal.copyright}
"""
html = render_template(
"emails/createAccountEmail.html",
username = request.json["username"],
verifyEmailLink = verifyEmailLink,
copyright = Universal.copyright
)
Emailer.sendEmail(request.json["email"], "Welcome To Verdex", altText, html)
# destEmail, subject, altText, html
session["idToken"] = tokenInfo["idToken"]
if "generatedItineraryID" in session:
if session["generatedItineraryID"] in DI.data["itineraries"]:
DI.data["itineraries"][session["generatedItineraryID"]]["associatedAccountID"] = accID
DI.save()
generatedItineraryID = session["generatedItineraryID"]
del session["generatedItineraryID"]
return "SUCCESS ITINERARYREDIRECT: Account created successfully. Itinerary ID: {}".format(generatedItineraryID)
del session["generatedItineraryID"]
return "SUCCESS: Account created successfully."
@apiBP.route("/api/generateItinerary", methods=["POST"])
def generateItinerary():
headersCheck = checkHeaders(request.headers)
if headersCheck != True:
return headersCheck
authCheck = manageIDToken()
targetAccountID = None
if authCheck.startswith("SUCCESS"):
targetAccountID = authCheck[len("SUCCESS: ")::]
# Check body
if "targetLocations" not in request.json:
return "ERROR: One or more required payload parameters not present."
if not isinstance(request.json["targetLocations"], list):
return "ERROR: One or more required payload parameters are invalid."
if "title" not in request.json:
return "ERROR: One or more required payload parameters not present."
if "description" not in request.json:
return "ERROR: One or more required payload parameters not present."
if len(Universal.generationData) == 0 or 'locations' not in Universal.generationData or len(Universal.generationData['locations']) == 0:
return "UERROR: Generation data not available. Please try again later."
cleanTargetLocations = [x for x in request.json['targetLocations'] if x in Universal.generationData['locations']]
if len(cleanTargetLocations) > 9:
cleanTargetLocations = cleanTargetLocations[:9]
uniqueLocations = []
for location in cleanTargetLocations:
if location not in uniqueLocations:
uniqueLocations.append(location)
cleanTargetLocations = uniqueLocations
title: str = request.json['title'].strip()
description: str = request.json['description'].strip()
# Itinerary generation process
firstActivityTimeRange = ("0900", "1200")
secondActivityTimeRange = ("1300", "1600")
thirdActivityTimeRange = ("1600", "1800")
activityTimeRanges = [firstActivityTimeRange, secondActivityTimeRange, thirdActivityTimeRange]
## Prepare root itinerary object
itineraryID = Universal.generateUniqueID()
itinerary = {
"title": title,
"description": description,
"associatedAccountID": "None" if targetAccountID == None else targetAccountID,
"generationDatetime": datetime.datetime.now().strftime(Universal.systemWideStringDatetimeFormat),
"days": {}
}
## Prepare locations list
locations = cleanTargetLocations
duplicatesInsertedAsContingency = 0
while len(locations) < 9:
randomIndex = random.randint(0, len(locations) - 1) if len(locations) > 0 else 0
randomLocation = None
attempts = 30
while (randomLocation == None or randomLocation in locations) and attempts > 0:
randomLocation = random.choice([name for name in Universal.generationData["locations"]])
attempts -= 1
## If a unique new location really cannot be found, insert a random location, regardless of duplicates
if randomLocation == None or attempts <= 0:
locations.insert(randomIndex, random.choice([name for name in Universal.generationData["locations"]]))
duplicatesInsertedAsContingency += 1
continue
locations.insert(randomIndex, randomLocation)
if duplicatesInsertedAsContingency > 0:
Logger.log("API GENERATEITINERARY WARNING: {} duplicate locations inserted as contingency as enough new unique locations could not be found to insert.".format(duplicatesInsertedAsContingency))
activities = [tuple(locations[i:i+3]) for i in range(0, len(locations), 3)]
## Prepare days
sevenDayDeltaObject = datetime.datetime.now() + datetime.timedelta(days=7)
dayDates = [(sevenDayDeltaObject + datetime.timedelta(days=i+1)).strftime("%Y-%m-%d") for i in range(3)]
## Generate days
for dayCount in range(3):
day = {
"date": dayDates[dayCount],
"activities": {}
}
for activityCount in range(3):
activityLocation = activities[dayCount][activityCount]
attempts = 5
activityType = None
while (activityType == None or activityType in [x["activity"] for x in day["activities"].values()]) and attempts > 0:
activityType = random.choice(Universal.generationData["locations"][activityLocation]["supportedActivities"])
attempts -= 1
if activityType == None:
## Backup default activity type
activityType = "Visiting"
startTime = activityTimeRanges[activityCount][0]
endTime = activityTimeRanges[activityCount][1]
day["activities"][str(activityCount)] = {
"name": activities[dayCount][activityCount],
"activity": activityType,
"imageURL": Universal.generationData["locations"][activityLocation]["imageURL"],
"startTime": startTime,
"endTime": endTime
}
itinerary["days"][str(dayCount + 1)] = day
## Save itinerary
DI.data["itineraries"][itineraryID] = itinerary
DI.save()
if targetAccountID == None:
## Triggers redirect to create account/login flow
session["generatedItineraryID"] = itineraryID
return "SUCCESS ACCOUNTREDIRECT: Itinerary ID: {}".format(itineraryID)
else:
return "SUCCESS: Itinerary ID: {}".format(itineraryID)
@apiBP.route("/api/editUsername", methods = ['POST'])
def editUsername():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
## Check body
if "username" not in request.json:
return "ERROR: One or more payload not present."
if not isinstance(request.json["username"], str):
return "ERROR: Invalid username provided."
if not request.json["username"].isalnum():
return "UERROR: Username can only contain alphanumeric characters."
# Check if the username is already in use
for accountID in DI.data["accounts"]:
if DI.data["accounts"][accountID]["username"] == request.json["username"]:
return "UERROR: Username is already taken."
# Update the username in the data
DI.data["accounts"][targetAccountID]["username"] = request.json["username"]
DI.save()
return "SUCCESS: Username updated."
@apiBP.route("/api/editEmail", methods = ['POST'])
def editEmail():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
## Check body
if "email" not in request.json:
return "ERROR: One or more payload not present."
for accountID in DI.data["accounts"]:
if DI.data["accounts"][accountID]["email"] == request.json["email"]:
return "UERROR: Email is already taken."
if "googleLogin" in DI.data["accounts"][targetAccountID] and DI.data["accounts"][targetAccountID]["googleLogin"] == True:
return "UERROR: This account is linked to Google, email cannot be changed."
# Success case
## Change email in Firebase Authentication
response = FireAuth.changeUserEmail(fireAuthID = DI.data["accounts"][targetAccountID]["fireAuthID"], newEmail = request.json["email"])
if response != True:
Logger.log("API EDITEMAIL ERROR: Failed to get FireAuth to change email for account ID '{}'; response: {}".format(targetAccountID, response))
return "ERROR: Failed to change email."
## Change email verified status to False in Firebase Authentication (ignore if goes wrong)
verification = FireAuth.updateEmailVerifiedStatus(DI.data["accounts"][targetAccountID]["fireAuthID"], False)
if verification != True:
Logger.log("ACCOUNTS EDITEMAIL ERROR: Failed to update email verification status; response: {}".format(response))
## Generate email verification link
username = DI.data["accounts"][targetAccountID]["username"]
email = request.json["email"]
verifyEmailLink = FireAuth.generateEmailVerificationLink(email)
if verifyEmailLink.startswith("ERROR"):
Logger.log("ACCOUNTS EDITEMAIL ERROR: Failed to generate email verification link; response: {}".format(response))
return "ERROR: Email verification link generation failed."
## Nullify session
deleteSession(targetAccountID)
altText = f"""
Dear {username},
Please verify your email here:
{verifyEmailLink}
If you did not request this, please ignore this email.
Kind regards, The Verdex Team
THIS IS AN AUTOMATED MESSAGE DELIVERED TO YOU BY VERDEX. DO NOT REPLY TO THIS EMAIL.
{Universal.copyright}
"""
html = render_template(
"emails/resendVerificationEmail.html",
username = username,
verifyEmailLink = verifyEmailLink,
copyright = Universal.copyright
)
## Dispatch email with link via Emailer
Emailer.sendEmail(email, "Verdex Email Verification", altText, html)
# Update the email in the data
DI.data["accounts"][targetAccountID]["email"] = request.json["email"]
DI.save()
return "SUCCESS: Email updated and verification sent! Please re-login."
@apiBP.route('/api/resendEmail', methods=['POST'])
def resendEmail():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
if "googleLogin" in DI.data["accounts"][targetAccountID] and DI.data["accounts"][targetAccountID]["googleLogin"] == True:
return "UERROR: This account is linked to Google, email verification is not needed."
token = DI.data["accounts"][targetAccountID]["idToken"]
verified = FireAuth.accountInfo(token)["emailVerified"]
if verified != False:
return "ERROR: Email already verified!"
username = DI.data["accounts"][targetAccountID]["username"]
email = DI.data["accounts"][targetAccountID]["email"]
verifyEmailLink = FireAuth.generateEmailVerificationLink(email)
if verifyEmailLink.startswith("ERROR"):
Logger.log("ACCOUNTS EDITEMAIL ERROR: Failed to generate email verification link; response: {}".format(verifyEmailLink))
return "ERROR: Email verification link generation failed."
altText = f"""
Dear {username},
Please verify your email here:
{verifyEmailLink}
If you did not request this, please ignore this email.
Kind regards, The Verdex Team
THIS IS AN AUTOMATED MESSAGE DELIVERED TO YOU BY VERDEX. DO NOT REPLY TO THIS EMAIL.
{Universal.copyright}
"""
html = render_template(
"emails/resendVerificationEmail.html",
username = username,
verifyEmailLink = verifyEmailLink,
copyright = Universal.copyright
)
Emailer.sendEmail(email, "Verdex Email Verification", altText, html)
return "SUCCESS: Email verification sent."
@apiBP.route('/api/changePassword', methods=['POST'])
def changePassword():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
## Check body
if "currentPassword" not in request.json:
return "ERROR: One or more payload not present."
if "newPassword" not in request.json:
return "ERROR: One or more payload not present."
if "cfmNewPassword" not in request.json:
return "ERROR: One or more payload not present."
currentPassword = request.json["currentPassword"].strip()
newPassword = request.json["newPassword"].strip()
cfmNewPassword = request.json["cfmNewPassword"].strip()
if newPassword != cfmNewPassword:
return "UERROR: New and confirm password fields do not match."
if len(newPassword) < 6:
return "UERROR: Password must be at least 6 characters long."
if currentPassword == newPassword:
return "UERROR: New password must differ from the current password."
if "googleLogin" in DI.data["accounts"][targetAccountID] and DI.data["accounts"][targetAccountID]["googleLogin"] == True:
return "UERROR: This account is linked to Google, please change password via Google instead."
## Return change password cannot be executed if current password is not stored (in case of database synchronisation problems)
if "password" not in DI.data["accounts"][targetAccountID]:
return "UERROR: Your password cannot be changed at this time. Please try again."
## Check if current password is correct
oldPassword = DI.data["accounts"][targetAccountID]["password"]
if not Encryption.verifySHA256(currentPassword, oldPassword):
return "UERROR: Current password is incorrect."
## Update password
fireAuthID = DI.data["accounts"][targetAccountID]["fireAuthID"]
response = FireAuth.updatePassword(fireAuthID=fireAuthID, newPassword=newPassword)
if response != True:
Logger.log("ACCOUNTS CHANGEPASSWORD ERROR: Failed to change password; response: {}".format(response))
return "ERROR: Failed to change password."
### Update DI
DI.data["accounts"][targetAccountID]["password"] = Encryption.encodeToSHA256(newPassword)
DI.save()
## Automated re-login
email = DI.data["accounts"][targetAccountID]["email"]
loginResponse = FireAuth.login(email=email, password=newPassword)
if isinstance(loginResponse, str) and loginResponse.startswith("ERROR"):
Logger.log("ACCOUNTS CHANGEPASWORD ERROR: Auto login failed; response: {}".format(loginResponse))
deleteSession(targetAccountID)
return "ERROR: Change password auto login failed."
else:
DI.data["accounts"][targetAccountID]["idToken"] = loginResponse["idToken"]
DI.data["accounts"][targetAccountID]["refreshToken"] = loginResponse["refreshToken"]
DI.data["accounts"][targetAccountID]["tokenExpiry"] = (datetime.datetime.now() + datetime.timedelta(hours=1)).strftime(Universal.systemWideStringDatetimeFormat)
DI.save()
session["idToken"] = loginResponse["idToken"]
return "SUCCESS: Password updated successfully."
@apiBP.route('/api/deletePFP', methods=['POST'])
def deletePFP():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
folderRegistered = FolderManager.checkIfFolderIsRegistered(targetAccountID)
if not folderRegistered:
return "ERROR: No folder registered."
storedFilenames = FolderManager.getFilenames(targetAccountID)
for storedFile in storedFilenames:
storedFilename = storedFile.split('.')[0]
if storedFilename.endswith("pfp"):
location = os.path.join(os.getcwd(), "UserFolders", targetAccountID, storedFile)
os.remove(location)
Logger.log("ACCOUNTS DELETEPFP: Profile picture deleted for {}".format(targetAccountID))
return "SUCCESS: File removed successfully."
@apiBP.route('/api/editAboutMeDescription', methods=['POST'])
def aboutMeDescription():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
if "description" not in request.json:
return "ERROR: One or more payload not present."
if not isinstance(request.json["description"], str):
return "ERROR: Invalid description provided."
description = request.json["description"].strip()
if len(description) > 150:
return "UERROR: Your description cannot exceed 150 characters."
DI.data["accounts"][targetAccountID]["aboutMe"] = description
Logger.log("ACCOUNTS ABOUTMEDESCRIPTION: About Me description updated for {}".format(targetAccountID))
DI.save()
return "SUCCESS: Description updated."
@apiBP.route('/api/logoutIdentity', methods=['POST'])
def logoutIdentity():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
deleteSession(targetAccountID)
Analytics.add_metrics(Analytics.EventTypes.sign_out)
return "SUCCESS: User logged out."
@apiBP.route('/api/deleteIdentity', methods=['POST'])
def deleteIdentity():
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
check = checkHeaders(request.headers)
if check != True:
return check
response = FireAuth.deleteAccount(session['idToken'])
if response != True:
Logger.log("API DELETEIDENTITY ERROR: Failed to delete account with ID '{}' from FireAuth; error response: {}".format(targetAccountID, response))
return "ERROR: Something went wrong. Please try again."
else:
Logger.log("API DELETEIDENTITY: Deleted account with ID '{}' from FireAuth.".format(targetAccountID))
## Delete account and account-generated resources from DI
del DI.data["accounts"][targetAccountID]
### Delete itineraries
for itineraryID in copy.deepcopy(DI.data["itineraries"]):
if "associatedAccountID" in DI.data["itineraries"][itineraryID] and DI.data["itineraries"][itineraryID]["associatedAccountID"] == targetAccountID:
del DI.data["itineraries"][itineraryID]
### Delete posts
for postDatetime in copy.deepcopy(DI.data["forum"]):
if DI.data["forum"][postDatetime]["targetAccountIDOfPostAuthor"] == targetAccountID:
del DI.data["forum"][postDatetime]
DI.save()
## Remove the userfolder
if FolderManager.checkIfFolderIsRegistered(targetAccountID):
FolderManager.deleteFolder(targetAccountID)
Logger.log("API DELETEIDENTITY: Deleted account with ID '{}' from DI.".format(targetAccountID))
session.clear()
return "SUCCESS: Account deleted successfully."
@apiBP.route('/api/likePost', methods=['POST'])
def like_post():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
if 'postId' not in request.json:
return "ERROR: One or more payload parameters are missing."
post_id = request.json['postId']
if post_id in DI.data["forum"]:
if targetAccountID not in DI.data["forum"][post_id]["users_who_liked"]:
DI.data["forum"][post_id]["likes"] = str(int(DI.data["forum"][post_id]["likes"]) + 1)
DI.data["forum"][post_id]["users_who_liked"].append(targetAccountID)
DI.save()
return jsonify({'likes': int(DI.data["forum"][post_id]["likes"])})
else:
DI.data["forum"][post_id]["likes"] = str(int(DI.data["forum"][post_id]["likes"]) - 1)
DI.data["forum"][post_id]["users_who_liked"].remove(targetAccountID)
DI.save()
return jsonify({'likes': int(DI.data["forum"][post_id]["likes"])})
return "ERROR: Post ID not found in system."
@apiBP.route('/api/deletePost', methods=['POST'])
def delete_post():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
if 'postId' not in request.json:
return "ERROR: One or more payload parameters are missing."
post_id = request.json['postId']
if post_id in DI.data["forum"]:
if targetAccountID == DI.data["forum"][post_id]["targetAccountIDOfPostAuthor"]:
del DI.data["forum"][post_id]
DI.save()
return "SUCCESS: Post was successfully removed from the system."
else:
return "UERROR: You can't delete someone else's post!"
return "ERROR: Post ID not found in system."
@apiBP.route('/api/nextDay', methods=['POST'])
def nextDay():
check = checkHeaders(request.headers)
if check != True:
return check
nextDay = request.json['nextDay']
itineraryID = request.json['itineraryID']
if 'nextDay' not in request.json:
return "ERROR: One or more required payload parameters not provided."
if 'itineraryID' not in request.json:
return "ERROR: One or more required payload parameters not provided."
dayCountList = []
for key in DI.data["itineraries"][itineraryID]["days"]:
dayCountList.append(str(key))
if str(nextDay) not in dayCountList:
return "ERROR: You are not directed to the next day!"
else:
return "SUCCESS: You are directed to the next day!"
@apiBP.route('/api/previousDay', methods=['POST'])
def previousDay():
check = checkHeaders(request.headers)
if check != True:
return check
previousDay = request.json['previousDay']
itineraryID = request.json['itineraryID']
if 'previousDay' not in request.json:
return "ERROR: One or more required payload parameters not provided."
if 'itineraryID' not in request.json:
return "ERROR: One or more required payload parameters not provided."
dayCountList = []
for key in DI.data["itineraries"][itineraryID]["days"]:
dayCountList.append(str(key))
if str(previousDay) not in dayCountList:
return "ERROR: You are not directed to the previous day!"
else:
return "SUCCESS: You are directed to the previous day!"
@apiBP.route('/api/deleteComment', methods=['POST'])
def deleteComment():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
if 'postId' not in request.json:
return "ERROR: One or more payload parameters are missing."
if 'commentId' not in request.json:
return "ERROR: One or more payload parameters were not provided."
post_id = request.json['postId']
comment_id = request.json['commentId']
if post_id in DI.data["forum"]:
if comment_id in DI.data["forum"][post_id]["comments"]:
if targetAccountID == DI.data["forum"][post_id]["targetAccountIDOfPostAuthor"] or targetAccountID == comment_id.split("_")[1]:
del DI.data["forum"][post_id]["comments"][comment_id]
DI.save()
return "SUCCESS: Comment was successfully removed from the post in the system."
else:
return "UERROR: You can't delete someone else's comment!"
else:
return "ERROR: Comment ID not found in system."
else:
return "ERROR: Post ID not found in system."
@apiBP.route('/api/submitPost', methods=['POST'])
def submitPost():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
if 'post_title' not in request.json:
return "ERROR: One or more payload parameters are missing."
if 'post_description' not in request.json:
return "ERROR: One or more payload parameters are missing."
if 'post_tag' not in request.json:
return "ERROR: One or more payload parameters are missing."
post_title = request.json['post_title']
post_description = request.json['post_description']
post_tag = request.json['post_tag']
postDateTime = datetime.datetime.now().strftime(Universal.systemWideStringDatetimeFormat)
new_post = {
"username": DI.data["accounts"][targetAccountID]["username"],
"post_title": post_title,
"post_description": post_description,
"likes": "0",
"postDateTime": postDateTime,
"users_who_liked": [],
"tag": post_tag,
"targetAccountIDOfPostAuthor": targetAccountID,
"comments": {},
"itineraries": {}
}
DI.data["forum"][postDateTime] = new_post
DI.save()
Analytics.add_metrics(Analytics.EventTypes.forumPost)
print(Analytics.data)
return "SUCCESS: Post was successfully submitted to the system."
@apiBP.route('/api/commentPost', methods=['POST'])
def commentPost():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):
return authCheck
targetAccountID = authCheck[len("SUCCESS: ")::]
if "post_id" not in request.json:
return "ERROR: One or more payload parameters are missing."
if "comment_description" not in request.json:
return "ERROR: One or more payload parameters are missing."
post_id = request.json['post_id']
comment_description = request.json['comment_description']
if post_id in DI.data["forum"]:
if 'comments' not in DI.data["forum"][post_id]:
DI.data["forum"][post_id]['comments'] = {}
postDateTime = datetime.datetime.now().strftime(Universal.systemWideStringDatetimeFormat)
DI.data["forum"][post_id]['comments'][str(postDateTime + "_" + targetAccountID + "_" + DI.data["accounts"][targetAccountID]["username"])] = comment_description
DI.save()
return "SUCCESS: Comment successfully made."
else:
return "ERROR: Post ID not found in system."
@apiBP.route('/api/editPost', methods=['POST'])
def editPost():
check = checkHeaders(request.headers)
if check != True:
return check
authCheck = manageIDToken()
if not authCheck.startswith("SUCCESS"):