-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflask_app.py
More file actions
2055 lines (1739 loc) · 82.2 KB
/
Copy pathflask_app.py
File metadata and controls
2055 lines (1739 loc) · 82.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, flash, session, send_file
from flask_session import Session
from flask_mail import Mail, Message
from werkzeug.utils import secure_filename
import os
import uuid
from datetime import datetime, timedelta
import mimetypes
import json
from PIL import Image
import io
import secrets
import re
app = Flask(__name__)
app.secret_key = "super-secret"
UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), 'uploads')
SESSION_FOLDER = os.path.join(os.path.dirname(__file__), 'flask_session')
PROFILE_PICTURES_FOLDER = os.path.join(os.path.dirname(__file__), 'profile_pictures')
# Mail will be configured after loading settings
mail = None
# Configure server-side session storage
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_FILE_DIR'] = SESSION_FOLDER
app.config['SESSION_PERMANENT'] = True
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_FILE_THRESHOLD'] = 100
app.config['PERMANENT_SESSION_LIFETIME'] = 86400 # 24 hours in seconds
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 40 * 1024 * 1024 # 40 MB
ALLOWED_EXTENSIONS = None # None means allow all file types
# Initialize server-side sessions
Session(app)
# File path for user storage
USERS_FILE = os.path.join(os.path.dirname(__file__), 'users.json')
# File path for file database storage
FILES_DB_FILE = os.path.join(os.path.dirname(__file__), 'files_db.json')
# File path for settings storage
SETTINGS_FILE = os.path.join(os.path.dirname(__file__), 'settings.json')
# In-memory file info storage: {file_id: {filename, path, timestamp}}
file_db = {}
# Helper to check admin
ADMIN_USERS = {'gdhanush270'}
# Application settings (defaults, will be overridden by settings.json)
SETTINGS = {
'app_name': 'FileShare Pro',
'max_file_size_mb': 40,
'max_files_per_bundle': 5,
'registration_open': True,
'total_server_storage_mb': 500,
'user_storage_limit_mb': 50
}
def load_settings():
"""Load settings from JSON file and configure Flask-Mail"""
global mail
if os.path.exists(SETTINGS_FILE):
try:
with open(SETTINGS_FILE, 'r') as f:
loaded_settings = json.load(f)
# Merge with default settings to ensure all keys exist
for key, value in loaded_settings.items():
SETTINGS[key] = value
except (json.JSONDecodeError, IOError):
pass
# Configure Flask-Mail from settings
if 'email' in SETTINGS:
app.config.update({
'MAIL_SERVER': SETTINGS['email'].get('MAIL_SERVER', 'smtp.gmail.com'),
'MAIL_PORT': int(SETTINGS['email'].get('MAIL_PORT', 587)),
'MAIL_USE_TLS': SETTINGS['email'].get('MAIL_USE_TLS', True),
'MAIL_USERNAME': SETTINGS['email'].get('MAIL_USERNAME', ''),
'MAIL_PASSWORD': SETTINGS['email'].get('MAIL_PASSWORD', ''),
'MAIL_DEFAULT_SENDER': SETTINGS['email'].get('MAIL_DEFAULT_SENDER', '')
})
mail = Mail(app)
def save_settings():
"""Save settings to JSON file"""
try:
with open(SETTINGS_FILE, 'w') as f:
json.dump(SETTINGS, f, indent=2)
except IOError:
pass
def load_users():
"""Load users from JSON file"""
if os.path.exists(USERS_FILE):
try:
with open(USERS_FILE, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
pass
# Return default admin users if file doesn't exist or is corrupted
return {
'gdhanush270': {'password': 'ttpod123', 'email': 'gdhanush270@gmail.com', 'role': 'admin'},
}
def save_users(users):
"""Save users to JSON file"""
try:
with open(USERS_FILE, 'w') as f:
json.dump(users, f, indent=2)
except IOError:
pass
def load_files_db():
"""Load files database from JSON file"""
if os.path.exists(FILES_DB_FILE):
try:
with open(FILES_DB_FILE, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
pass
return {}
def save_files_db(files_db):
"""Save files database to JSON file"""
try:
with open(FILES_DB_FILE, 'w') as f:
json.dump(files_db, f, indent=2)
except IOError:
pass
# Load settings on startup
load_settings()
# Load users on startup
USERS = load_users()
# Load files database on startup
file_db = load_files_db()
# Application name (pulled from settings)
APP_NAME = SETTINGS.get('app_name', 'FileShare Pro')
# Helper functions for recovery tokens stored in users.json
def get_user_recovery_token(username, token_type):
"""Get recovery token for a user (token_type: 'verify', 'password_reset', 'account_recovery')"""
user = USERS.get(username)
if user and 'recovery_tokens' in user:
return user['recovery_tokens'].get(token_type)
return None
def set_user_recovery_token(username, token_type, token_data):
"""Set recovery token for a user"""
if username in USERS:
if 'recovery_tokens' not in USERS[username]:
USERS[username]['recovery_tokens'] = {}
USERS[username]['recovery_tokens'][token_type] = token_data
save_users(USERS)
def remove_user_recovery_token(username, token_type):
"""Remove recovery token for a user"""
if username in USERS and 'recovery_tokens' in USERS[username]:
USERS[username]['recovery_tokens'].pop(token_type, None)
save_users(USERS)
def find_user_by_token(token, token_type):
"""Find username by recovery token"""
for username, user_data in USERS.items():
if 'recovery_tokens' in user_data:
token_data = user_data['recovery_tokens'].get(token_type)
if token_data and token_data.get('token') == token:
return username
return None
def is_admin(username):
return username.lower() in ADMIN_USERS
def allowed_file(filename):
if ALLOWED_EXTENSIONS is None:
return True
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# Email helper functions
def send_email(to, subject, html_body):
"""Send an email using Flask-Mail"""
try:
# Check if email is configured
if not app.config.get('MAIL_PASSWORD'):
print("ERROR: MAIL_PASSWORD not configured in .env file")
return False
print(f"Attempting to send email to: {to}")
print(f"MAIL_SERVER: {app.config.get('MAIL_SERVER')}")
print(f"MAIL_USERNAME: {app.config.get('MAIL_USERNAME')}")
msg = Message(subject, recipients=[to])
msg.html = html_body
mail.send(msg)
print(f"Email sent successfully to: {to}")
return True
except Exception as e:
print(f"ERROR sending email to {to}: {type(e).__name__}: {e}")
import traceback
traceback.print_exc()
return False
def generate_token():
"""Generate a secure random token"""
return secrets.token_urlsafe(32)
def send_password_reset_email(email, token):
"""Send password reset email"""
reset_url = url_for('reset_password', token=token, _external=True)
subject = f"Password Reset Request - {APP_NAME}"
html_body = f"""
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; }}
.container {{ background-color: white; padding: 30px; border-radius: 10px; max-width: 600px; margin: 0 auto; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
.header {{ background: linear-gradient(120deg, #4361ee, #7209b7); color: white; padding: 20px; border-radius: 10px 10px 0 0; margin: -30px -30px 20px -30px; }}
.btn {{ display: inline-block; padding: 12px 30px; background-color: #4361ee; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }}
.footer {{ color: #666; font-size: 12px; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Password Reset Request</h1>
</div>
<p>Hello,</p>
<p>We received a request to reset your password for your {APP_NAME} account.</p>
<p>Click the button below to reset your password:</p>
<a href="{reset_url}" class="btn">Reset Password</a>
<p>Or copy and paste this link into your browser:</p>
<p style="word-break: break-all; color: #4361ee;">{reset_url}</p>
<p><strong>This link will expire in 1 hour.</strong></p>
<p>If you didn't request this password reset, you can safely ignore this email.</p>
<div class="footer">
<p>This is an automated email from {APP_NAME}. Please do not reply to this email.</p>
</div>
</div>
</body>
</html>
"""
return send_email(email, subject, html_body)
def send_verification_email(email, token, username):
"""Send email verification email"""
verify_url = url_for('verify_email', token=token, _external=True)
subject = f"Verify Your Email - {APP_NAME}"
html_body = f"""
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; }}
.container {{ background-color: white; padding: 30px; border-radius: 10px; max-width: 600px; margin: 0 auto; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
.header {{ background: linear-gradient(120deg, #4361ee, #7209b7); color: white; padding: 20px; border-radius: 10px 10px 0 0; margin: -30px -30px 20px -30px; }}
.btn {{ display: inline-block; padding: 12px 30px; background-color: #06d6a0; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }}
.footer {{ color: #666; font-size: 12px; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Welcome to {APP_NAME}!</h1>
</div>
<p>Hello {username},</p>
<p>Thank you for registering! Please verify your email address to start uploading files.</p>
<p>Click the button below to verify your email:</p>
<a href="{verify_url}" class="btn">Verify Email</a>
<p>Or copy and paste this link into your browser:</p>
<p style="word-break: break-all; color: #4361ee;">{verify_url}</p>
<p><strong>This link will expire in 24 hours.</strong></p>
<div class="footer">
<p>This is an automated email from {APP_NAME}. Please do not reply to this email.</p>
</div>
</div>
</body>
</html>
"""
return send_email(email, subject, html_body)
def send_email_change_notification(old_email, new_email, username):
"""Send email change notification to old email address"""
subject = f"Email Address Changed - {APP_NAME}"
html_body = f"""
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; }}
.container {{ background-color: white; padding: 30px; border-radius: 10px; max-width: 600px; margin: 0 auto; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
.header {{ background: linear-gradient(120deg, #ff6b6b, #ee5a6f); color: white; padding: 20px; border-radius: 10px 10px 0 0; margin: -30px -30px 20px -30px; }}
.info-box {{ background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 5px; }}
.new-email {{ color: #4361ee; font-weight: bold; }}
.footer {{ color: #666; font-size: 12px; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>⚠️ Email Address Changed</h1>
</div>
<p>Hello {username},</p>
<p>This is to inform you that the email address associated with your {APP_NAME} account has been changed.</p>
<div class="info-box">
<p><strong>Your email has been changed to:</strong></p>
<p class="new-email">{new_email}</p>
</div>
<p>If you made this change, no further action is needed. You will need to verify your new email address to continue using all features.</p>
<p><strong>If you did NOT make this change:</strong></p>
<ul>
<li>Your account security may be compromised</li>
<li>Please contact support immediately</li>
<li>Change your password as soon as possible</li>
</ul>
<div class="footer">
<p>This is an automated security notification from {APP_NAME}. Please do not reply to this email.</p>
<p>Sent on: {datetime.now().strftime('%B %d, %Y at %I:%M %p')}</p>
</div>
</div>
</body>
</html>
"""
return send_email(old_email, subject, html_body)
def validate_username(username):
"""
Validate username format.
Returns (is_valid, error_message)
Rules:
- 3-20 characters long
- Only alphanumeric characters, underscores, and hyphens
- Must start with a letter or number
- Cannot end with underscore or hyphen
"""
if not username:
return False, "Username is required"
if len(username) < 3:
return False, "Username must be at least 3 characters long"
if len(username) > 20:
return False, "Username must be no more than 20 characters long"
# Check if username starts with alphanumeric
if not username[0].isalnum():
return False, "Username must start with a letter or number"
# Check if username ends with alphanumeric
if not username[-1].isalnum():
return False, "Username cannot end with underscore or hyphen"
# Check for valid characters (alphanumeric, underscore, hyphen)
if not re.match(r'^[a-zA-Z0-9_-]+$', username):
return False, "Username can only contain letters, numbers, underscores, and hyphens"
return True, None
def validate_email(email):
"""
Validate email format.
Returns (is_valid, error_message)
"""
if not email:
return False, "Email is required"
# Basic email regex pattern
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_pattern, email):
return False, "Invalid email format"
return True, None
@app.route('/register', methods=['GET', 'POST'])
def register():
print("=== REGISTER ROUTE CALLED ===")
print(f"Request method: {request.method}")
if not SETTINGS.get('registration_open', True):
flash('Registration is currently disabled. Please contact an admin.', 'error')
return redirect(url_for('login'))
if request.method == 'POST':
username = request.form.get('username', '').strip()
email = request.form.get('email', '').strip()
password = request.form.get('password', '')
confirm_password = request.form.get('confirm_password', '')
print(f"Registration attempt - Username: {username}, Email: {email}")
# Validate all fields are present
if not username or not email or not password or not confirm_password:
flash('All fields are required!', 'error')
return render_template('register.html', APP_NAME=APP_NAME)
# Validate username format
is_valid, error_msg = validate_username(username)
if not is_valid:
flash(error_msg, 'error')
return render_template('register.html', APP_NAME=APP_NAME)
# Validate email format
is_valid, error_msg = validate_email(email)
if not is_valid:
flash(error_msg, 'error')
return render_template('register.html', APP_NAME=APP_NAME)
# Validate password strength
if len(password) < 8:
flash('Password must be at least 8 characters long!', 'error')
return render_template('register.html', APP_NAME=APP_NAME)
# Check password match
if password != confirm_password:
flash('Passwords do not match!', 'error')
return render_template('register.html', APP_NAME=APP_NAME)
# Check if email already exists
email_lower = email.lower()
for existing_username, user_data in USERS.items():
if user_data.get('email', '').lower() == email_lower:
# Skip if this is a deleted user that can be replaced
if user_data.get('deleted_at'):
deleted_at = datetime.fromisoformat(user_data['deleted_at'])
deletion_date = deleted_at + timedelta(days=30)
if datetime.now() > deletion_date:
continue # This deleted account can be replaced
flash('Email already in use!', 'error')
return render_template('register.html', APP_NAME=APP_NAME)
# Convert username to lowercase for case-insensitive comparison
username_lower = username.lower()
if username_lower in USERS:
# Check if user was deleted and 30 days have passed
existing_user = USERS[username_lower]
if existing_user.get('deleted_at'):
deleted_at = datetime.fromisoformat(existing_user['deleted_at'])
deletion_date = deleted_at + timedelta(days=30)
# If 30 days have passed, delete old account and create new one
if datetime.now() > deletion_date:
# Delete old user's profile picture if exists
if existing_user.get('profile_picture'):
old_pic_path = os.path.join(PROFILE_PICTURES_FOLDER, existing_user['profile_picture'])
if os.path.exists(old_pic_path):
try:
os.remove(old_pic_path)
except:
pass
# Delete old user's files
ids_to_delete = []
for fid, info in list(file_db.items()):
if info.get('owner') == username_lower:
ids_to_delete.append(fid)
for fid in ids_to_delete:
info = file_db.get(fid)
if info:
if info.get('is_bundle'):
for child_id in info.get('files', []):
child_info = file_db.get(child_id)
if child_info and os.path.exists(child_info['path']):
try:
os.remove(child_info['path'])
except:
pass
file_db.pop(child_id, None)
file_db.pop(fid, None)
else:
if os.path.exists(info['path']):
try:
os.remove(info['path'])
except:
pass
file_db.pop(fid, None)
save_files_db(file_db)
# Now create new user (continue below)
else:
flash('Username already exists!', 'error')
return render_template('register.html', APP_NAME=APP_NAME)
else:
flash('Username already exists!', 'error')
return render_template('register.html', APP_NAME=APP_NAME)
# Create new user with email_verified set to False
USERS[username_lower] = {
'password': password,
'email': email,
'role': 'user',
'storage_limit_mb': 50,
'email_verified': False
}
save_users(USERS)
# Generate verification token
token = generate_token()
set_user_recovery_token(username_lower, 'verify', {
'type': 'email_verification',
'username': username_lower,
'token': token,
'timestamp': datetime.now().isoformat()
})
# Send verification email
if send_verification_email(email, token, username):
flash('Account created successfully! Please check your email to verify your account.', 'success')
else:
flash('Account created but failed to send verification email. You can request it again from your profile.', 'warning')
print(f"User registered successfully: {username_lower}")
print(f"Current users: {list(USERS.keys())}")
return redirect(url_for('login'))
print("Returning register.html template")
return render_template('register.html', APP_NAME=APP_NAME)
@app.route('/recover', methods=['GET', 'POST'])
def recover():
"""Recovery page for permanently deleted accounts (>30 days)"""
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if not username or not password:
flash('Username and password are required!', 'error')
return render_template('recover.html', APP_NAME=APP_NAME)
# Convert username to lowercase
username_lower = username.lower()
user = USERS.get(username_lower)
# Always show the same message for security (prevent username enumeration)
# Only process if credentials are correct
should_process = False
if user and user['password'] == password and user.get('deleted_at'):
deleted_at = datetime.fromisoformat(user['deleted_at'])
deletion_date = deleted_at + timedelta(days=30)
# Only process if 30 days have passed and no existing request
token_data = get_user_recovery_token(username_lower, 'account_recovery')
if datetime.now() > deletion_date and not token_data:
should_process = True
# Process the recovery request if credentials are correct
if should_process:
set_user_recovery_token(username_lower, 'account_recovery', {
'username': username_lower,
'requested_at': datetime.now().isoformat(),
'deleted_at': user['deleted_at'],
'role': user.get('role', 'user')
})
# Always show the same message regardless of success
flash('Request will be sent if the credentials are correct.', 'info')
return redirect(url_for('login'))
return render_template('recover.html', APP_NAME=APP_NAME)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username') or ""
password = request.form.get('password') or ""
print(f"Login attempt - Username: {username}")
if not username or not password:
flash('Please enter both username and password!', 'error')
return render_template('login.html', APP_NAME=APP_NAME)
# Convert username to lowercase for case-insensitive lookup
username_lower = username.lower().strip()
user = USERS.get(username_lower)
print(f"User found: {user is not None}")
if user and user['password'] == password:
# Check if account is marked for deletion
if user.get('deleted_at'):
deleted_at = datetime.fromisoformat(user['deleted_at'])
deletion_date = deleted_at + timedelta(days=30)
# Check if 30 days have passed
if datetime.now() > deletion_date:
flash('Your account has been permanently deleted. Visit the recovery page to restore your account.', 'error')
return render_template('login.html', APP_NAME=APP_NAME)
else:
# Account is scheduled for deletion, allow login to recover
session['username'] = username_lower
session['role'] = user['role']
flash(f'Your account is scheduled for deletion on {deletion_date.strftime("%B %d, %Y")}. Visit your profile to recover it.', 'warning')
return redirect(url_for('index'))
session['username'] = username_lower
session['role'] = user['role']
print(f"Login successful for: {username_lower}")
flash('Login successful!', 'success')
return redirect(url_for('index'))
else:
print(f"Login failed for: {username_lower}")
# Generic error message to prevent username enumeration
flash('Invalid username or password! Please try again.', 'error')
return render_template('login.html', APP_NAME=APP_NAME)
return render_template('login.html', APP_NAME=APP_NAME)
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
flash('Logged out successfully!', 'success')
return redirect(url_for('login'))
@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
if request.method == 'POST':
email = request.form.get('email', '').strip().lower()
if not email:
flash('Please enter your email address.', 'error')
return render_template('forgot_password.html', APP_NAME=APP_NAME)
# Find user by email
user_found = None
username_found = None
for username, user_data in USERS.items():
if user_data.get('email', '').lower() == email:
user_found = user_data
username_found = username
break
# Always show success message for security (prevent email enumeration)
if user_found and not user_found.get('deleted_at'):
# Generate reset token
token = generate_token()
set_user_recovery_token(username_found, 'password_reset', {
'type': 'password_reset',
'username': username_found,
'token': token,
'timestamp': datetime.now().isoformat()
})
# Send reset email
send_password_reset_email(email, token)
flash('If the email exists in our system, you will receive a password reset link shortly.', 'success')
return redirect(url_for('login'))
return render_template('forgot_password.html', APP_NAME=APP_NAME)
@app.route('/reset_password/<token>', methods=['GET', 'POST'])
def reset_password(token):
# Find the reset request by token
username = find_user_by_token(token, 'password_reset')
if username:
token_data = get_user_recovery_token(username, 'password_reset')
# Check if token is expired (1 hour)
timestamp = datetime.fromisoformat(token_data['timestamp'])
if datetime.now() - timestamp >= timedelta(hours=1):
username = None
if not username:
flash('Invalid or expired reset link. Please request a new one.', 'error')
return redirect(url_for('forgot_password'))
if request.method == 'POST':
password = request.form.get('password', '')
confirm_password = request.form.get('confirm_password', '')
if not password or not confirm_password:
flash('All fields are required!', 'error')
return render_template('reset_password.html', APP_NAME=APP_NAME, token=token)
if password != confirm_password:
flash('Passwords do not match!', 'error')
return render_template('reset_password.html', APP_NAME=APP_NAME, token=token)
# Update password
if username in USERS:
USERS[username]['password'] = password
save_users(USERS)
# Remove the reset request
remove_user_recovery_token(username, 'password_reset')
flash('Password reset successfully! You can now login with your new password.', 'success')
return redirect(url_for('login'))
else:
flash('User not found!', 'error')
return redirect(url_for('login'))
return render_template('reset_password.html', APP_NAME=APP_NAME, token=token)
@app.route('/verify_email/<token>')
def verify_email(token):
# Find the verification request by token
username = find_user_by_token(token, 'verify')
if username:
token_data = get_user_recovery_token(username, 'verify')
# Check if token is expired (24 hours)
timestamp = datetime.fromisoformat(token_data['timestamp'])
if datetime.now() - timestamp >= timedelta(hours=24):
username = None
if not username:
flash('Invalid or expired verification link. Please request a new one from your profile.', 'error')
return redirect(url_for('login'))
# Verify the user's email
if username in USERS:
USERS[username]['email_verified'] = True
save_users(USERS)
# Remove the verification request
remove_user_recovery_token(username, 'verify')
flash('Email verified successfully! You can now upload files.', 'success')
# If user is logged in, redirect to profile, otherwise to login
if session.get('username') == username:
return redirect(url_for('profile', username=username))
else:
return redirect(url_for('login'))
else:
flash('User not found!', 'error')
return redirect(url_for('login'))
@app.route('/resend_verification')
def resend_verification():
if 'username' not in session:
flash('Please login first.', 'error')
return redirect(url_for('login'))
username = session['username']
user = USERS.get(username)
if not user:
flash('User not found!', 'error')
return redirect(url_for('login'))
if user.get('email_verified'):
flash('Your email is already verified!', 'info')
return redirect(url_for('profile', username=username))
# Generate new verification token
token = generate_token()
set_user_recovery_token(username, 'verify', {
'type': 'email_verification',
'username': username,
'token': token,
'timestamp': datetime.now().isoformat()
})
# Send verification email
if send_verification_email(user['email'], token, username):
flash('Verification email sent! Please check your inbox and spam.', 'success')
else:
flash('Failed to send verification email. Please try again later.', 'error')
return redirect(url_for('profile', username=username))
@app.route('/u/<username>', methods=['GET', 'POST'])
def profile(username):
# Check if the profile user exists
if username not in USERS:
flash('User not found!', 'error')
return redirect(url_for('login'))
# Determine if viewing own profile
current_user = session.get('username')
is_own_profile = (current_user == username)
if request.method == 'POST':
# Password change requires login
if 'username' not in session:
flash('Please login to change your password!', 'error')
return redirect(url_for('login'))
# Only allow changes for own profile
if not is_own_profile:
flash('You can only modify your own profile!', 'error')
return redirect(url_for('profile', username=username))
# Handle storage visibility toggle
if 'toggle_storage_visibility' in request.form:
user = USERS.get(username)
current_visibility = user.get('storage_public', True)
user['storage_public'] = not current_visibility
save_users(USERS)
flash(f"Storage visibility set to {'public' if user['storage_public'] else 'private'}!", 'success')
return redirect(url_for('profile', username=username))
# Handle email change
action = request.form.get('action')
if action == 'change_email':
new_email = request.form.get('new_email', '').strip()
email_password = request.form.get('email_password')
# Validate inputs
if not new_email or not email_password:
flash('All fields are required!', 'error')
return redirect(url_for('profile', username=username))
# Check password
user = USERS.get(username)
if not user or user['password'] != email_password:
flash('Password is incorrect!', 'error')
return redirect(url_for('profile', username=username))
# Check if email already exists
email_lower = new_email.lower()
for existing_username, user_data in USERS.items():
if existing_username != username and user_data.get('email', '').lower() == email_lower:
flash('Email already in use by another account!', 'error')
return redirect(url_for('profile', username=username))
# Update email and reset verification if changed
old_email = USERS.get(username, {}).get('email', '')
USERS[username]['email'] = new_email
if old_email.strip().lower() != new_email.strip().lower():
USERS[username]['email_verified'] = False
# Send notification to old email about the change
if old_email:
send_email_change_notification(old_email, new_email, username)
# Send verification email to new email address
token = generate_token()
set_user_recovery_token(username, 'verify', {
'type': 'email_verification',
'username': username,
'token': token,
'timestamp': datetime.now().isoformat()
})
send_verification_email(new_email, token, username)
save_users(USERS)
flash('Email updated successfully! Check your inbox or Spam folder for confirmation emails.', 'success')
return redirect(url_for('profile', username=username))
# Handle password reset request via email
if action == 'change_password':
user = USERS.get(username)
if not user:
flash('User not found.', 'error')
return redirect(url_for('login'))
token = generate_token()
set_user_recovery_token(username, 'password_reset', {
'type': 'password_reset',
'username': username,
'token': token,
'timestamp': datetime.now().isoformat()
})
if send_password_reset_email(user.get('email', ''), token):
flash('A password reset link has been sent to your email address. Please check your inbox and Spam folder.', 'success')
else:
flash('Failed to send password reset email. Please try again later.', 'error')
return redirect(url_for('profile', username=username))
# Enforce email-based password changes: send reset link
if request.form.get('current_password') or request.form.get('new_password') or request.form.get('confirm_password'):
user = USERS.get(username)
if not user:
flash('User not found.', 'error')
return redirect(url_for('login'))
token = generate_token()
set_user_recovery_token(username, 'password_reset', {
'type': 'password_reset',
'username': username,
'token': token,
'timestamp': datetime.now().isoformat()
})
if send_password_reset_email(user.get('email', ''), token):
flash('A password reset link has been sent to your email address. Please check your inbox and Spam folder.', 'success')
else:
flash('Failed to send password reset email. Please try again later.', 'error')
return redirect(url_for('profile', username=username))
user_info = USERS.get(username, {})
# Initialize storage_public if not set
if 'storage_public' not in user_info:
user_info['storage_public'] = True
USERS[username] = user_info
save_users(USERS)
# Determine if storage should be visible
# Admins can always see storage, even if private
is_admin_viewing = current_user and is_admin(current_user)
storage_visible = is_own_profile or user_info.get('storage_public', True) or is_admin_viewing
# Calculate user's storage usage
total_storage_bytes = 0
file_count = 0
bundle_count = 0
for file_id, file_info in file_db.items():
if file_info.get('owner') == username:
if file_info.get('is_bundle'):
bundle_count += 1
else:
file_count += 1
if os.path.exists(file_info['path']):
total_storage_bytes += os.path.getsize(file_info['path'])
# Format storage size
def format_bytes(bytes_val):
if bytes_val < 1024:
return f"{bytes_val} B"
elif bytes_val < 1024 * 1024:
return f"{bytes_val/1024:.2f} KB"
elif bytes_val < 1024 * 1024 * 1024:
return f"{bytes_val/1024/1024:.2f} MB"
else:
return f"{bytes_val/1024/1024/1024:.2f} GB"
# Calculate storage percentage (use user-specific limit or default to 50MB)
user_limit_mb = user_info.get('storage_limit_mb', 50)
user_limit_bytes = user_limit_mb * 1024 * 1024
storage_percentage = (total_storage_bytes / user_limit_bytes * 100) if user_limit_bytes > 0 else 0
storage_info = {
'total_storage': format_bytes(total_storage_bytes),
'total_storage_bytes': total_storage_bytes,
'file_count': file_count,
'bundle_count': bundle_count,
'storage_limit': format_bytes(user_limit_bytes),
'storage_limit_bytes': user_limit_bytes,
'storage_percentage': round(storage_percentage, 1)
}
# Add deletion info if account is marked for deletion
if user_info.get('deleted_at'):
deleted_at = datetime.fromisoformat(user_info['deleted_at'])
deletion_date = deleted_at + timedelta(days=30)
user_info['deletion_date'] = deletion_date.strftime('%B %d, %Y')
return render_template('profile.html', user_info=user_info, username=username, storage_info=storage_info, is_own_profile=is_own_profile, storage_visible=storage_visible, APP_NAME=APP_NAME, is_admin=is_admin(session.get('username', '')))
@app.route('/u/<username>/upload_profile_picture', methods=['POST'])
def upload_profile_picture(username):
# Check if user is logged in and viewing own profile
if 'username' not in session:
flash('Please login to upload a profile picture!', 'error')
return redirect(url_for('login'))
if session['username'] != username:
flash('You can only change your own profile picture!', 'error')
return redirect(url_for('profile', username=username))
if 'profile_picture' not in request.files:
flash('No file selected!', 'error')
return redirect(url_for('profile', username=username))
file = request.files['profile_picture']
if file.filename == '':
flash('No file selected!', 'error')
return redirect(url_for('profile', username=username))
# Check if file is an image
mime_type, _ = mimetypes.guess_type(file.filename)
if not mime_type or not mime_type.startswith('image/'):
flash('Only image files are allowed for profile pictures!', 'error')
return redirect(url_for('profile', username=username))
# Save the profile picture
try:
# Remove old profile picture if exists
user = USERS.get(username)
if user and user.get('profile_picture'):
old_pic_path = os.path.join(PROFILE_PICTURES_FOLDER, user['profile_picture'])
if os.path.exists(old_pic_path):
try:
os.remove(old_pic_path)
except:
pass
# Generate unique filename
file_ext = os.path.splitext(file.filename)[1]
unique_filename = f"{username}_{uuid.uuid4().hex}{file_ext}"
file_path = os.path.join(PROFILE_PICTURES_FOLDER, unique_filename)
# Save and resize the image
img = Image.open(file.stream)
# Convert RGBA to RGB if necessary
if img.mode in ('RGBA', 'LA', 'P'):