forked from Bitwise-01/Notebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notebook.py
993 lines (741 loc) · 26.6 KB
/
notebook.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
# Date: 02/08/2019
# Author: Mohamed
# Description: A secure notebook
import os
import sys
from time import time
from flask_wtf import CSRFProtect
from datetime import timedelta, datetime
from lib.cipher import get_random_bytes, CryptoAES
from lib.database.database import Account, Profile
from lib.const import (
SessionConst,
CredentialConst,
ProfileConst,
PermissionConst,
)
from flask import (
Flask,
flash,
render_template,
request,
session,
jsonify,
redirect,
url_for,
)
from markupsafe import escape
# app
if getattr(sys, "frozen", False):
path = os.path.abspath(".")
if not os.path.exists("database"):
os.mkdir(os.path.join(path, "database"))
static_folder = os.path.join(path, "static")
template_folder = os.path.join(path, "templates")
app = Flask(
__name__, template_folder=template_folder, static_folder=static_folder
)
else:
app = Flask(__name__)
app.config["SECRET_KEY"] = get_random_bytes(0x20)
app.permanent_session_lifetime = timedelta(
minutes=SessionConst.SESSION_TTL.value
)
# Protection against CSRF attack
csrf = CSRFProtect(app)
csrf.init_app(app)
# databases
account_db = Account()
profile_db = Profile()
# core functions
def login_required(func):
def wrapper(*args, **kwargs):
if not "logged_in" in session:
return redirect(url_for("index"))
elif not session["logged_in"]:
return redirect(url_for("index"))
else:
return func(*args, **kwargs)
wrapper.__name__ = func.__name__
return wrapper
def permission_required(func):
def wrapper(*args, **kwargs):
if session["access_level"] == PermissionConst.NONE.value:
return redirect(url_for("index"))
return func(*args, **kwargs)
wrapper.__name__ = func.__name__
return wrapper
def admin_required(func):
def wrapper(*args, **kwargs):
if session["access_level"] != PermissionConst.ROOT.value:
return redirect(url_for("admin"))
return func(*args, **kwargs)
wrapper.__name__ = func.__name__
return wrapper
def invalid_username(username):
if len(username) < CredentialConst.MIN_USERNAME_LENGTH.value:
return "Username must be at least {} characters long".format(
CredentialConst.MIN_USERNAME_LENGTH.value
)
if len(username) > CredentialConst.MAX_USERNAME_LENGTH.value:
return "Username must not be longer than {} characters".format(
CredentialConst.MAX_USERNAME_LENGTH.value
)
if username.isdigit():
return "Username must contain a letter"
if not username[0].isalpha():
return "Username must start with a letter"
if [_ for _ in username if not _.isdigit() and not _.isalpha()]:
return "Username must not contain special characters"
def invalid_password(username, password, confirm):
if password != confirm:
return "Passwords do not match"
if len(password) < CredentialConst.MIN_PASSWORD_LENGTH.value:
return "Password must be at least {} characters long".format(
CredentialConst.MIN_PASSWORD_LENGTH.value
)
if len(password) > CredentialConst.MAX_PASSWORD_LENGTH.value:
return "Password must not be longer than {} characters".format(
CredentialConst.MAX_PASSWORD_LENGTH.value
)
if not " " in password:
return "Password must contain at least 1 space character"
if password[0] == " " or password[-1] == " ":
return "Password must not start or end with a space character"
if password[-1].isdigit():
return "Password must not end with a number"
if not [_ for _ in password if _.isalpha() if _ == _.upper()]:
return "Password must contain at least 1 capital letter"
if (
"".join([_ for _ in username if _.isalpha()]).lower()
in password.lower()
):
return "Password must not contain your username"
def get_user_key():
user_id = session["user_id"]
master_key = session["master_key"]
encrypted_user_key = account_db.get_encrypted_user_key(user_id)
decrypted_user_key = CryptoAES.decrypt(encrypted_user_key, master_key)
return decrypted_user_key
def create_topic(topic_name, time_stamp):
user_key = get_user_key()
user_id = session["user_id"]
topic_name = topic_name.strip()
return profile_db.add_topic(user_id, user_key, topic_name, time_stamp)
def get_topics():
user_key = get_user_key()
user_id = session["user_id"]
return profile_db.decrypt_topics(user_id, user_key)
def create_note(topic_id, note_title, time_stamp):
user_key = get_user_key()
note_title = note_title.strip()
return profile_db.add_note(topic_id, user_key, note_title, "", time_stamp)
def get_notes(topic_id):
user_key = get_user_key()
return profile_db.decrypt_notes(topic_id, user_key)
def delete_usr(user_id):
if (
user_id == session["user_id"]
and session["access_level"] == PermissionConst.ROOT.value
):
if account_db.get_admin() == 1:
# sorry, I can't allow you to do that
return False
account_db.delete_account(user_id)
profile_db.delete_account(user_id)
return True
# endpoints
@app.before_request
def single_browser():
if not "logged_in" in session:
return
if not session["logged_in"]:
return
if (time() - session["last_checked"]) < 1.5:
return
user_id = session["user_id"]
session_token = session["token"]
session["last_checked"] = time()
if not account_db.is_logged_in(user_id, session_token):
logout()
@app.route("/settings")
@login_required
def settings():
return render_template("settings.html", PermissionConst=PermissionConst)
@app.route("/updateusername", methods=["POST"])
@login_required
def update_username():
resp = {"msg": "Username Changed Successfully", "resp_code": -1}
if not "username" in request.form:
resp["msg"] = "Incomplete form"
return jsonify(resp)
username = escape(request.form["username"].strip().lower())
username_error = invalid_username(username)
if username_error:
resp["msg"] = username_error
return jsonify(resp)
if account_db.account_exists(username):
resp["msg"] = "Username already exists"
return jsonify(resp)
user_id = session["user_id"]
account_db.update_username(user_id, username)
resp["resp_code"] = 0
return jsonify(resp)
@app.route("/updatepassword", methods=["POST"])
@login_required
def update_password():
resp = {"msg": "Password Changed Successfully", "resp_code": -1}
if not (
"old" in request.form
and "new" in request.form
and "conf" in request.form
):
resp["resp"] = "Incomplete form"
return jsonify(resp)
old_password = escape(request.form["old"].strip())
new_password = escape(request.form["new"].strip())
confirm_password = escape(request.form["conf"].strip())
if (
(len(old_password) > CredentialConst.MAX_PASSWORD_LENGTH.value)
or (len(new_password) > CredentialConst.MAX_PASSWORD_LENGTH.value)
or (new_password != confirm_password)
):
resp["msg"] = "Password must not be longer than {} characters".format(
CredentialConst.MAX_PASSWORD_LENGTH.value
)
return jsonify(resp)
user_id = session["user_id"]
if not account_db.compare_passwords(user_id, old_password):
resp["msg"] = "Check your current password field"
return jsonify(resp)
username = account_db.get_user_name(user_id)
password_error = invalid_password(username, new_password, confirm_password)
if password_error:
resp["msg"] = password_error
return jsonify(resp)
if account_db.compare_passwords(user_id, new_password):
resp["msg"] = "You are already using that password"
return jsonify(resp)
new_master_key = account_db.update_password(
user_id, old_password, new_password
)
session["master_key"] = new_master_key
resp["resp_code"] = 0
return jsonify(resp)
# topic
@app.route("/createtopic", methods=["POST"])
@login_required
def createtopic():
resp = {"topic_id": "", "date_created": "", "resp": "error-msg"}
if not ("topic_name" in request.form and "time_stamp" in request.form):
return jsonify(resp)
timestamp = request.form["time_stamp"]
if not timestamp.isdigit():
return jsonify(resp)
current_time = int(timestamp) / 1000
try:
datetime.fromtimestamp(current_time)
except:
return jsonify(resp)
topic_name = escape(request.form["topic_name"].strip())
topic_len = len(topic_name)
if (topic_len < ProfileConst.MIN_TOPIC_LENGTH.value) or (
topic_len > ProfileConst.MAX_TOPIC_LENGTH.value
):
return jsonify(resp)
if (
profile_db.get_total_topics(session["user_id"])
>= ProfileConst.MAX_TOPICS.value
):
return jsonify(resp)
resp["resp"] = "success-msg"
resp["topic_id"], resp["date_created"] = create_topic(
topic_name, current_time
)
return jsonify(resp)
@app.route("/gettopics", methods=["POST"])
@login_required
def gettopics():
resp = {"topics": []}
resp["topics"] = get_topics()
return jsonify(resp)
@app.route("/topic")
@login_required
def gettopic():
if not "id" in request.args:
return render_template("topic.html", PermissionConst=PermissionConst)
user_id = session["user_id"]
user_key = get_user_key()
topic_id = escape(request.args.get("id"))
if not profile_db.topic_exists(user_id, topic_id):
return render_template("topic.html", PermissionConst=PermissionConst)
topic = profile_db.decrypt_topic(topic_id, user_key)
return render_template(
"topic.html", topic=topic, PermissionConst=PermissionConst
)
@app.route("/settings/topic")
@login_required
def settings_topic():
if not "topic_id" in request.args:
return redirect(url_for("index"))
user_id = session["user_id"]
user_key = get_user_key()
topic_id = escape(request.args.get("topic_id"))
if not profile_db.topic_exists(user_id, topic_id):
return redirect(url_for("index"))
topic = profile_db.decrypt_topic(topic_id, user_key, get_notes=False)
return render_template(
"settingstopic.html", topic=topic, PermissionConst=PermissionConst
)
@app.route("/settings/topic/update", methods=["POST"])
@login_required
def update_topic():
resp = {"resp": "error-msg"}
if not ("topic_id" in request.form and "modified_name" in request.form):
return jsonify(resp)
modified_name = escape(request.form["modified_name"].strip())
topic_id = escape(request.form["topic_id"].strip())
modified_name_len = len(modified_name)
user_id = session["user_id"]
user_key = get_user_key()
if (
(modified_name_len < ProfileConst.MIN_TOPIC_LENGTH.value)
or (modified_name_len > ProfileConst.MAX_TOPIC_LENGTH.value)
or not (profile_db.topic_exists(user_id, topic_id))
):
return jsonify(resp)
profile_db.modify_topic(topic_id, user_key, modified_name)
resp["resp"] = "success-msg"
return jsonify(resp)
@app.route("/settings/topic/delete", methods=["POST"])
@login_required
def delete_topic():
resp = {"resp": "error-msg"}
if not "topic_id" in request.form:
return jsonify(resp)
user_id = session["user_id"]
topic_id = escape(request.form["topic_id"].strip())
if not profile_db.topic_exists(user_id, topic_id):
return jsonify(resp)
profile_db.delete_topic(topic_id)
resp["resp"] = "success-msg"
return jsonify(resp)
# note
@app.route("/createnote", methods=["POST"])
@login_required
def createnote():
resp = {"note_id": "", "date_created": "", "resp": "error-msg"}
if not (
"topic_id" in request.form
and "note_title" in request.form
and "time_stamp" in request.form
):
return jsonify(resp)
if (
profile_db.get_total_notes(session["user_id"])
>= ProfileConst.MAX_NOTES.value
):
return jsonify(resp)
note_title = escape(request.form["note_title"].strip())
topic_id = escape(request.form["topic_id"].strip())
timestamp = escape(request.form["time_stamp"])
note_len = len(note_title)
if (note_len < ProfileConst.MIN_NOTE_LENGTH.value) or (
note_len > ProfileConst.MAX_NOTE_LENGTH.value
):
return jsonify(resp)
if not timestamp.isdigit():
return jsonify(resp)
current_time = int(timestamp) / 1000
try:
datetime.fromtimestamp(current_time)
except:
return jsonify(resp)
resp["resp"] = "success-msg"
resp["note_id"], resp["date_created"] = create_note(
topic_id, note_title, current_time
)
return jsonify(resp)
@app.route("/getnotes", methods=["POST"])
@login_required
def getnotes():
resp = {"notes": []}
if not "topic_id" in request.form:
return jsonify(resp)
topic_id = escape(request.form["topic_id"].strip())
if not len(topic_id):
return jsonify(resp)
resp["notes"] = get_notes(topic_id)
return jsonify(resp)
@app.route("/note", methods=["GET"])
@login_required
def get_note():
if not ("topic_id" in request.args and "note_id" in request.args):
return redirect(url_for("index"))
user_id = session["user_id"]
topic_id = escape(request.args.get("topic_id"))
note_id = escape(request.args.get("note_id"))
if not (
profile_db.topic_exists(user_id, topic_id)
and profile_db.note_exists(topic_id, note_id)
):
return redirect(url_for("index"))
user_key = get_user_key()
topic = profile_db.decrypt_topic(topic_id, user_key, False)
topic_info = {"topic_id": topic_id, "topic_name": topic["topic_name"]}
note = dict(topic_info, **profile_db.decrypt_note(note_id, user_key))
return render_template(
"note.html", note=note, PermissionConst=PermissionConst
)
@app.route("/save", methods=["POST"])
@login_required
def save_note():
resp = {"resp": "success-msg"}
if not (
"topic_id" in request.form
and "note_id" in request.form
and "content" in request.form
):
return jsonify(resp)
user_id = session["user_id"]
user_key = get_user_key()
note_id = escape(request.form["note_id"].strip())
topic_id = escape(request.form["topic_id"].strip())
note_content = escape(request.form["content"].strip())
if not (
profile_db.topic_exists(user_id, topic_id)
and profile_db.note_exists(topic_id, note_id)
):
return jsonify(resp)
profile_db.modify_note_content(topic_id, note_id, note_content, user_key)
return jsonify(resp)
@app.route("/modify", methods=["POST"])
@login_required
def modify_note():
resp = {"resp": "error-msg"}
if not (
"topic_id" in request.form
and "note_id" in request.form
and "modified_title" in request.form
):
return jsonify(resp)
note_title = escape(request.form["modified_title"])
modified_title_len = len(note_title)
topic_id = escape(request.form["topic_id"])
note_id = escape(request.form["note_id"])
user_id = session["user_id"]
user_key = get_user_key()
if (
(modified_title_len < ProfileConst.MIN_NOTE_LENGTH.value)
or (modified_title_len > ProfileConst.MAX_NOTE_LENGTH.value)
or not profile_db.topic_exists(user_id, topic_id)
or not profile_db.note_exists(topic_id, note_id)
):
return jsonify(resp)
profile_db.modify_note_title(topic_id, note_id, note_title, user_key)
resp["resp"] = "success-msg"
return jsonify(resp)
@app.route("/delete", methods=["POST"])
@login_required
def delete_note():
resp = {"resp": "error-msg"}
if not ("topic_id" in request.form and "note_id" in request.form):
return jsonify(resp)
user_id = session["user_id"]
note_id = escape(request.form["note_id"])
topic_id = escape(request.form["topic_id"])
if not (
profile_db.topic_exists(user_id, topic_id)
and profile_db.note_exists(topic_id, note_id)
):
return jsonify(resp)
profile_db.delete_note(topic_id, note_id)
resp["resp"] = "success-msg"
return jsonify(resp)
@app.route("/session_check", methods=["POST"])
@login_required
def session_check():
return jsonify({"resp": 0})
# admin
@app.route("/admin")
@login_required
@permission_required
def admin():
users = []
stats = {"total_users": 0, "total_topics": 0, "total_notes": 0}
for row in account_db.get_users():
user_id = row[0]
ip_address = account_db.get_ip_address(user_id)
permission = account_db.get_access_level(user_id)
last_online = account_db.get_last_online(user_id)
date_created = account_db.get_date_created(user_id)
username = account_db.get_user_name(user_id).title()
permission = (
"Admin"
if permission == PermissionConst.ROOT.value
else "View Only"
if permission == PermissionConst.VIEW.value
else "User"
)
total_notes = profile_db.get_total_notes(user_id)
total_topics = profile_db.get_total_topics(user_id)
stats["total_users"] += 1
stats["total_notes"] += total_notes
stats["total_topics"] += total_topics
users.append(
{
"user_id": user_id,
"username": username,
"ip_address": ip_address,
"access_level": permission,
"last_online": last_online,
"total_notes": total_notes,
"date_created": date_created,
"total_topics": total_topics,
}
)
stats["total_users"] = "{:02,}".format(stats["total_users"])
stats["total_notes"] = "{:02,}".format(stats["total_notes"])
stats["total_topics"] = "{:02,}".format(stats["total_topics"])
return render_template("admin.html", users=users, stats=stats)
@app.route("/edit_user")
@login_required
@admin_required
def edit_user():
if not "id" in request.args:
return redirect(url_for("admin"))
user_id = escape(request.args.get("id"))
if not account_db.user_id_exists(user_id):
return redirect(url_for("admin"))
user = {}
user["user_id"] = user_id
permission = account_db.get_access_level(user_id)
user["ip_address"] = account_db.get_ip_address(user_id)
user["last_online"] = account_db.get_last_online(user_id)
user["date_created"] = account_db.get_date_created(user_id)
user["username"] = account_db.get_user_name(user_id).title()
user["total_notes"] = "{:02,}".format(profile_db.get_total_notes(user_id))
user["total_topics"] = "{:02,}".format(
profile_db.get_total_topics(user_id)
)
user["access_level"] = (
"Admin"
if permission == PermissionConst.ROOT.value
else "View Only"
if permission == PermissionConst.VIEW.value
else "User"
)
return render_template(
"adminedit.html", user=user, PermissionConst=PermissionConst
)
@app.route("/update_access", methods=["POST"])
@login_required
@admin_required
def update_access():
resp = {"resp": "error-msg"}
if not ("user_id" in request.form and "access_id" in request.form):
return jsonify(resp)
user_id = escape(request.form["user_id"])
access_id = escape(request.form["access_id"])
if not account_db.user_id_exists(user_id):
return jsonify(resp)
if not access_id.isdigit():
return jsonify(resp)
access_id = int(access_id)
if (
access_id != PermissionConst.ROOT.value
and access_id != PermissionConst.VIEW.value
and access_id != PermissionConst.NONE.value
):
return jsonify(resp)
if access_id == account_db.get_access_level(user_id):
return jsonify(resp)
if user_id == session["user_id"]:
if account_db.get_admin() == 1:
# sorry, I can't allow you to do that
return jsonify(resp)
resp["resp"] = "success-msg"
account_db.update_permission(user_id, access_id)
account_db.logout(user_id)
return jsonify(resp)
@app.route("/logout_user", methods=["POST"])
@login_required
@admin_required
def logout_user():
resp = {"resp": "error"}
if not "user_id" in request.form:
return jsonify(resp)
user_id = escape(request.form["user_id"])
if not account_db.user_id_exists(user_id):
return jsonify(resp)
resp["resp"] = "success"
account_db.logout(user_id)
return jsonify(resp)
@app.route("/delete_user", methods=["POST"])
@login_required
@admin_required
def delete_user():
resp = {"resp": "error"}
if not "user_id" in request.form:
return jsonify(resp)
user_id = escape(request.form["user_id"])
if not account_db.user_id_exists(user_id):
return jsonify(resp)
if delete_usr(user_id):
resp["resp"] = "success"
return jsonify(resp)
@app.route("/")
def index():
if not "logged_in" in session:
session["logged_in"] = False
return render_template("index.html")
if not session["logged_in"]:
username = session.get("username")
username = username if username else ""
if username:
session.pop("username")
return render_template("index.html", username=username)
last_active_timestamp = session["last_active"]
return render_template(
"home.html",
PermissionConst=PermissionConst,
lastActiveTimestamp=last_active_timestamp,
)
@app.route("/signup", methods=["GET", "POST"])
def signup():
if "logged_in" in session:
if session["logged_in"]:
return redirect(url_for("index"))
if request.method == "GET":
return render_template(
"register.html",
min_password_length=CredentialConst.MIN_PASSWORD_LENGTH.value,
max_password_length=CredentialConst.MAX_PASSWORD_LENGTH.value,
)
form = request.form
if not ("username" in form and "password" in form and "confirm" in form):
flash("Incomplete form", "error")
return render_template(
"register.html",
min_password_length=CredentialConst.MIN_PASSWORD_LENGTH.value,
max_password_length=CredentialConst.MAX_USERNAME_LENGTH.value,
)
username, password, confirm = (
escape(form["username"].strip()),
escape(form["password"]),
escape(form["confirm"]),
)
creds = {
"username": username,
"password": password,
"confirm": confirm if confirm == password else "",
"success": 0,
}
if not (username and password and confirm):
flash("Incomplete form", category="error")
return render_template(
"register.html",
data=creds,
min_password_length=CredentialConst.MIN_PASSWORD_LENGTH.value,
max_password_length=CredentialConst.MAX_USERNAME_LENGTH.value,
)
username_error = invalid_username(username)
if username_error:
flash(username_error, "error")
return render_template(
"register.html",
data=creds,
min_password_length=CredentialConst.MIN_PASSWORD_LENGTH.value,
max_password_length=CredentialConst.MAX_USERNAME_LENGTH.value,
)
if account_db.account_exists(username.lower()):
flash("{} already exists".format(username).format(username), "error")
return render_template(
"register.html",
data=creds,
min_password_length=CredentialConst.MIN_PASSWORD_LENGTH.value,
max_password_length=CredentialConst.MAX_USERNAME_LENGTH.value,
)
password_error = invalid_password(username, password, confirm)
if password_error:
flash(password_error, "error")
return render_template(
"register.html",
data=creds,
min_password_length=CredentialConst.MIN_PASSWORD_LENGTH.value,
max_password_length=CredentialConst.MAX_USERNAME_LENGTH.value,
)
creds["success"] = 1
session["logged_in"] = False
account_db.register(username, password.strip())
return render_template(
"register.html",
data=creds,
min_password_length=CredentialConst.MIN_PASSWORD_LENGTH.value,
max_password_length=CredentialConst.MAX_USERNAME_LENGTH.value,
)
@app.route("/login", methods=["GET", "POST"])
def login():
if not "logged_in" in session:
return redirect(url_for("index"))
if session["logged_in"]:
return redirect(url_for("index"))
if not (
"username" in request.form
and "password" in request.form
and "timestamp" in request.form
):
return jsonify(
{"is_authenticated": False, "msg": "Provide all requirements"}
)
username = escape(request.form["username"].strip())
password = escape(request.form["password"])
timestamp = escape(request.form["timestamp"])
if not timestamp.isdigit():
return jsonify({"is_authenticated": False, "msg": "Invalid timestamp"})
current_time = int(timestamp) / 1000
try:
datetime.fromtimestamp(current_time)
except:
return jsonify({"is_authenticated": False, "msg": "Invalid timestamp"})
if (
(len(password) > CredentialConst.MAX_PASSWORD_LENGTH.value)
or (len(username) > CredentialConst.MAX_USERNAME_LENGTH.value)
or (len(username) < CredentialConst.MIN_USERNAME_LENGTH.value)
):
return jsonify(
{"is_authenticated": False, "msg": "Account does not exist"}
)
session["username"] = username
ip_addr = request.headers.get("X-Forwarded-For")
account_data, err_msg = account_db.authenticate(
username, password, ip_addr, current_time
)
if not account_data:
return jsonify({"is_authenticated": False, "msg": err_msg})
user_id, master_key, token, last_active, access_level = account_data
session["token"] = token
session.permanent = True
session["logged_in"] = True
session["user_id"] = user_id
session["last_checked"] = time()
session["master_key"] = master_key
session["last_active"] = last_active
session["username"] = username.title()
session["access_level"] = access_level
return jsonify({"is_authenticated": True, "msg": ""})
@app.route("/delete_account", methods=["POST"])
@login_required
def delete_account():
user_id = session["user_id"]
if not delete_usr(user_id):
return jsonify({"resp": ""})
session.clear()
return jsonify({"resp": ""})
@app.route("/logout")
@login_required
def logout():
session.clear()
return redirect(url_for("index"))
if __name__ == "__main__":
app.run()