forked from opencodeiiita/PhotoStore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·844 lines (642 loc) · 24.5 KB
/
app.py
File metadata and controls
executable file
·844 lines (642 loc) · 24.5 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
#!/usr/bin/env python
# for system operations, file handling
import base64
import random
import string
import time
import os
from hashlib import md5
import mimetypes
from datetime import datetime
from pathlib import Path
from io import BytesIO
from PIL import Image, UnidentifiedImageError
# for HTTP server, web application
import json
from flask import (
Flask,
flash,
request,
redirect,
url_for,
jsonify,
render_template,
make_response,
render_template_string,
send_from_directory,
)
from werkzeug.exceptions import RequestEntityTooLarge
# we will be using hashes
# from werkzeug.utils import secure_filename
# to pretiffy the rendered HTML document
from flask_pretty import Prettify
# to sanitize input
import re
# for session tokens
import jwt
from jwt.exceptions import PyJWTError, ExpiredSignatureError
# for local database
from threading import Lock
from tinydb import TinyDB, Query
import tinydb.operations
# for authentication, CAPTCHA image
import bcrypt
from captcha.image import ImageCaptcha
# SECRETs
from secret import SECRET_KEY, CAPTCHA_KEY
# some bookkeeping
CWD = Path(os.path.dirname(__file__))
UPLOAD_FOLDER = CWD / "uploads"
ALLOWED_EXTENSIONS = {"jpg", "png", "svg", "jpeg"}
# flask app
app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["SECRET_KEY"] = SECRET_KEY
app.config["CAPTCHA_KEY"] = CAPTCHA_KEY
app.config["CAPTCHA_EXPIRE_SECONDS"] = 5 * 60 # 5 minutes
app.config["MAX_CONTENT_LENGTH"] = 1 * 1000 * 1000 # 1MB limit
app.config["DATABASE"] = "photostore.db"
app.config["USE_CAPTCHA"] = False
# for CAPTCHA
captcha = ImageCaptcha()
# for local database (this table is not used)
TinyDB.default_table_name = "photostore"
dbLock = Lock()
def allowed_file(filename):
return extension(filename).lower() in ALLOWED_EXTENSIONS
def extension(filename):
return "" if "." not in filename else filename.rsplit(".", 1)[1]
def validUsername(username):
return username and re.match(r"^[0-9A-Z_]{4,32}$", username, flags=re.I)
def isLoggedIn():
token = request.cookies.get("jwt")
jwtData = decodeFromJWT(token)
return bool(jwtData)
def encodeToJWT(data):
return jwt.encode(data, key=app.config["SECRET_KEY"], algorithm="HS256")
def decodeFromJWT(token):
jwtData = {}
try:
jwtData = jwt.decode(token, key=app.config["SECRET_KEY"], algorithms=["HS256"])
# except PyJWTError:
except Exception as exc:
pass
return jwtData
def generateCaptcha():
captcha_length = random.choice(range(6, 11))
captcha_value = "".join(
[random.choice(string.ascii_lowercase) for _ in range(captcha_length)]
)
captcha_image = captcha.generate_image(captcha_value)
captcha_buffer = BytesIO()
captcha_image.save(captcha_buffer, format="PNG")
captcha_base64 = base64.b64encode(captcha_buffer.getvalue()).decode("latin1")
captcha_timestamp = int(time.time())
captcha_expiry = captcha_timestamp + app.config["CAPTCHA_EXPIRE_SECONDS"]
captcha_salt = bcrypt.gensalt(rounds=12)
captcha_code = (str(captcha_expiry) + captcha_value).encode("latin")
captcha_hash = bcrypt.hashpw(captcha_code, captcha_salt).decode("latin1")
captcha_jwt = jwt.encode(
{"hash": captcha_hash, "exp": captcha_expiry},
key=app.config["CAPTCHA_KEY"],
algorithm="HS256",
)
return (captcha_value, captcha_base64, captcha_hash, captcha_jwt)
def verifyCaptcha(captcha_answer, token):
captcha_result = {"valid": False, "expired": False}
if not captcha_answer:
return captcha_result
jwtData = {}
try:
jwtData = jwt.decode(
token,
key=app.config["CAPTCHA_KEY"],
algorithms=["HS256"],
options={"verify_exp": True},
)
except ExpiredSignatureError:
captcha_result["expired"] = True
# except PyJWTError:
except Exception as exc:
pass
if jwtData:
captcha_hash = jwtData.get("hash").encode("latin1")
captcha_expiry = jwtData.get("exp")
captcha_code = (str(captcha_expiry) + captcha_answer).encode("latin1")
captcha_result["valid"] = bcrypt.checkpw(captcha_code, captcha_hash)
return captcha_result
@app.route("/")
def index():
loggedIn = isLoggedIn()
return render_template("index.html", loggedIn=loggedIn)
@app.route("/community")
def community():
loggedIn = isLoggedIn()
return render_template("community.html", visibility="public", loggedIn=loggedIn)
@app.route("/api/captcha")
def api_captcha():
captcha_value, captcha_base64, captcha_hash, captcha_jwt = generateCaptcha()
return jsonify({"b64": captcha_base64, "jwt": captcha_jwt})
@app.route("/api/image/list")
def api_image_list():
data = []
token = request.cookies.get("jwt")
jwtData = decodeFromJWT(token)
owner = jwtData.get("username")
forProfile = request.args.get("private", False)
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
data = []
images = db.table("images")
if forProfile and owner:
data += images.search(Query().owner == owner)
else:
data += images.search(Query().public == True)
# sort such that most recent images comes first
data.sort(key=lambda image: image["timestamp"], reverse=True)
data = [image.doc_id for image in data]
return jsonify(data)
@app.route("/api/image/get/<id>")
def api_image_get(id):
try:
id = int(id)
except ValueError:
id = None
if not id:
return "", 404
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
images = db.table("images")
image = images.get(doc_id=id)
if not image:
return "", 404
filename = image.get("filename")
if not filename:
return "", 404
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
if os.path.isfile(filepath):
return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
return "", 404
@app.route("/api/image/info/<id>")
def api_image_info(id):
try:
id = int(id)
except ValueError:
id = None
if not id:
return json.dumps(None), 404
image = None
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
images = db.table("images")
image = images.get(doc_id=id)
if not image:
return json.dumps(None), 404
public = image.get("public")
owner = image.get("owner")
filename = image.get("filename")
token = request.cookies.get("jwt")
jwtData = decodeFromJWT(token)
username = jwtData.get("username")
info = {
"date": str(datetime.fromtimestamp(image.get("timestamp"))),
"owner": owner,
"description": image.get("description"),
"public": public,
"likes": len(image.get("likes")),
"liked": username and username in image.get("likes"),
}
if public or owner == username:
return jsonify(info)
return json.dumps(None), 403
@app.route("/api/image/delete", methods=["POST"])
def api_image_delete():
try:
data = json.loads(request.data.decode("latin1"))
id = int(data.get("id"))
# except (JSONDecodeError, TypeError, ValueError):
except:
id = None
if not id:
return json.dumps(None), 404
image = None
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
images = db.table("images")
image = images.get(doc_id=id)
if not image:
return json.dumps(None), 404
public = image.get("public")
owner = image.get("owner")
filename = image.get("filename")
token = request.cookies.get("jwt")
jwtData = decodeFromJWT(token)
username = jwtData.get("username")
if owner == username:
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
if os.path.isfile(filepath):
os.remove(filepath)
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
accounts = db.table("accounts")
accounts.update(
tinydb.operations.decrement("uploads"),
Query().username == username,
)
images = db.table("images")
image = images.remove(doc_ids=[id])
return json.dumps(True), 200
else:
return json.dumps(None), 404
return json.dumps(False), 403
@app.route("/api/image/make_public", methods=["POST"])
def api_image_make_public():
try:
data = json.loads(request.data.decode("latin1"))
id = int(data.get("id"))
value = bool(data.get("value"))
# except (JSONDecodeError, TypeError, ValueError):
except:
id = None
value = False
if not id:
return json.dumps(None), 404
image = None
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
images = db.table("images")
image = images.get(doc_id=id)
if not image:
return json.dumps(None), 404
public = image.get("public")
owner = image.get("owner")
filename = image.get("filename")
token = request.cookies.get("jwt")
jwtData = decodeFromJWT(token)
username = jwtData.get("username")
if owner == username:
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
images = db.table("images")
images.update(tinydb.operations.set("public", value), doc_ids=[id])
return json.dumps(True), 200
return json.dumps(False), 403
@app.route("/api/image/like", methods=["POST"])
def api_image_like():
try:
data = json.loads(request.data.decode("latin1"))
id = int(data.get("id"))
value = bool(data.get("value"))
# except (JSONDecodeError, TypeError, ValueError):
except:
id = None
value = False
if not id:
return json.dumps(None), 404
token = request.cookies.get("jwt")
jwtData = decodeFromJWT(token)
username = jwtData.get("username")
if not username:
return json.dumps(False), 403
image = None
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
images = db.table("images")
image = images.get(doc_id=id)
if not image:
return json.dumps(None), 404
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
images = db.table("images")
image = images.get(doc_id=id)
likes = image.get("likes")
if value and username not in likes:
likes.append(username)
elif not value and username in likes:
likes.remove(username)
images.update(tinydb.operations.set("likes", likes), doc_ids=[id])
return json.dumps({"likes": len(likes)}), 200
return json.dumps(False), 403
@app.route("/avatar", methods=["GET", "POST"])
def avatar():
token = request.cookies.get("jwt")
jwtData = decodeFromJWT(token)
if not jwtData:
resp = make_response(redirect(url_for("login")))
resp.delete_cookie("jwt")
return resp
username = jwtData.get("username")
if request.method == "POST":
returnURL = request.headers.get("Referer", request.url)
file = None
try:
if "avatar" in request.files:
file = request.files["avatar"]
else:
flash("Invalid request!", "error")
except RequestEntityTooLarge as exc:
useragent = request.headers.get("User-Agent", "")
contentlength = request.headers.get("Content-Length", "")
sizelimit = app.config["MAX_CONTENT_LENGTH"]
errors = list(
map(
render_template_string,
[
"Woah! Your file is too powerful!",
f"User-Agent: {useragent}",
f"Content-Length: {contentlength}",
f"Size Limit: {sizelimit} bytes",
],
)
)
return render_template(
"layouts/error.html", errors=errors, returnURL=returnURL, loggedIn=True
)
else:
if file:
if not file.filename:
flash("No file selected!", "error")
else:
ext = extension(file.filename)
if allowed_file(file.filename):
# this will clear `file.stream`, so it will become empty
buffer = BytesIO(file.stream.read())
try:
image = Image.open(buffer)
# except PIL.UnidentifiedImageError:
except:
flash("Invalid image!", "error")
else:
# `extFromMIME` will be of the form `.EXT`
mimetype = image.get_format_mimetype()
extFromMIME = mimetypes.guess_extension(mimetype)
if allowed_file(extFromMIME):
size = image.size
# check if the avatar is square or not
if size[0] != size[1]:
flash("Uploaded image is not square!", "warning")
filename = f"avatar-{username}.png"
filepath = os.path.join(
app.config["UPLOAD_FOLDER"], filename
)
image.save(filepath, format="PNG")
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
accounts = db.table("accounts")
accounts.update(
tinydb.operations.set("avatar", filename),
Query().username == username,
)
flash("Avatar updated successfully!", "success")
else:
flash(f"Invalid mimetype: `{mimetype}`", "error")
else:
flash(f"Invalid file extension: `{ext}`", "error")
else:
flash("No file selected!", "error")
return redirect(returnURL)
return avatar_username(username)
@app.route("/avatar/<username>")
def avatar_username(username):
filename = None
if validUsername(username):
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
accounts = db.table("accounts")
account = accounts.get(Query().username == username)
if account:
filename = account.get("avatar")
if filename and os.path.isfile(os.path.join(app.config["UPLOAD_FOLDER"], filename)):
return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
else:
return redirect(url_for("static", filename="icons/defaultprofile.png"))
@app.route("/signup", methods=["GET", "POST"])
def signup():
if request.cookies.get("jwt"):
return redirect(url_for("profile"))
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
cpassword = request.form.get("cpassword")
if not username:
flash("Username cannot be empty!", "error")
return redirect(request.url)
else:
if not validUsername(username):
flash(
"Username can only contain alphabets and digits (4-32 characters)!",
"error",
)
return redirect(request.url)
if not password:
flash("Password cannot be empty!", "error")
return redirect(request.url)
if not (8 <= len(password) <= 32):
flash("Password can have 8-32 characters only!", "error")
return redirect(request.url)
if not cpassword:
flash("Confirmed password cannot be empty!", "error")
return redirect(request.url)
if password != cpassword:
flash("Passwords are not same!", "error")
return redirect(request.url)
if app.config["USE_CAPTCHA"]:
captcha_answer = request.form.get("captcha_answer")
captcha_jwt = request.form.get("captcha_jwt")
captcha_result = verifyCaptcha(captcha_answer, captcha_jwt)
if captcha_result["expired"]:
flash("CAPTCHA has expired!", "error")
return redirect(request.url)
if not captcha_result["valid"]:
flash("CAPTCHA error!", "error")
return redirect(request.url)
newUser = True
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
accounts = db.table("accounts")
account = accounts.get(Query().username == username)
newUser = not account
if not newUser:
flash("Username already registered!", "error")
return redirect(request.url)
passwd_salt = bcrypt.gensalt(rounds=12)
passwd_hash = bcrypt.hashpw(password.encode("latin1"), passwd_salt).decode(
"latin1"
)
account = {
"username": username,
"passwd_hash": passwd_hash,
"avatar": None,
"timestamp": int(time.time()),
"uploads": 0,
}
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
accounts = db.table("accounts")
accounts.insert(account)
resp = make_response(redirect(url_for("profile")))
resp.set_cookie("jwt", encodeToJWT({"username": username}))
return resp
return render_template("signup.html", captcha_enabled=app.config["USE_CAPTCHA"])
@app.route("/login", methods=["GET", "POST"])
def login():
if request.cookies.get("jwt"):
return redirect(url_for("profile"))
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
if not username:
flash("Username cannot be empty!", "error")
return redirect(request.url)
if not password:
flash("Password cannot be empty!", "error")
return redirect(request.url)
if app.config["USE_CAPTCHA"]:
captcha_answer = request.form.get("captcha_answer")
captcha_jwt = request.form.get("captcha_jwt")
captcha_result = verifyCaptcha(captcha_answer, captcha_jwt)
if captcha_result["expired"]:
flash("CAPTCHA has expired!", "error")
return redirect(request.url)
if not captcha_result["valid"]:
flash("CAPTCHA error!", "error")
return redirect(request.url)
userExists = False
validCredentials = False
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
accounts = db.table("accounts")
account = accounts.get(Query().username == username)
if account:
userExists = True
passwd_hash = account.get("passwd_hash").encode("latin1")
validCredentials = bcrypt.checkpw(
password.encode("latin1"), passwd_hash
)
else:
userExists = False
if userExists:
if validCredentials:
resp = make_response(redirect(url_for("profile")))
resp.set_cookie("jwt", encodeToJWT({"username": username}))
return resp
else:
flash("Invalid credentials!", "error")
else:
flash("This user does not exist!", "error")
return render_template("login.html", captcha_enabled=app.config["USE_CAPTCHA"])
@app.route("/logout")
def logout():
resp = make_response(redirect(url_for("login")))
resp.delete_cookie("jwt")
return resp
@app.route("/profile")
def profile():
token = request.cookies.get("jwt")
jwtData = decodeFromJWT(token)
if not jwtData:
resp = make_response(redirect(url_for("login")))
resp.delete_cookie("jwt")
return resp
username = jwtData.get("username")
uploads = 0
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
accounts = db.table("accounts")
account = accounts.get(Query().username == username)
if account:
uploads = account.get("uploads", 0)
return render_template(
"profile.html",
username=username,
uploads=uploads,
visibility="private",
loggedIn=True,
)
@app.route("/upload", methods=["GET", "POST"])
def upload():
if not request.cookies.get("jwt"):
return redirect(url_for("login"))
token = request.cookies.get("jwt")
jwtData = decodeFromJWT(token)
if not jwtData:
resp = make_response(redirect(url_for("login")))
resp.delete_cookie("jwt")
return resp
username = jwtData.get("username")
if request.method == "POST":
# the error will be triggered when we first access the `resquest` object
try:
description = request.form.get("description", "")
file = None
if "fileToUpload" in request.files:
file = request.files["fileToUpload"]
else:
flash("Invalid request!", "error")
except RequestEntityTooLarge as exc:
useragent = request.headers.get("User-Agent", "")
contentlength = request.headers.get("Content-Length", "")
sizelimit = app.config["MAX_CONTENT_LENGTH"]
errors = list(
map(
render_template_string,
[
"Woah! Your file is too powerful!",
f"User-Agent: {useragent}",
f"Content-Length: {contentlength}",
f"Size Limit: {sizelimit} bytes",
],
)
)
return render_template(
"layouts/error.html",
errors=errors,
returnURL=request.url,
loggedIn=True,
)
else:
if file:
if not file.filename:
flash("No file selected!", "error")
else:
ext = extension(file.filename)
if allowed_file(file.filename):
timestamp = time.time()
timestamp_hash = md5(
str(timestamp).encode("utf-8")
).hexdigest()
filename = f"{username}-{timestamp_hash}.{ext}"
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(filepath)
image = {
"filename": filename,
"owner": username,
"timestamp": int(timestamp),
"public": False,
"description": description,
"likes": [],
}
with dbLock:
with TinyDB(app.config["DATABASE"]) as db:
accounts = db.table("accounts")
accounts.update(
tinydb.operations.increment("uploads"),
Query().username == username,
)
images = db.table("images")
images.insert(image)
flash("File uploaded successfully!", "success")
else:
flash(f"Invalid file extension: `{ext}`", "error")
else:
flash("No file selected!", "error")
return redirect(request.url)
return render_template("upload.html", loggedIn=True)
if __name__ == "__main__":
# to keep the rendered HTML output clean of redundant whitespaces
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
# for development
app.config["PRETTIFY"] = True
prettify = Prettify(app)
app.run(host="localhost", port="8080")