-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathapp.py
More file actions
1101 lines (912 loc) · 38.1 KB
/
Copy pathapp.py
File metadata and controls
1101 lines (912 loc) · 38.1 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 os
from datetime import datetime, timedelta
from sqlite import SQLite
from flask import (
Flask,
flash,
render_template,
request,
redirect,
session,
Response,
jsonify,
)
from flask_session import Session
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
import pyotp
from additional import (
gen_id,
login_required,
stat,
file_check,
encrypt,
decrypt,
validate_alias,
jsonfy,
csvfy,
textify,
totp_generator,
totpCode,
totp_verify,
qrTObasecode,
)
app = Flask(__name__)
# Connect to SQLITE3 Database
db = SQLite("clipbin.db")
# Custom Filter JINJA
app.jinja_env.filters["stat"] = stat
# Configure Flask, Login Session Cache
app.config["MAX_CONTENT_LENGTH"] = 1.5 * 1024 * 1024
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.secret_key = os.environ.get("SECRET_KEY")
time = {
"day": timedelta(days=1),
"week": timedelta(weeks=1),
"twoweek": timedelta(weeks=2),
"month": timedelta(weeks=4),
"half": timedelta(weeks=26),
"year": timedelta(weeks=52),
}
alias = [
"clip",
"login",
"register",
"about",
"api",
"dashboard",
"settings",
"update",
"delete",
"terms",
"feedback",
]
# Set Login Data
def loginData():
login = False
name = ""
try:
if int(session["user_id"]):
login = True
name = session["uname"]
except KeyError:
login = False
return [login, name]
def twoFACheck(user_id=None):
if user_id is None:
if "user_id" not in session:
return False
user_id = session["user_id"]
data = db.execute("SELECT uri FROM twoFA WHERE user_id=?", user_id)
if not data:
return False
else:
return data[0]["uri"]
def render_totp_template(totp_secret, qr_b64):
return render_template("totp_setup.html", totp_secret=totp_secret, qr_code=qr_b64, dat=loginData())
# Server-Side Year PreProcessor
@app.context_processor
def inject_year():
return {"this_year": datetime.now().year}
# Error Handling 404
@app.errorhandler(404)
def error_404(code):
return render_template("error.html", code="404 Not Found!"), 404
# Error Handling 405
@app.errorhandler(405)
def error_405(code):
return render_template("error.html", code="405 Method Not Allowed!"), 405
# Error Handling 500
@app.errorhandler(500)
def error_500(code):
return render_template("error.html", code="500 Internal Server Error!"), 500
# Error Handling 413
@app.errorhandler(413)
def error_413(code):
return render_template("error.html", code="413 Content Too Large!"), 413
# Initialize session after error handlers
Session(app)
# Main Index Function
@app.route("/", methods=["GET", "POST"])
def index():
post_id = gen_id()
is_editable = 0
is_unlisted = 0
if request.method == "POST":
name = request.form.get("clip_name")
text_raw = request.form.get("clip_text")
text = str(text_raw).strip() if text_raw else ""
passwd_raw = request.form.get("clip_passwd")
passwd = str(passwd_raw) if passwd_raw else ""
editable = request.form.get("clip_edit")
unlist = request.form.get("clip_disp")
custom_alias = request.form.get("clip_alias")
remove_time = request.form.get("clip_delete")
custom_delete = request.form.get("clip_custom_delete")
file = request.files.get("clip_file")
if custom_alias:
custom_alias = custom_alias.strip()
if custom_alias in alias:
flash("Alias cannot be one of the Primary Routes.")
return redirect("/")
if not validate_alias(custom_alias):
flash("Alias must be 4-12 characters long and contain only letters, numbers, hyphens and underscores!")
return redirect("/")
check = db.execute("SELECT clip_url from clips WHERE clip_url=?", custom_alias)
if len(check) != 0:
flash("This alias is already taken!")
return redirect("/")
post_id = custom_alias
if editable:
is_editable = 1
if unlist:
is_unlisted = 1
if text and file and file.filename:
flash("Cannot upload both Text and File together!")
return redirect("/")
if not text and (not file or not file.filename):
flash("Text Field or File Cannot be Empty!")
return redirect("/")
if text and not name:
flash("Title Cannot be Empty!")
return redirect("/")
if file and file.filename:
if file_check(file.filename):
text = str(file.read().decode("utf-8"))
else:
flash("File Not Allowed!")
return redirect("/")
if not name:
name = secure_filename(file.filename)
if editable:
is_editable = 1
if unlist:
is_unlisted = 1
check = db.execute("SELECT clip_url from clips WHERE clip_url=?", post_id)
if len(check) != 0:
if not custom_alias:
post_id = gen_id()
else:
flash("This alias is already taken!")
return redirect("/")
if remove_time:
if remove_time == "never":
remove_time = None
elif remove_time == "custom" and custom_delete:
try:
hours = int(custom_delete)
remove_time = (datetime.now() + timedelta(hours=hours)).strftime("%d-%m-%Y %H:%M:%S")
except ValueError:
flash("Invalid custom delete time.")
return redirect("/")
else:
remove_time = (time[remove_time] + datetime.now()).strftime("%d-%m-%Y %H:%M:%S")
cur_time = datetime.now().strftime("%d-%m-%Y @ %H:%M:%S")
if not passwd:
db.execute(
"INSERT INTO clips (clip_url, clip_name, clip_text, is_editable, is_unlisted, clip_time, delete_time) VALUES (?, ?, ?, ?, ?, ?, ?)",
str(post_id),
name,
text,
is_editable,
is_unlisted,
cur_time,
remove_time,
)
else:
pwd = generate_password_hash(passwd, method="scrypt")
text = encrypt(text.encode(), passwd)
db.execute(
"INSERT INTO clips (clip_url, clip_name, clip_text, clip_pwd, is_editable, is_unlisted, clip_time, delete_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
str(post_id),
name,
text,
pwd,
is_editable,
is_unlisted,
cur_time,
remove_time,
)
if loginData()[0]:
uid = db.execute("SELECT id FROM users WHERE username=?", loginData()[1])[0]["id"]
cid = db.execute("SELECT id FROM clips WHERE clip_url=?", str(post_id))[0]["id"]
db.execute("INSERT INTO clipRef (userid, clipid) VALUES (?, ?)", int(uid), int(cid))
return redirect(f"/{post_id}")
else:
return render_template("index.html", dat=loginData())
# Show CLIP Function
@app.route("/<clip_url_id>", methods=["GET", "POST"])
@app.route("/clip/<clip_url_id>", methods=["GET", "POST"])
def clip(clip_url_id):
data = db.execute(
"SELECT clip_name, clip_text, clip_time, clip_pwd, is_editable, update_time, delete_time FROM clips WHERE clip_url=?",
clip_url_id,
)
passwd = ""
is_editable = False
is_owner = False
if len(data) != 0:
# Check for ownership if a user is logged in
if loginData()[0]:
user_id = session.get("user_id")
if user_id:
owner_check = db.execute(
"SELECT C.id FROM clipRef R JOIN clips C ON C.id = R.clipid WHERE R.userid = ? AND C.clip_url = ?",
user_id,
clip_url_id,
)
if len(owner_check) > 0:
is_owner = True
text = data[0]["clip_text"]
name = data[0]["clip_name"]
time = data[0]["clip_time"]
passwd = data[0]["clip_pwd"]
editable = data[0]["is_editable"]
updated = data[0]["update_time"]
remove_time = data[0]["delete_time"]
time_left = ""
if remove_time:
if datetime.strptime(remove_time, "%d-%m-%Y %H:%M:%S") < datetime.now():
db.execute("DELETE FROM clips WHERE clip_url=?", clip_url_id)
return (
render_template("error.html", code="This Clip was Expired.", dat=loginData()),
404,
)
time_left = datetime.strptime(remove_time, "%d-%m-%Y %H:%M:%S") - datetime.now()
if time_left.days < 1:
seconds = time_left.seconds
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
time_left = f"{hours}h {minutes}m"
else:
time_left = f"{time_left.days} days"
if editable == 1:
is_editable = True
if passwd and request.method != "POST":
return render_template("clip.html", passwd=True, url_id=clip_url_id, dat=loginData())
elif request.method == "POST":
clip_passwd = request.form.get("clip_passwd")
if check_password_hash(passwd, clip_passwd):
text = decrypt(text, clip_passwd).decode()
return render_template(
"clip.html",
url_id=clip_url_id,
name=name,
text=text,
time=time,
edit=is_editable,
is_owner=is_owner,
update=updated,
time_left=time_left,
passwd2=passwd,
dat=loginData(),
)
else:
return render_template(
"clip.html",
passwd=True,
error="Incorrect Password!",
url_id=clip_url_id,
dat=loginData(),
)
else:
text = str(text)
return render_template(
"clip.html",
url_id=clip_url_id,
name=name,
text=text,
time=time,
edit=is_editable,
is_owner=is_owner,
update=updated,
time_left=time_left,
dat=loginData(),
)
else:
return (
render_template("error.html", code="That was not found on this server.", dat=loginData()),
404,
)
# Show Raw
@app.route("/<clip_url_id>/raw", methods=["GET", "POST"])
@app.route("/clip/<clip_url_id>/raw", methods=["GET", "POST"])
def clipraw(clip_url_id):
data = db.execute(
"SELECT clip_text, clip_pwd, delete_time FROM clips WHERE clip_url=?",
clip_url_id,
)
passwd = ""
if len(data) != 0:
text = data[0]["clip_text"]
passwd = data[0]["clip_pwd"]
remove_time = data[0]["delete_time"]
if remove_time:
if datetime.strptime(remove_time, "%d-%m-%Y %H:%M:%S") < datetime.now():
db.execute("DELETE FROM clips WHERE clip_url=?", clip_url_id)
return Response("This Clip was Expired.", mimetype="text/plain"), 404
if passwd and request.method != "POST":
return Response(
f"This Clip is Password Protected. Send a POST request at the url {request.url} with parameter passwd=<your_password>\n"
f'Example Request: curl -d "passwd=<your_password>" -X POST {request.url}\n',
mimetype="text/plain",
)
elif request.method == "POST":
clip_passwd = request.form.get("passwd")
if check_password_hash(passwd, clip_passwd):
text = decrypt(text, clip_passwd).decode()
return text, {"Content-Type": "text/plain"}
else:
return Response("Incorrect Password!\n", mimetype="text/plain")
else:
text = str(text)
return text, {"Content-Type": "text/plain"}
else:
return (
Response("That was not found on this server.\n", mimetype="text/plain"),
404,
)
# Search Function
@app.route("/clip", methods=["GET", "POST"])
def search():
if request.method == "POST":
clip_info = request.form.get("clip_info")
if not clip_info:
return render_template("search.html", error="Search Field cannot be empty!", dat=loginData())
info = str("%" + clip_info + "%")
data = db.execute(
"SELECT clip_name, clip_url, clip_time FROM clips WHERE clip_url LIKE ? AND is_unlisted!=1 OR clip_name LIKE ? AND is_unlisted!=1",
info,
info,
)
if len(data) != 0:
return render_template("search.html", data=data, dat=loginData())
return render_template("search.html", error="Nothing was found!", dat=loginData())
return render_template("search.html", dat=loginData())
# Render About Page
@app.route("/about", methods=["GET"])
def about():
return render_template("about.html", dat=loginData())
# Test route for 405 error testing (only used in tests)
@app.route("/test-405", methods=["GET"])
def test_405():
return "Test route for 405 error", 200
# Update Function
@app.route("/update/<url_id>", methods=["GET", "POST"])
@login_required
def update(url_id):
if loginData()[0]:
data = db.execute(
"SELECT clips.id, clips.is_editable, clips.clip_pwd, clips.clip_text "
"FROM clipRef JOIN clips ON clips.id = clipRef.clipid "
"WHERE clipRef.userid=? AND clips.clip_URL=?",
session["user_id"],
url_id,
)
if not data:
return render_template("error.html", code="You cannot edit this clip!")
if data[0]["is_editable"] != 1:
return render_template("error.html", code="Editing disabled for this clip")
clip_id = data[0]["id"]
clip_pwd = data[0]["clip_pwd"]
old_text = data[0]["clip_text"]
if request.method == "POST":
if request.form.get("clip_text") is None:
flash("No content submitted")
return redirect(f"/{url_id}")
new_text = str(request.form.get("clip_text")).strip()
if clip_pwd:
clip_pass = str(request.form.get("clip_passwd"))
if not clip_pass:
flash("Password required to update this protected clip.")
return redirect(f"/{url_id}")
if not check_password_hash(clip_pwd, clip_pass):
flash("Incorrect password!")
return redirect(f"/{url_id}")
try:
old_plain = decrypt(old_text, clip_pass).decode()
except Exception as e:
flash("Failed to decrypt old content.")
return redirect(f"/{url_id}")
if old_plain != new_text:
new_text = encrypt(new_text.encode(), clip_pass)
cur_time = datetime.now().strftime("%d-%m-%Y @ %H:%M:%S")
db.execute(
"UPDATE clips SET clip_text=?, update_time=? WHERE id=?",
new_text,
cur_time,
clip_id,
)
flash("Clip has been updated")
else:
if old_text != new_text:
cur_time = datetime.now().strftime("%d-%m-%Y @ %H:%M:%S")
db.execute(
"UPDATE clips SET clip_text=?, update_time=? WHERE id=?",
new_text,
cur_time,
clip_id,
)
flash("Clip has been updated")
return redirect(f"/{url_id}")
return render_template("error.html", code="Invalid edit request")
return redirect("/login")
# Delete Function
@app.route("/delete/<url_id>")
@login_required
def delete(url_id):
if loginData()[0]:
data = db.execute(
"SELECT clips.id FROM clipRef JOIN clips ON clips.id = clipRef.clipid WHERE clipRef.userid=? AND clips.clip_URL=?",
session["user_id"],
url_id,
)
if len(data) != 0:
db.execute("DELETE FROM clips WHERE id=?", data[0]["id"])
return redirect("/dashboard")
else:
return render_template("error.html", code="Cannot Delete this Clip!")
return redirect("/login")
# Download Function -> File
@app.route("/download/<url_id>", methods=["GET", "POST"])
def download(url_id):
data = db.execute("SELECT clip_text, clip_name, clip_pwd FROM clips WHERE clip_url=? ", url_id)
# HOT FIX
if len(data) == 0:
return render_template("error.html", code="404 Not Found!"), 404
text = str(data[0]["clip_text"])
name = data[0]["clip_name"]
passwd = data[0]["clip_pwd"]
if not file_check(name):
name = name + ".txt"
if passwd and request.method != "POST":
return render_template("passwd.html", url_id=url_id)
# This is the new, corrected code
elif request.method == "POST":
clip_passwd = request.form.get("clip_passwd")
if check_password_hash(passwd, clip_passwd):
return Response(
text,
mimetype="text/plain",
headers={"Content-disposition": f"attachment; filename={name}"},
)
# FIX: Decrypt the content before sending it in the response.
decrypted_text = decrypt(data[0]["clip_text"], clip_passwd).decode("utf-8")
return Response(
decrypted_text,
mimetype="text/plain",
headers={"Content-disposition": f"attachment; filename={name}"},
)
else:
return render_template("passwd.html", error="Incorrect Password!", url_id=url_id)
return Response(
text,
mimetype="text/plain",
headers={"Content-disposition": f"attachment; filename={name}"},
)
# Login Function
@app.route("/login", methods=["GET", "POST"])
def login():
session.clear()
if request.method == "POST":
# Handle both 'uname' and 'username' field names for compatibility
uname = request.form.get("uname") or request.form.get("username")
# Handle both 'passwd' and 'password' field names for compatibility
passwd = request.form.get("passwd") or request.form.get("password")
if not uname and not passwd:
flash("Username and Password Cannot be Empty!")
return render_template("login.html", dat=loginData(), reg=True)
if not uname:
flash("Username Cannot be Empty!")
if not passwd:
flash("Password Cannot be Empty!")
if uname and passwd:
data = db.execute("SELECT * FROM users WHERE username=?", uname)
if len(data) != 0:
if check_password_hash(data[0]["password"], passwd):
twofa_enabled = twoFACheck(data[0]["id"])
session["user_id"] = data[0]["id"]
session["uname"] = uname
if not twofa_enabled:
return redirect("/")
else:
return redirect("/login/totp")
else:
flash("Incorrect Username or Password!")
return render_template("login.html", dat=loginData(), reg=True)
else:
flash("Account Not Found!")
return render_template("login.html", dat=loginData(), reg=True)
# TOTP Function
@app.route("/login/totp", methods=["GET", "POST"])
@login_required
def totp():
if "user_id" not in session or "uname" not in session:
flash("Session expired. Please log in again.")
return redirect("/login")
user_id = session["user_id"]
uname = session["uname"]
twofa_data = twoFACheck(user_id)
if not twofa_data:
flash("2FA not set up for this account.")
return redirect("/login")
if request.method == "POST":
user_code = request.form.get("totp")
if not user_code:
flash("TOTP code cannot be empty!")
return render_template("totp.html", dat=loginData())
# FIX: Extract the encrypted secret from the database result
data = db.execute("SELECT uri FROM twoFA WHERE user_id =?", user_id)
if not data:
flash("2FA data not found!")
return redirect("/login")
encrypted_secret = data[0]["uri"] # This should be the actual bytes
totp_secret = totpCode(encrypted_secret=encrypted_secret, user_id=user_id, username=uname)
# Verify the TOTP code
totp = pyotp.TOTP(totp_secret)
if totp.verify(user_code):
session["user_id"] = user_id
session["uname"] = uname
return redirect("/")
else:
flash("Invalid TOTP code!")
return render_template("totp.html", dat=loginData())
return render_template("totp.html", dat=loginData())
@app.route("/login/totp/<mode>", methods=["GET", "POST"])
@login_required
def totp_manage(mode):
if "user_id" not in session or "uname" not in session:
flash("Session expired. Please log in again.")
return redirect("/login")
user_id = session["user_id"]
uname = session["uname"]
mode = mode.lower().strip()
if mode not in ("setup", "resync"):
flash("Invalid 2FA action.")
return redirect("/settings")
encrypted_uri = twoFACheck(user_id=user_id)
if mode == "setup" and not encrypted_uri:
if "temp_totp_secret" not in session:
encrypted_uri, provisioning_uri = totp_generator(user_id, uname)
session["temp_totp_secret"] = encrypted_uri
else:
encrypted_uri = session["temp_totp_secret"]
totp_secret = totpCode(encrypted_uri, user_id, uname)
provisioning_uri = pyotp.TOTP(totp_secret).provisioning_uri(name=uname, issuer_name="Clipbin")
success_msg = "2FA setup successful!"
elif mode == "setup" and encrypted_uri:
totp_secret = totpCode(encrypted_uri, user_id, uname)
provisioning_uri = pyotp.TOTP(totp_secret).provisioning_uri(name=uname, issuer_name="Clipbin")
success_msg = "2FA already enabled."
else:
if not encrypted_uri:
flash("Two-Factor Authentication is disabled.")
return redirect("/settings")
session.pop("temp_totp_secret", None)
totp_secret = totpCode(encrypted_uri, user_id, uname)
provisioning_uri = pyotp.TOTP(totp_secret).provisioning_uri(name=uname, issuer_name="Clipbin")
success_msg = "2FA resynced successfully!"
qr_b64 = qrTObasecode(provisioning_uri)
if mode == "setup" and "temp_totp_secret" in session:
otp_secret = totpCode(session["temp_totp_secret"], user_id, uname)
else:
otp_secret = totpCode(encrypted_uri, user_id, uname)
totp = pyotp.TOTP(otp_secret)
if request.method == "POST":
user_code = request.form.get("totp", "").strip()
if not user_code:
return render_totp_template(otp_secret, qr_b64)
if mode == "setup" and "temp_totp_secret" in session:
is_valid = totp_verify(session["temp_totp_secret"], user_id, uname, user_code)
else:
is_valid = totp_verify(encrypted_uri, user_id, uname, user_code)
if is_valid:
if mode == "setup" and "temp_totp_secret" in session:
db.execute("INSERT INTO twoFA (user_id, uri) VALUES (?, ?)", user_id, session["temp_totp_secret"])
session.pop("temp_totp_secret")
print(session)
return jsonify({"status": "success", "message": success_msg, "redirect": "/"})
else:
return jsonify(
{"status": "error", "message": f"Invalid TOTP code! {totp.now()} secret:{session['temp_totp_secret']}"}
)
return render_totp_template(otp_secret, qr_b64)
# Logout Function
@app.route("/logout")
def logout():
session.clear()
return redirect("/")
# 2FA permission
@app.route("/permission", methods=["POST"])
@login_required
def permission():
twofa_action = request.form.get("2fa_action")
password = request.form.get("password")
if not password:
flash("Password cannot be empty!")
return redirect("/settings")
user = db.execute("SELECT * FROM users WHERE id=?", session["user_id"])
if not user or not check_password_hash(user[0]["password"], password):
flash("Incorrect password!")
return redirect("/settings")
# Handle Enable / Disable / Resync Actions
if twofa_action == "enable":
flash("Please complete 2FA setup with your authenticator app.")
return redirect("/login/totp/setup")
elif twofa_action == "disable":
db.execute("DELETE FROM twoFA WHERE user_id=?", session["user_id"])
flash("2FA has been disabled successfully.")
return redirect("/settings")
elif twofa_action == "resync":
flash("Password verified. Please resynchronize your TOTP device.")
return redirect("/login/totp/resync")
else:
flash("Invalid 2FA action selected.")
return redirect("/settings")
# Registration Function
@app.route("/register", methods=["GET", "POST"])
def register():
session.clear()
if request.method == "POST":
# Handle both 'uname' and 'username' field names for compatibility
uname = request.form.get("uname") or request.form.get("username")
# Handle both 'passwd' and 'password' field names for compatibility
passwd = request.form.get("passwd") or request.form.get("password")
conf = request.form.get("passwdconf") or request.form.get("password_confirm")
# If no confirmation provided, use password (for API/test
# compatibility)
if conf is None:
conf = passwd
if not uname:
return render_template("register.html", error="Username cannot be empty!", dat=loginData())
name = db.execute("SELECT username FROM users WHERE username=?", uname)
if len(name) != 0:
return render_template("register.html", error="This username already exists!", dat=loginData())
if not passwd:
return render_template("register.html", error="Password cannot be empty!")
if not conf:
return render_template("register.html", error="Password Confirmation is required!", dat=loginData())
if passwd != conf:
return render_template("register.html", error="Passwords do not match!", dat=loginData())
db.execute(
"INSERT INTO users (username, password) VALUES (?, ?)",
uname,
generate_password_hash(passwd, method="scrypt"),
)
return redirect("/login")
return render_template("register.html", dat=loginData())
# Dashboard Function
@app.route("/dashboard")
@app.route("/dashboard/")
@login_required
def dashboard():
loginData()[1]
data = db.execute(
"SELECT clips.clip_name, clips.clip_url, clips.clip_time, clips.is_editable, clips.is_unlisted FROM clipRef JOIN clips ON clips.id = clipRef.clipid JOIN users ON users.id = clipRef.userid WHERE users.username=?",
session["uname"],
)
return render_template("dash.html", dat=loginData(), data=data)
# Settings Route
@app.route("/settings", methods=["GET", "POST"])
@login_required
def settings():
twoFA_enabled = bool(twoFACheck())
if request.method == "POST":
old_pass = str(request.form.get("old_passwd"))
new_pass = str(request.form.get("new_passwd"))
conf_pass = str(request.form.get("conf_passwd"))
if not old_pass:
flash("Enter your Old Password.")
return render_template("settings.html", dat=loginData(), user_2fa_enabled=twoFA_enabled)
if not new_pass:
flash("Enter your New Password.")
return render_template("settings.html", dat=loginData(), user_2fa_enabled=twoFA_enabled)
if not conf_pass:
flash("Confirm your New Password.")
return render_template("settings.html", dat=loginData(), user_2fa_enabled=twoFA_enabled)
if conf_pass != new_pass:
flash("New Password not Confirmed. Does not Match.")
return render_template("settings.html", dat=loginData(), user_2fa_enabled=twoFA_enabled)
if new_pass == old_pass:
flash("New Password cannot be same as Old Password.")
return render_template("settings.html", dat=loginData(), user_2fa_enabled=twoFA_enabled)
data = db.execute("SELECT password FROM users WHERE id=? AND username=?", session["user_id"], session["uname"])
if data and check_password_hash(data[0]["password"], old_pass):
db.execute(
"UPDATE users SET password=? WHERE id=? AND username=?",
generate_password_hash(new_pass, method="scrypt"),
session["user_id"],
session["uname"],
)
flash("Password Updated!")
return render_template("settings.html", dat=loginData(), user_2fa_enabled=twoFA_enabled)
flash("Old Password Does Not Match.")
return render_template("settings.html", dat=loginData(), user_2fa_enabled=twoFA_enabled)
return render_template("settings.html", dat=loginData(), user_2fa_enabled=twoFA_enabled)
# Export Data Function -> File
@app.route("/settings/export", methods=["POST", "GET"])
@login_required
def exportdata():
if request.method == "POST":
ext = request.form.get("export_ext")
data = db.execute(
"SELECT clips.clip_url AS id, clips.clip_name AS name, clips.clip_text AS text, clips.clip_time AS time FROM clipRef JOIN clips ON clips.id = clipRef.clipid JOIN users ON users.id = clipRef.userid WHERE users.username=? AND clips.clip_pwd IS NULL",
session["uname"],
)
if len(data) != 0:
if ext == "json":
return Response(
jsonfy(data),
mimetype="text/json",
headers={
"Content-disposition": f'attachment; filename={session["uname"]}_export.json',
"Content-Type": "application/json; charset=utf-8",
},
)
elif ext == "csv":
return Response(
csvfy(data),
mimetype="text/csv",
headers={"Content-disposition": f'attachment; filename={session["uname"]}_export.csv'},
)
elif ext == "text":
return Response(
textify(data),
mimetype="text/plain",
headers={"Content-disposition": f'attachment; filename={session["uname"]}_export.txt'},
)
return render_template("error.html", code="Nothing to Export!")
return render_template("error.html", code="Nothing to Export!")
# API Get Function
@app.route("/api/get_data")
def get_data():
clip_id = request.args.get("id")
clip_name = request.args.get("name")
clip_alias = request.args.get("alias")
clip_pass = request.args.get("pwd")
unlisted = request.args.get("unlisted")
data = {}
# If no parameters provided, return empty list instead of error
if not clip_id and not clip_name and not clip_alias:
return jsonify([])
if clip_name and unlisted == "true":
return jsonify({"Message": "To Search, enter Id not Name with unlisted!"}), 400
if clip_name:
clip_name = "%" + clip_name + "%"
# Handle alias parameter
if clip_alias:
clip_id = clip_alias # Use alias as ID for searching
if not clip_pass:
if unlisted == "true" and clip_id:
data = db.execute(
"SELECT clip_url, clip_name, clip_text, clip_time, delete_time, clip_pwd FROM clips WHERE (clip_url LIKE ?) AND is_unlisted == 1 AND clip_pwd IS NULL",
str(clip_id),
)
else:
data = db.execute(
"SELECT clip_url, clip_name, clip_text, clip_time, delete_time, clip_pwd FROM clips WHERE (clip_url LIKE ? OR clip_name LIKE ?) AND is_unlisted != 1 AND clip_pwd IS NULL",
str(clip_id),
clip_name,
)
else:
if unlisted == "true" and clip_id:
data = db.execute(
"SELECT clip_url, clip_name, clip_text, clip_time, delete_time, clip_pwd FROM clips WHERE (clip_url LIKE ?) AND is_unlisted == 1",
str(clip_id),
)
else:
data = db.execute(
"SELECT clip_url, clip_name, clip_text, clip_time, delete_time, clip_pwd FROM clips WHERE (clip_url LIKE ? OR clip_name LIKE ?) AND is_unlisted != 1",
str(clip_id),
clip_name,
)
if len(data) != 0:
for i in data:
if i["delete_time"]:
if datetime.strptime(i["delete_time"], "%d-%m-%Y %H:%M:%S") < datetime.now():
db.execute("DELETE FROM clips WHERE clip_url=?", i["clip_url"])
data.remove(i)
data_list = []
if len(data) != 0:
if data[0]["clip_pwd"] is not None:
if not check_password_hash(data[0]["clip_pwd"], clip_pass):
return jsonify({"Error": "Incorrect Password"}), 401
for i in data:
data_dict = {}
data_dict["id"] = i["clip_url"]
data_dict["name"] = i["clip_name"]
text = i["clip_text"]
if isinstance(text, bytes):
data_dict["text"] = decrypt(text, clip_pass).decode()
else:
data_dict["text"] = text
data_dict["time"] = i["clip_time"]
data_list.append(data_dict)
return jsonify(data_list)
return jsonify({"Error": "No Data"}), 404