This repository has been archived by the owner on Mar 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
__init__.py
6476 lines (5563 loc) · 322 KB
/
__init__.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
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
from flask import Flask, render_template, request, redirect, url_for, session, make_response, flash, Markup, abort, send_from_directory
from werkzeug.utils import secure_filename
import shelve, math, paypalrestsdk, difflib, json, csv, phonenumbers, pyotp, qrcode
from os import environ
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from pathlib import Path
from requests import post as pyPost
from flask_mailman import Mail
from datetime import date, timedelta, datetime
from base64 import b64encode, b64decode
from apscheduler.schedulers.background import BackgroundScheduler
from matplotlib import pyplot as plt
from dicebear import DOptions
from python_files import Student, Teacher, Forms, Course
from python_files.Ticket import Ticket
from python_files.Cashout import Cashout
from python_files.Common import checkUniqueElements
from python_files.Security import sanitise, sanitise_quote
from python_files.IntegratedFunctions import *
"""Web app configurations"""
# general Flask configurations
app = Flask(__name__)
app.config["SECRET_KEY"] = "a secret key" # for demonstration purposes, if deployed, change it to something more secure
scheduler = BackgroundScheduler()
# Maximum file size for uploading anything to the web app's server
app.config['MAX_CONTENT_LENGTH'] = 200 * 1024 * 1024 # 200MiB
# Configurations for dicebear api for user profile image options
app.config["DICEBEAR_OPTIONS"] = DOptions(
size=250
)
# creating an absolute path for storing the shelve files
app.config["DATABASE_FOLDER"] = str(app.root_path) + "\\databases"
# for image uploads file path
app.config["PROFILE_UPLOAD_PATH"] = "static/images/user"
app.config["THUMBNAIL_UPLOAD_PATH"] = "static/images/courses/thumbnails"
app.config["ALLOWED_IMAGE_EXTENSIONS"] = ("png", "jpg", "jpeg")
# for course video uploads file path
app.config["COURSE_VIDEO_FOLDER"] = "static/course_videos"
app.config["ALLOWED_VIDEO_EXTENSIONS"] = (
".mp4, .mov, .avi, .3gpp, .flv, .mpeg4, .flv, .webm, .mpegs, .wmv")
# configuration for email
# Make sure to enable access for less secure apps
app.config["MAIL_SERVER"] = "smtp.gmail.com" # using gmail
app.config["MAIL_PORT"] = 587
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USERNAME"] = "CourseFinity123@gmail.com" # using gmail
app.config["MAIL_PASSWORD"] = environ.get("EMAIL_PASS") # setting password but hiding the password for the CourseFinity123@gmail.com password using system environment variables
mail = Mail(app)
# paypal sdk configuration
paypalrestsdk.configure({
"mode": "sandbox",
"client_id": "AUTh83JMz8mLNGNzpzJRJSbSLUAEp7oe1ieGGqYCmVXpq427DeSVElkHnc0tt70b8gHlWg4yETnLLu1s",
"client_secret": environ.get("PAYPAL_SECRET") })
# Flask limiter configuration
limiter = Limiter(app, key_func=get_remote_address, default_limits=["30 per second"])
"""End of Web app configurations"""
"""Home page by Jason"""
@app.route('/')
def home():
courseDict = {}
userDict = {}
try:
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "r")
courseDict = db['Courses']
userDict = db['Users']
db.close()
print("File found.")
except:
print("File could not be found.")
# since the shelve files could not be found, it will create a placeholder/empty shelve files
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "c")
db["Courses"] = courseDict
db["Users"] = userDict
db.close()
# for trending algorithm
trendingCourseList = []
count = 0
try:
courseDictCopy = courseDict.copy()
while count != 3:
highestViewedCourse = max(courseDictCopy, key=lambda courseID: courseDictCopy[courseID].get_views())
# retrieve teacher user ID
courseTeacherID = courseDict.get(highestViewedCourse).get_userID()
# based on the teacher user ID and check if the teacher is banned
if userDict.get(courseTeacherID).get_status() == "Good":
# append course object if the teacher is not banned
trendingCourseList.append(courseDict.get(highestViewedCourse))
courseDictCopy.pop(highestViewedCourse)
count += 1
else:
# remove the course object from the courseDictCopy if the teacher is banned
courseDictCopy.pop(highestViewedCourse)
except:
print("No courses or not enough courses (requires 3 courses)")
trendingCourseList = []
for course in courseDict.values():
if userDict.get(course.get_userID()).get_status() == "Good":
trendingCourseList.append(course)
# for retrieving the teacher's username
trendingDict = {}
for courses in trendingCourseList:
teacherObject = userDict.get(courses.get_userID())
teacherUsername = teacherObject.get_username()
trendingDict[courses] = teacherUsername
if "adminSession" in session or "userSession" in session:
if "adminSession" in session:
userSession = session["adminSession"]
else:
userSession = session["userSession"]
userKey, userFound, accGoodStatus, accType, imagesrcPath = general_page_open_file_with_userKey(userSession)
if userFound and accGoodStatus:
if accType != "Admin":
# for recommendation algorithm
recommendCourseList = []
# removing purchased courses from being recommended since it has already been bought by the user
userPurchasedCourses = userKey.get_purchases() # to be edited once the attribute in the class has been updated
for courseID in list(courseDict.keys()):
if courseID in userPurchasedCourses:
print("User has purchased the course,", courseDict[courseID].get_title())
courseDict.pop(courseID)
if len(courseDict) > 3:
userTagDict = userKey.get_tags_viewed()
numberOfUniqueViews = checkUniqueElements(userTagDict)
if numberOfUniqueViews > 1:
highestWatchedByTag = max(userTagDict, key=userTagDict.get)
userTagDict.pop(highestWatchedByTag)
numberOfUnqiueViews = checkUniqueElements(userTagDict)
if numberOfUnqiueViews > 1:
secondHighestWatchedByTag = max(userTagDict, key=userTagDict.get)
else:
print("User has watched some tags but only one tag is the highest while the rest of tags are the same (assuming the dictionary has not popped its highest tag yet)")
try:
# hence choosing one other random course objects
while True:
randomisedCourse = random.choice(list(courseDict.values()))
if userDict.get(randomisedCourse.get_userID()).get_status() == "Good":
recommendCourseList.append(randomisedCourse)
courseDict.pop(randomisedCourse.get_courseID())
break
else:
# if the teacher of the course has been banned
courseDict.pop(randomisedCourse.get_courseID())
except:
print("No course found.")
else:
# choosing three random course objects
print("User has not watched any tags or has watched an equal balance of various tags.")
try:
while len(recommendCourseList) != 3:
randomisedCourse = random.choice(list(courseDict.values()))
if userDict.get(randomisedCourse.get_userID()).get_status() == "Good":
recommendCourseList.append(randomisedCourse)
courseDict.pop(randomisedCourse.get_courseID())
else:
# if the teacher of the course has been banned
courseDict.pop(randomisedCourse.get_courseID())
except:
print("No courses found.")
print(courseDict)
recommendedCourseListByHighestTag = []
# checking current length of the recommendCourseList if the length is less than 3, then adding courses to make it a length of 3
courseListLen = len(recommendCourseList)
if courseListLen == 0: # condition will be true when the user has two unique highest tags
recommendedCourseListBySecondHighestTag = []
for courseObject in list(courseDict.values()):
courseTag = courseObject.get_tag()
if courseTag == highestWatchedByTag:
if userDict.get(courseObject.get_userID()).get_status() == "Good":
recommendedCourseListByHighestTag.append(courseObject)
else:
# if the teacher of the course has been banned
courseDict.pop(courseObject.get_courseID())
elif courseTag == secondHighestWatchedByTag:
if userDict.get(courseObject.get_userID()).get_status() == "Good":
recommendedCourseListBySecondHighestTag.append(courseObject)
else:
# if the teacher of the course has been banned
courseDict.pop(courseObject.get_courseID())
# appending course object for recommendations
count = 0
HighestTagCoursesAvailable = len(recommendedCourseListByHighestTag)
print("Courses available: ", HighestTagCoursesAvailable)
if HighestTagCoursesAvailable >= 2:
courseOne, courseTwo = random.sample(recommendedCourseListByHighestTag, 2)
recommendCourseList.append(courseOne)
recommendCourseList.append(courseTwo)
print("Two courses picked accordingly to user's highly watched tag.")
# picks one course for recommendations according to the user's second highly watched tag
SecondHighestTagCoursesAvailable = len(recommendedCourseListBySecondHighestTag)
print("Courses available: ", SecondHighestTagCoursesAvailable)
if SecondHighestTagCoursesAvailable >= 1:
randomisedCourse = random.choice(recommendedCourseListBySecondHighestTag)
recommendCourseList.append(randomisedCourse)
print("One course picked accordingly to user's second highly watched tag.")
elif HighestTagCoursesAvailable == 1:
# if there is only one course according to the user's highly watched tag (possibly due to a lack of courses, the teacher deleting the course, or the teacher being banned)
# recommends 1 courses according to the user's highly watched tag
course = recommendedCourseListByHighestTag[0]
recommendCourseList.append(course)
print("One course picked accordingly to user's highly watched tag.")
SecondHighestTagCoursesAvailable = len(recommendedCourseListBySecondHighestTag)
print("Courses available: ", SecondHighestTagCoursesAvailable)
if SecondHighestTagCoursesAvailable >= 2:
randomisedCourseOne, randomisedCourseTwo = random.sample(recommendedCourseListBySecondHighestTag, 2)
recommendCourseList.append(randomisedCourseOne)
recommendCourseList.append(randomisedCourseTwo)
print("Two courses picked accordingly to user's second highly watched tag.")
elif SecondHighestTagCoursesAvailable == 1:
course = recommendedCourseListBySecondHighestTag[0]
recommendCourseList.append(course)
print("One course picked accordingly to user's second highly watched tag.")
else:
# if there is only no courses according to the user's highly watched tag (possibly due to a lack of courses, the teacher deleting the course, or the teacher being banned)
# recommends 2 courses according to the user's second highly watched tag
SecondHighestTagCoursesAvailable = len(recommendedCourseListBySecondHighestTag)
print("Courses available: ", SecondHighestTagCoursesAvailable)
if SecondHighestTagCoursesAvailable >= 2:
randomisedCourseOne, randomisedCourseTwo = random.sample(recommendedCourseListBySecondHighestTag, 2)
recommendCourseList.append(randomisedCourseOne)
recommendCourseList.append(randomisedCourseTwo)
print("Two courses picked accordingly to user's second highly watched tag.")
elif SecondHighestTagCoursesAvailable == 1:
course = recommendedCourseListBySecondHighestTag[0]
recommendCourseList.append(course)
print("One course picked accordingly to user's second highly watched tag.")
elif courseListLen == 1: # condition will be true when the user has only one unique highest tag
for courseObject in list(courseDict.values()):
courseTag = courseObject.get_tag()
if courseTag == highestWatchedByTag:
if (userDict.get(courseObject.get_userID()).get_status() == "Good") and (courseObject not in recommendCourseList):
recommendedCourseListByHighestTag.append(courseObject)
else:
# if the teacher of the course has been banned or has already been recommended
courseDict.pop(courseObject.get_courseID())
# appending course object for recommendations
HighestTagCoursesAvailable = len(recommendedCourseListByHighestTag)
print("Courses available: ", HighestTagCoursesAvailable)
if HighestTagCoursesAvailable >= 2:
courseOne, courseTwo = random.sample(recommendedCourseListByHighestTag, 2)
recommendCourseList.append(courseOne)
recommendCourseList.append(courseTwo)
print("Two courses picked accordingly to user's highly watched tag.")
elif HighestTagCoursesAvailable == 1:
# if there is only one course according to the user's highly watched tag (possibly due to a lack of courses, the teacher deleting the course, or the teacher being banned)
# recommends 1 courses according to the user's highly watched tag
course = recommendedCourseListByHighestTag[0]
recommendCourseList.append(course)
print("One course picked accordingly to user's highly watched tag.")
# in the event where there is insufficient courses to recommend, it will randomly choose another course object
recommendLen = len(recommendCourseList)
if recommendLen != 3:
print("Retrieving random courses as recommendations...")
while recommendLen != 3:
try:
randomisedCourse = random.choice(list(courseDict.values()))
except:
break
if userDict.get(randomisedCourse.get_userID()).get_status() == "Good":
if randomisedCourse not in recommendCourseList:
recommendCourseList.append(randomisedCourse)
recommendLen = len(recommendCourseList)
else:
courseDict.pop(randomisedCourse.get_courseID())
else:
courseDict.pop(randomisedCourse.get_courseID())
else:
print("Not enough courses to personalise the recommendations...")
for value in courseDict.values():
if userDict.get(value.get_userID()).get_status() == "Good":
recommendCourseList.append(value)
# retrieving course teacher's username
recommedationDict = {}
for courses in recommendCourseList:
teacherObject = userDict.get(courses.get_userID())
teacherUsername = teacherObject.get_username()
recommedationDict[courses] = teacherUsername
# logged in users
if accType == "Teacher":
teacherUID = userSession
else:
teacherUID = ""
# Get shopping cart len
shoppingCartLen = len(userKey.get_shoppingCart())
return render_template('users/general/home.html', shoppingCartLen=shoppingCartLen, accType=accType, imagesrcPath=imagesrcPath, trendingCourseDict=trendingDict, recommendCourseDict=recommedationDict, trendingCourseLen=len(trendingCourseList), recommendCourseLen=len(recommendCourseList), teacherUID=teacherUID, userPurchasedCourses=userPurchasedCourses)
else:
# admins
recommendCourseList = get_random_courses(courseDict)
# retrieving course teacher's username
recommedationDict = {}
for courses in recommendCourseList:
teacherObject = userDict.get(courses.get_userID())
teacherUsername = teacherObject.get_username()
recommedationDict[courses] = teacherUsername
return render_template('users/general/home.html', accType=accType, imagesrcPath=imagesrcPath, trendingCourseDict=trendingDict, recommendCourseDict=recommedationDict, trendingCourseLen=len(trendingCourseList), recommendCourseLen=len(recommendCourseList))
else:
# users with invalid session, aka guest
print("Admin/User account is not found or is not active/banned.")
session.clear()
return redirect(url_for("home"))
else:
# guests
if not request.cookies.get("guestSeenTags"):
print("Guest user do not have cookie.")
session["sessionCookieCreated"] = True
return redirect(url_for("guestCookies"))
else:
print("Guest user has a cookie.")
userTagDict = json.loads(b64decode(request.cookies.get("guestSeenTags")))
# for recommendation algorithm
recommendCourseList = []
if len(courseDict) > 3:
numberOfUniqueViews = checkUniqueElements(userTagDict)
if numberOfUniqueViews > 1:
highestWatchedByTag = max(userTagDict, key=userTagDict.get)
userTagDict.pop(highestWatchedByTag)
numberOfUnqiueViews = checkUniqueElements(userTagDict)
if numberOfUnqiueViews > 1:
secondHighestWatchedByTag = max(userTagDict, key=userTagDict.get)
else:
print("User has watched some tags but only one tag is the highest while the rest of tags are the same (assuming the dictionary has not popped its highest tag yet)")
try:
# hence choosing one other random course objects
while True:
randomisedCourse = random.choice(list(courseDict.values()))
if userDict.get(randomisedCourse.get_userID()).get_status() == "Good":
recommendCourseList.append(randomisedCourse)
break
else:
courseDict.pop(randomisedCourse.get_courseID())
except:
print("No course found.")
else:
# choosing three random course objects
print("User has not watched any tags or has watched an equal balance of various tags.")
try:
while len(recommendCourseList) != 3:
randomisedCourse = random.choice(list(courseDict.values()))
if userDict.get(randomisedCourse.get_userID()).get_status() == "Good":
if randomisedCourse not in recommendCourseList:
recommendCourseList.append(randomisedCourse)
else:
# if course has been recommended already
courseDict.pop(randomisedCourse.get_courseID())
else:
# if teacher has been banned
courseDict.pop(randomisedCourse.get_courseID())
except:
print("No courses found.")
recommendedCourseListByHighestTag = []
# checking current length of the recommendCourseList if the length is less than 3, then adding courses to make it a length of 3
courseListLen = len(recommendCourseList)
if courseListLen == 0: # condition will be true when the user has two unique highest tags
recommendedCourseListBySecondHighestTag = []
for courseObject in list(courseDict.values()):
courseTag = courseObject.get_tag()
if courseTag == highestWatchedByTag:
if userDict.get(courseObject.get_userID()).get_status() == "Good":
recommendedCourseListByHighestTag.append(courseObject)
else:
# if the teacher of the course has been banned
courseDict.pop(courseObject.get_courseID())
elif courseTag == secondHighestWatchedByTag:
if userDict.get(courseObject.get_userID()).get_status() == "Good":
recommendedCourseListBySecondHighestTag.append(courseObject)
else:
# if the teacher of the course has been banned
courseDict.pop(courseObject.get_courseID())
# appending course object for recommendations
count = 0
print("Courses available: ", len(recommendedCourseListByHighestTag))
HighestTagCoursesAvailable = len(recommendedCourseListByHighestTag)
if HighestTagCoursesAvailable >= 2:
courseOne, courseTwo = random.sample(recommendedCourseListByHighestTag, 2)
recommendCourseList.append(courseOne)
recommendCourseList.append(courseTwo)
print("Two courses picked accordingly to user's highly watched tag.")
# picks one course for recommendations according to the user's second highly watched tag
SecondHighestTagCoursesAvailable = len(recommendedCourseListBySecondHighestTag)
print("Courses available: ", SecondHighestTagCoursesAvailable)
if SecondHighestTagCoursesAvailable >= 1:
randomisedCourse = random.choice(recommendedCourseListBySecondHighestTag)
recommendCourseList.append(randomisedCourse)
print("One course picked accordingly to user's second highly watched tag.")
elif HighestTagCoursesAvailable == 1:
# if there is only one course according to the user's highly watched tag (possibly due to a lack of courses, the teacher deleting the course, or the teacher being banned)
# recommends 1 course according to the user's highly watched tag
course = recommendedCourseListByHighestTag[0]
recommendCourseList.append(course)
print("One course picked accordingly to user's highly watched tag.")
SecondHighestTagCoursesAvailable = len(recommendedCourseListBySecondHighestTag)
print("Courses available: ", SecondHighestTagCoursesAvailable)
if SecondHighestTagCoursesAvailable >= 2:
randomisedCourseOne, randomisedCourseTwo = random.sample(recommendedCourseListBySecondHighestTag, 2)
recommendCourseList.append(randomisedCourseOne)
recommendCourseList.append(randomisedCourseTwo)
print("Two courses picked accordingly to user's second highly watched tag.")
elif SecondHighestTagCoursesAvailable == 1:
course = recommendedCourseListBySecondHighestTag[0]
recommendCourseList.append(course)
print("One course picked accordingly to user's second highly watched tag.")
else:
# if there is only no courses according to the user's highly watched tag (possibly due to a lack of courses, the teacher deleting the course, or the teacher being banned)
# recommends 2 courses according to the user's second highly watched tag
SecondHighestTagCoursesAvailable = len(recommendedCourseListBySecondHighestTag)
print("Courses available: ", SecondHighestTagCoursesAvailable)
if SecondHighestTagCoursesAvailable >= 2:
randomisedCourseOne, randomisedCourseTwo = random.sample(recommendedCourseListBySecondHighestTag, 2)
recommendCourseList.append(randomisedCourseOne)
recommendCourseList.append(randomisedCourseTwo)
print("Two courses picked accordingly to user's second highly watched tag.")
elif SecondHighestTagCoursesAvailable == 1:
course = recommendedCourseListBySecondHighestTag[0]
recommendCourseList.append(course)
print("One course picked accordingly to user's second highly watched tag.")
elif courseListLen == 1: # condition will be true when the user has one unique highest tag
for courseObject in list(courseDict.values()):
courseTag = courseObject.get_tag()
if courseTag == highestWatchedByTag:
if (userDict.get(courseObject.get_userID()).get_status() == "Good") and (courseObject not in recommendCourseList):
recommendedCourseListByHighestTag.append(courseObject)
else:
# if the teacher of the course has been banned or has already been recommended
courseDict.pop(courseObject.get_courseID())
print("Courses available: ", len(recommendedCourseListByHighestTag))
HighestTagCoursesAvailable = len(recommendedCourseListByHighestTag)
if HighestTagCoursesAvailable >= 2:
courseOne, courseTwo = random.sample(recommendedCourseListByHighestTag, 2)
recommendCourseList.append(courseOne)
recommendCourseList.append(courseTwo)
print("Two courses picked accordingly to user's highly watched tag.")
elif HighestTagCoursesAvailable == 1:
# if there is only one course according to the user's highly watched tag (possibly due to a lack of courses, the teacher deleting the course, or the teacher being banned)
# recommends 1 course according to the user's highly watched tag
course = recommendedCourseListByHighestTag[0]
recommendCourseList.append(course)
print("One course picked accordingly to user's highly watched tag.")
# in the event where there is insufficient tags to recommend, it will randomly choose another course object
recommendLen = len(recommendCourseList)
if recommendLen != 3:
print("Retrieving random courses as recommendations...")
while recommendLen != 3:
try:
randomisedCourse = random.choice(list(courseDict.values()))
except:
break
if userDict.get(randomisedCourse.get_userID()).get_status() == "Good":
if randomisedCourse not in recommendCourseList:
recommendCourseList.append(randomisedCourse)
recommendLen = len(recommendCourseList)
else:
# if course has been recommended already
courseDict.pop(randomisedCourse.get_courseID())
else:
# if the teacher of the course has been banned
courseDict.pop(randomisedCourse.get_courseID())
else:
print("Not enough courses to personalise the recommendations...")
for value in courseDict.values():
if userDict.get(value.get_userID()).get_status() == "Good":
recommendCourseList.append(value)
# retrieving course teacher's username
recommedationDict = {}
for courses in recommendCourseList:
teacherObject = userDict.get(courses.get_userID())
teacherUsername = teacherObject.get_username()
recommedationDict[courses] = teacherUsername
return render_template("users/general/home.html", accType="Guest", trendingCourseDict=trendingDict, recommendCourseDict=recommedationDict, trendingCourseLen=len(trendingCourseList), recommendCourseLen=len(recommendCourseList))
# for setting a cookie for the guest for content personalisation
@app.route('/set_cookies')
@limiter.limit("10/second")
def guestCookies():
res = make_response(redirect(url_for("home")))
cookieCreated = False
if "sessionCookieCreated" in session:
cookieCreated = session["sessionCookieCreated"]
print("Retrieved session cookie.")
else:
print("Guest user had disabled cookie.")
if not request.cookies.get("guestSeenTags") and cookieCreated:
# encoding the cookie value with base64 such that the guest cannot replace the cookie with tampered values in the dictionary too easily
res.set_cookie(
"guestSeenTags",
value=b64encode(json.dumps({"Programming": 0,
"Web_Development": 0,
"Game_Development": 0,
"Mobile_App_Development": 0,
"Software_Development": 0,
"Other_Development": 0,
"Entrepreneurship": 0,
"Project_Management": 0,
"BI_Analytics": 0,
"Business_Strategy": 0,
"Other_Business": 0,
"3D_Modelling": 0,
"Animation": 0,
"UX_Design": 0,
"Design_Tools": 0,
"Other_Design": 0,
"Digital_Photography": 0,
"Photography_Tools": 0,
"Video_Production": 0,
"Video_Design_Tools": 0,
"Other_Photography_Videography": 0,
"Science": 0,
"Math": 0,
"Language": 0,
"Test_Prep": 0,
"Other_Academics": 0}).encode("utf-8")),
expires=datetime.now() + timedelta(days=90)
)
if not request.cookies.get("guestSeenTags") and cookieCreated == False:
return redirect("/home/no_cookies") # if the user had disabled cookies
return res
@app.route('/home/no_cookies')
def homeNoCookies():
if "userSession" not in session and "adminSession" not in session: # since if the user is logged in, it means that their cookie is enabled as the login uses session cookies
courseDict = {}
userDict = {}
try:
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "r")
courseDict = db['Courses']
userDict = db['Users']
db.close()
print("File found.")
except:
print("File could not be found.")
# since the shelve files could not be found, it will create a placeholder/empty shelve files
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "c")
db["Courses"] = courseDict
db['Users'] = userDict
db.close()
# for trending algorithm
trendingCourseList = []
count = 0
try:
courseDictCopy = courseDict.copy()
while count != 3:
highestViewedCourse = max(courseDictCopy, key=lambda courseID: courseDictCopy[courseID].get_views())
# retrieve teacher user ID
courseTeacherID = courseDict.get(highestViewedCourse).get_userID()
# based on the teacher user ID and check if the teacher is banned
if userDict.get(courseTeacherID).get_status() == "Good":
print("Username:", userDict.get(courseTeacherID).get_username() )
print("User status:", userDict.get(courseTeacherID).get_status() )
# append course object if the teacher is not banned
trendingCourseList.append(courseDict.get(highestViewedCourse))
courseDictCopy.pop(highestViewedCourse)
count += 1
else:
# remove the course object from the courseDictCopy if the teacher is banned
courseDictCopy.pop(highestViewedCourse)
except:
print("No courses or not enough courses (requires 3 courses)")
trendingCourseList = []
for values in courseDict.values():
if userDict.get(values.get_userID()).get_status() == "Good":
trendingCourseList.append(values)
# for retrieving the teacher's username
trendingDict = {}
for courses in trendingCourseList:
teacherObject = userDict.get(courses.get_userID())
teacherUsername = teacherObject.get_username()
trendingDict[courses] = teacherUsername
recommendCourseDict = get_random_courses(courseDict)
return render_template("users/general/home.html", accType="Guest", trendingCourseDict=trendingDict, recommendCourseDict=recommendCourseDict, trendingCourseLen=len(trendingCourseList), recommendCourseLen=len(recommendCourseDict))
else:
return redirect(url_for("home"))
"""End of Home pages by Jason"""
"""User login and logout by Jason"""
@app.route('/login', methods=['GET', 'POST'])
@limiter.limit("10/second") # to prevent attackers from trying to crack passwords or doing enumeration attacks by sending too many automated requests from their ip address
def userLogin():
if "userSession" not in session and "adminSession" not in session:
create_login_form = Forms.CreateLoginForm(request.form)
if request.method == "POST" and create_login_form.validate():
emailInput = sanitise(create_login_form.email.data.lower())
passwordInput = create_login_form.password.data
userDict = {}
try:
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "r")
userDict = db['Users']
db.close()
print("File found.")
except:
print("File could not be found.")
# since the shelve files could not be found, it will create a placeholder/empty shelve files so that user can submit the login form but will still be unable to login
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "c")
db["Users"] = userDict
db.close()
# Declaring the 4 variables below to prevent UnboundLocalError
email_found = False
password_matched = False
emailShelveData = ""
# Checking the email input and see if it matches with any in the database
print("Retrieving emails from database.")
for key in userDict:
emailShelveData = userDict[key].get_email()
if emailInput == emailShelveData:
emailKey = userDict[key]
email_found = True
print("Email in database:", emailShelveData)
print("Email Input:", emailInput)
break
# if the email is found in the shelve database, it will then validate the password input and see if it matches with the one in the database
if email_found:
password_matched = emailKey.verify_password(passwordInput)
# printing for debugging purposes
if password_matched:
print("Correct password!")
else:
print("Password incorrect.")
else:
print("User email not found.")
if email_found and password_matched:
print("User validated...")
# checking if the user is banned
accGoodStatus = emailKey.get_status()
if accGoodStatus == "Good":
# setting the user session based on the user's user ID
userID = emailKey.get_user_id()
if bool(emailKey.get_otp_setup_key()):
session["2FAUserSession"] = (userID, "login")
return redirect(url_for("twoFactorAuthentication"))
else:
session["userSession"] = userID
print("User account not banned, login successful.")
return redirect(url_for("home"))
else:
flash("Your account have been banned. Please contact us if you think that this was a mistake.", "Danger")
print("User account banned.")
return render_template('users/guest/login.html', form=create_login_form)
else:
flash("Please check your entries and try again.", "Danger")
return render_template('users/guest/login.html', form=create_login_form)
else:
return render_template('users/guest/login.html', form=create_login_form)
else:
return redirect(url_for("home"))
@app.route('/logout')
def logout():
if "userSession" in session or "adminSession" in session:
session.clear()
else:
return redirect(url_for("home"))
flash("You have successfully logged out.", "You have logged out!")
return redirect(url_for("home"))
"""End of User login and logout by Jason"""
"""2FA by Jason"""
@app.route('/2FA', methods=['GET', 'POST'])
@limiter.limit("10/second") # to prevent attackers from trying to crack passwords or doing enumeration attacks by sending too many automated requests from their ip address
def twoFactorAuthenticationSetup():
if "userSession" in session:
userSession = session["userSession"]
userDict = {}
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "c")
try:
if 'Users' in db:
userDict = db['Users']
else:
db.close()
print("User data in shelve is empty.")
session.clear()
return redirect(url_for("home"))
except:
db.close()
print("Error in retrieving Users from user.db")
return redirect(url_for("home"))
# retrieving the object based on the shelve files using the user's user ID
userKey, userFound, accGoodStatus, accType = get_key_and_validate(userSession, userDict)
if userFound and accGoodStatus:
create_2fa_form = Forms.twoFAForm(request.form)
qrCodePath = "".join(["static/images/qrcode/", userSession, ".png"])
qrCodeFullPath = Path(app.root_path).joinpath(qrCodePath)
if request.method == "POST" and create_2fa_form.validate():
secret = request.form.get("secret")
otpInput = sanitise(create_2fa_form.twoFAOTP.data)
isValid = pyotp.TOTP(secret).verify(otpInput)
print(pyotp.TOTP(secret).now())
if isValid:
userKey.set_otp_setup_key(secret)
flash(Markup("2FA setup was successful!<br>You will now be prompted to enter your Google Authenticator's time-based OTP every time you login."), "2FA setup successful!")
db["Users"] = userDict
db.close()
qrCodeFullPath.unlink(missing_ok=True) # missing_ok argument is set to True as the file might not exist (>= Python 3.8)
return redirect(url_for("userProfile"))
else:
db.close()
flash("Invalid OTP Entered! Please try again!")
return redirect(url_for("twoFactorAuthenticationSetup"))
else:
db.close()
secret = pyotp.random_base32() # for google authenticator setup key
imagesrcPath = retrieve_user_profile_pic(userKey)
if accType == "Teacher":
teacherUID = userSession
else:
teacherUID = ""
# Get shopping cart len
shoppingCartLen = len(userKey.get_shoppingCart())
qrCodeForOTP = pyotp.totp.TOTP(s=secret, digits=6).provisioning_uri(name=userKey.get_username(), issuer_name='CourseFinity')
img = qrcode.make(qrCodeForOTP)
qrCodeFullPath.unlink(missing_ok=True) # missing_ok argument is set to True as the file might not exist (>= Python 3.8)
img.save(qrCodeFullPath)
return render_template('users/loggedin/2fa.html', shoppingCartLen=shoppingCartLen, accType=accType, imagesrcPath=imagesrcPath, teacherUID=teacherUID, form=create_2fa_form, secret=secret, qrCodePath=qrCodePath)
else:
db.close()
print("User not found or is banned")
session.clear()
return redirect(url_for("userLogin"))
else:
if "adminSession" in session:
return redirect(url_for("home"))
else:
return redirect(url_for("userLogin"))
@app.route('/2FA_disable')
@limiter.limit("10/second") # to prevent attackers from trying to crack passwords or doing enumeration attacks by sending too many automated requests from their ip address
def removeTwoFactorAuthentication():
if "userSession" in session:
userSession = session["userSession"]
userDict = {}
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "c")
try:
if 'Users' in db:
userDict = db['Users']
else:
db.close()
print("User data in shelve is empty.")
session.clear()
return redirect(url_for("home"))
except:
db.close()
print("Error in retrieving Users from user.db")
return redirect(url_for("home"))
# retrieving the object based on the shelve files using the user's user ID
userKey, userFound, accGoodStatus, accType = get_key_and_validate(userSession, userDict)
if userFound and accGoodStatus:
userKey.set_otp_setup_key("")
flash(Markup("2FA has been disabled.<br>You will no longer be prompted to enter your Google Authenticator's time-based OTP upon loggin in."), "2FA disabled!")
db["Users"] = userDict
db.close()
return redirect(url_for("userProfile"))
else:
db.close()
print("User not found or is banned")
session.clear()
return redirect(url_for("userLogin"))
else:
if "adminSession" in session:
return redirect(url_for("home"))
else:
return redirect(url_for("userLogin"))
@app.route('/2FA_required', methods=['GET', 'POST'])
@limiter.limit("10/second") # to prevent attackers from trying to bruteforce the 2FA
def twoFactorAuthentication():
# checks if the user is not logged in
if "userSession" not in session and "adminSession" not in session:
# for admin login
if "adminOTPSession" in session:
userID, originFeature = session["adminOTPSession"]
adminDict = {}
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\admin", "c")
try:
if 'Admins' in db:
adminDict = db['Admins']
db.close()
else:
db.close()
print("User data in shelve is empty.")
session.clear()
return redirect(url_for("home"))
except:
db.close()
print("Error in retrieving Users from user.db")
return redirect(url_for("home"))
userKey, userFound, accActive = admin_get_key_and_validate(userID, adminDict)
if userFound and accActive:
if bool(userKey.get_otp_setup_key()):
create_2fa_form = Forms.twoFAForm(request.form)
if request.method == "POST" and create_2fa_form.validate():
otpInput = sanitise(create_2fa_form.twoFAOTP.data)
secret = userKey.get_otp_setup_key()
isValid = pyotp.TOTP(secret).verify(otpInput)
if isValid:
# requires 2FA time-based OTP to be entered when user is logging in
if originFeature == "adminLogin":
session.pop("2FAUserSession", None)
session["adminSession"] = userID
return redirect(url_for("home"))
else:
session.clear()
return redirect(url_for("home"))
else:
flash("Invalid OTP Entered! Please try again!")
return render_template("users/guest/enter_2fa.html", form=create_2fa_form)
else:
return render_template("users/guest/enter_2fa.html", form=create_2fa_form)
else:
print("Unexpected Error: User had disabled 2FA.")
return redirect(url_for("userLogin"))
else:
print("User not found or is inactive")
session.clear()
return redirect(url_for("adminLogin"))
# for user login
elif "2FAUserSession" in session:
userID, originFeature = session["2FAUserSession"]
userDict = {}
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "c")
try:
if 'Users' in db:
userDict = db['Users']
db.close()
else:
db.close()
print("User data in shelve is empty.")
session.clear()
return redirect(url_for("home"))
except:
db.close()
print("Error in retrieving Users from user.db")
return redirect(url_for("home"))
userKey, userFound, accGoodStatus, accType = get_key_and_validate(userID, userDict)
if userFound and accGoodStatus:
if bool(userKey.get_otp_setup_key()):
create_2fa_form = Forms.twoFAForm(request.form)
if request.method == "POST" and create_2fa_form.validate():
otpInput = sanitise(create_2fa_form.twoFAOTP.data)
secret = userKey.get_otp_setup_key()
isValid = pyotp.TOTP(secret).verify(otpInput)
if isValid:
# requires 2FA time-based OTP to be entered when user is logging in
if originFeature == "login":
session.pop("2FAUserSession", None)
session["userSession"] = userID
return redirect(url_for("home"))
else:
session.clear()
return redirect(url_for("home"))
else:
flash("Invalid OTP Entered! Please try again!")
return render_template("users/guest/enter_2fa.html", form=create_2fa_form)
else:
return render_template("users/guest/enter_2fa.html", form=create_2fa_form)
else:
print("Unexpected Error: User had disabled 2FA.")
return redirect(url_for("userLogin"))
else:
print("User not found or is banned")
session.clear()
return redirect(url_for("userLogin"))
else:
return redirect(url_for("home"))
else:
return redirect(url_for("home"))
"""End of 2FA by Jason"""
"""Reset Password by Jason"""
@app.route('/reset_password', methods=['GET', 'POST'])
def requestPasswordReset():
if "userSession" not in session and "adminSession" not in session:
create_request_form = Forms.RequestResetPasswordForm(request.form)
if request.method == "POST" and create_request_form.validate():
emailInput = sanitise(create_request_form.email.data.lower())
userDict = {}
try:
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "r")
userDict = db['Users']
db.close()
print("File found.")
fileFound = True
except:
print("File could not be found.")
fileFound = False
# since the shelve files could not be found, it will create a placeholder/empty shelve files so that user can submit the login form but will still be unable to login
db = shelve.open(app.config["DATABASE_FOLDER"] + "\\user", "c")
db["Users"] = userDict
db.close()
if fileFound:
# Declaring the 2 variables below to prevent UnboundLocalError
email_found = False
emailShelveData = ""
# Checking the email input and see if it matches with any in the database
print("Retrieving emails from database.")
for key in userDict:
emailShelveData = userDict[key].get_email()
if emailInput == emailShelveData:
emailKey = userDict[key]
email_found = True
print("Email in database:", emailShelveData)
print("Email Input:", emailInput)
break
if email_found:
print("User email found...")
# checking if the user is banned
accGoodStatus = emailKey.get_status()
if accGoodStatus == "Good":
try: