Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
3022 lines (2583 loc) · 129 KB
/
Copy pathapp.py
File metadata and controls
3022 lines (2583 loc) · 129 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
"""
Ahmed Youssef Bosha — Personal Portfolio & CMS
A Flask portfolio application with a public profile, project showcase,
content-management dashboard, authentication, contact messaging, and email workflows.
"""
import os
import base64
import sqlite3
import functools
import uuid
import smtplib
import threading
import time
import json
import urllib.request
import urllib.error
import datetime
import re
import secrets
import html as html_lib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from flask import (
Flask, render_template, request, redirect, url_for,
flash, session, g, abort, jsonify, send_from_directory, Response,
)
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.exceptions import NotFound
from urllib.parse import urlparse, quote
# ---------------------------------------------------------------------------
# App configuration
# ---------------------------------------------------------------------------
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY") or secrets.token_hex(32)
app.config["MAX_CONTENT_LENGTH"] = 4 * 1024 * 1024 # 4 MB upload limit
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["SESSION_COOKIE_SECURE"] = (
os.environ.get("SESSION_COOKIE_SECURE") == "1"
or os.environ.get("RENDER", "").lower() == "true"
)
app.config["PERMANENT_SESSION_LIFETIME"] = datetime.timedelta(hours=12)
app.config["ALLOW_REGISTRATION"] = os.environ.get("ALLOW_REGISTRATION", "1") == "1"
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
@app.after_request
def set_security_headers(response):
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("X-Frame-Options", "DENY")
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
response.headers.setdefault(
"Permissions-Policy",
"camera=(), microphone=(), geolocation=(), payment=()",
)
response.headers.setdefault(
"Content-Security-Policy",
"default-src 'self'; "
"img-src 'self' data: blob: https:; "
"style-src 'self' 'unsafe-inline'; "
"script-src 'self' 'unsafe-inline'; "
"font-src 'self' data: https:; "
"connect-src 'self'; "
"frame-ancestors 'none'; "
"base-uri 'self'; "
"form-action 'self'",
)
if request.is_secure:
response.headers.setdefault(
"Strict-Transport-Security",
"max-age=31536000; includeSubDomains",
)
if request.path.startswith(("/admin", "/login", "/register", "/forgot-password", "/reset-password", "/verify-")):
response.headers["Cache-Control"] = "no-store"
return response
DATABASE = os.environ.get("DATABASE_PATH") or os.path.join(app.root_path, "portfolio.db")
UPLOAD_FOLDER = os.environ.get("UPLOAD_FOLDER") or os.path.join(app.root_path, "static", "uploads")
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "gif", "webp"}
# Durable persistence through Supabase Postgres.
# SQLite stays local for fast queries. Database snapshots and uploaded images
# are mirrored to protected Postgres tables so Render redeploys do not reset data.
SUPABASE_URL = os.environ.get("SUPABASE_URL", "").strip().rstrip("/")
SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY", "").strip()
SUPABASE_APP_KEY = os.environ.get("SUPABASE_APP_KEY", "").strip()
CLOUD_STORAGE_ENABLED = bool(SUPABASE_URL and SUPABASE_ANON_KEY and SUPABASE_APP_KEY)
DB_SYNC_READY = False
DB_SYNC_LOCK = threading.Lock()
# Mail configuration
MAIL_SERVER = os.environ.get("MAIL_SERVER", "smtp.gmail.com")
MAIL_PORT = int(os.environ.get("MAIL_PORT", 587))
MAIL_USERNAME = os.environ.get("MAIL_USERNAME")
MAIL_PASSWORD = os.environ.get("MAIL_PASSWORD")
MAIL_RECIPIENT = os.environ.get("MAIL_RECIPIENT")
RESEND_API_KEY = os.environ.get("RESEND_API_KEY")
HEX_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
EMAIL_RE = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
ALLOWED_THEMES = {"default"}
def allowed_file(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def clean_hex_color(value, fallback):
value = (value or "").strip()
return value if HEX_COLOR_RE.fullmatch(value) else fallback
def clean_http_url(value):
value = (value or "").strip()
if not value:
return None
parsed = urlparse(value)
if parsed.scheme in {"http", "https"} and parsed.netloc:
return value
return None
def parse_int(value, default=0, minimum=None, maximum=None):
try:
parsed = int(value)
except (TypeError, ValueError):
parsed = default
if minimum is not None:
parsed = max(minimum, parsed)
if maximum is not None:
parsed = min(maximum, parsed)
return parsed
def media_url(value):
"""Return a safe URL for local uploaded media or approved remote media."""
value = (value or "").strip()
if not value:
return ""
remote = clean_http_url(value)
if remote:
return remote
return url_for("uploaded_file", filename=value)
app.jinja_env.globals["media_url"] = media_url
def generate_otp():
return f"{secrets.randbelow(900000) + 100000:06d}"
def csrf_token():
token = session.get("_csrf_token")
if not token:
token = secrets.token_urlsafe(32)
session["_csrf_token"] = token
return token
app.jinja_env.globals["csrf_token"] = csrf_token
@app.before_request
def verify_csrf():
if request.method not in {"POST", "PUT", "PATCH", "DELETE"}:
return None
expected = session.get("_csrf_token")
supplied = request.form.get("_csrf_token") or request.headers.get("X-CSRF-Token", "")
if expected and supplied and secrets.compare_digest(str(expected), str(supplied)):
return None
if request.is_json or request.headers.get("X-Requested-With") == "XMLHttpRequest":
return jsonify({"success": False, "error": "Invalid or expired request token. Refresh the page and try again."}), 400
abort(400)
def _supabase_headers(content_type=None, prefer=None):
# Publishable keys belong in the apikey header. The gateway maps that to
# the anon role; our RLS policies additionally require x-app-api-key.
headers = {
"apikey": SUPABASE_ANON_KEY,
"x-app-api-key": SUPABASE_APP_KEY,
}
if content_type:
headers["Content-Type"] = content_type
if prefer:
headers["Prefer"] = prefer
return headers
def _postgrest_url(table, query=""):
base = f"{SUPABASE_URL}/rest/v1/{table}"
return f"{base}?{query}" if query else base
def restore_database_from_cloud():
"""Restore the latest SQLite snapshot from the protected Supabase table."""
if not CLOUD_STORAGE_ENABLED:
return False
req = urllib.request.Request(
_postgrest_url("portfolio_snapshots", "id=eq.main&select=payload&limit=1"),
headers=_supabase_headers(),
method="GET",
)
try:
with urllib.request.urlopen(req, timeout=20) as response:
rows = json.loads(response.read().decode("utf-8") or "[]")
if not rows or not rows[0].get("payload"):
return False
payload = base64.b64decode(rows[0]["payload"], validate=True)
os.makedirs(os.path.dirname(os.path.abspath(DATABASE)), exist_ok=True)
temp_path = DATABASE + ".cloud-download"
with open(temp_path, "wb") as handle:
handle.write(payload)
os.replace(temp_path, DATABASE)
print("[SUPABASE] Restored portfolio database snapshot.")
return True
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
print(f"[SUPABASE] Database restore failed ({exc.code}): {body}")
return False
except Exception as exc:
print(f"[SUPABASE] Database restore failed: {exc}")
return False
def sync_database_to_cloud():
"""Upsert the current SQLite snapshot into the protected Supabase table."""
if not CLOUD_STORAGE_ENABLED or not DB_SYNC_READY or not os.path.exists(DATABASE):
return False
with DB_SYNC_LOCK:
try:
with open(DATABASE, "rb") as handle:
encoded = base64.b64encode(handle.read()).decode("ascii")
body = json.dumps({
"id": "main",
"payload": encoded,
"updated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
}).encode("utf-8")
req = urllib.request.Request(
_postgrest_url("portfolio_snapshots", "on_conflict=id"),
data=body,
headers=_supabase_headers(
content_type="application/json",
prefer="resolution=merge-duplicates,return=minimal",
),
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as response:
response.read()
return True
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
print(f"[SUPABASE] Database sync failed ({exc.code}): {body}")
return False
except Exception as exc:
print(f"[SUPABASE] Database sync failed: {exc}")
return False
def cloud_save_media(filename, content_type, payload):
if not CLOUD_STORAGE_ENABLED:
return False
body = json.dumps({
"filename": filename,
"content_type": content_type or "application/octet-stream",
"payload": base64.b64encode(payload).decode("ascii"),
"updated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
}).encode("utf-8")
req = urllib.request.Request(
_postgrest_url("portfolio_media", "on_conflict=filename"),
data=body,
headers=_supabase_headers(
content_type="application/json",
prefer="resolution=merge-duplicates,return=minimal",
),
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as response:
response.read()
return True
def cloud_get_media(filename):
if not CLOUD_STORAGE_ENABLED:
return None
safe_filename = quote(filename, safe="")
req = urllib.request.Request(
_postgrest_url(
"portfolio_media",
f"filename=eq.{safe_filename}&select=content_type,payload&limit=1",
),
headers=_supabase_headers(),
method="GET",
)
try:
with urllib.request.urlopen(req, timeout=20) as response:
rows = json.loads(response.read().decode("utf-8") or "[]")
if not rows:
return None
return (
rows[0].get("content_type") or "application/octet-stream",
base64.b64decode(rows[0]["payload"], validate=True),
)
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
print(f"[SUPABASE] Media restore failed ({exc.code}): {body}")
return None
except Exception as exc:
print(f"[SUPABASE] Media restore failed: {exc}")
return None
def cloud_delete_media(filename):
if not CLOUD_STORAGE_ENABLED:
return False
safe_filename = quote(filename, safe="")
req = urllib.request.Request(
_postgrest_url("portfolio_media", f"filename=eq.{safe_filename}"),
headers=_supabase_headers(prefer="return=minimal"),
method="DELETE",
)
try:
with urllib.request.urlopen(req, timeout=20) as response:
response.read()
return True
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
print(f"[SUPABASE] Media delete failed ({exc.code}): {body}")
return False
def commit_and_sync(db):
db.commit()
return sync_database_to_cloud()
def save_upload(file, prefix="img"):
"""Save an uploaded image locally and mirror it to Supabase Postgres."""
ext = file.filename.rsplit(".", 1)[1].lower()
filename = f"{prefix}_{uuid.uuid4().hex[:8]}.{ext}"
local_path = os.path.join(UPLOAD_FOLDER, filename)
file.save(local_path)
if CLOUD_STORAGE_ENABLED:
try:
with open(local_path, "rb") as handle:
cloud_save_media(
filename,
file.mimetype or "application/octet-stream",
handle.read(),
)
except Exception:
try:
os.remove(local_path)
except OSError:
pass
raise
return filename
def delete_upload(filename):
"""Delete an uploaded media file from local cache and Supabase Postgres."""
if not filename or clean_http_url(filename):
return
path = os.path.join(UPLOAD_FOLDER, filename)
if os.path.exists(path):
os.remove(path)
if CLOUD_STORAGE_ENABLED:
cloud_delete_media(filename)
# ---------------------------------------------------------------------------
# Email Forwarding (Resend HTTPS API & Gmail SMTP fallback)
# ---------------------------------------------------------------------------
def send_custom_email(to_email, subject, html_body, reply_to=None):
"""Core unified email sender: Tries Resend API (HTTPS), then falls back to Gmail SMTP (SSL/TLS)."""
resend_key = os.environ.get("RESEND_API_KEY", "").strip()
brevo_key = (
os.environ.get("BREVO_API_KEY")
or os.environ.get("BREVO_KEY")
or os.environ.get("SENDINBLUE_API_KEY")
or os.environ.get("BREVO_API_TOKEN")
or ""
).strip()
mail_user = os.environ.get("MAIL_USERNAME", "").strip()
mail_pass = os.environ.get("MAIL_PASSWORD", "").strip()
if not to_email:
to_email = (os.environ.get("MAIL_RECIPIENT") or mail_user or "ahmedyoussefmansourbosha@gmail.com").strip()
# 1. Try Brevo HTTPS API (100% Free - 300 emails/day to ANY recipient in the world over HTTPS port 443!)
if brevo_key:
brevo_key_clean = brevo_key.strip("'\" \t\r\n")
print(f"[BREVO] API key configured (length: {len(brevo_key_clean)})")
try:
url = "https://api.brevo.com/v3/smtp/email"
headers = {
"api-key": brevo_key_clean,
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "Portfolio-App/1.0",
}
sender_email_val = (
os.environ.get("BREVO_SENDER_EMAIL")
or mail_user
or os.environ.get("MAIL_RECIPIENT")
or "ahmedyoussefmansourbosha@gmail.com"
).strip("'\" \t\r\n")
payload = {
"sender": {"name": "Ahmed Youssef Bosha Portfolio", "email": sender_email_val},
"to": [{"email": to_email}],
"subject": subject,
"htmlContent": html_body,
}
if reply_to:
payload["replyTo"] = {"email": reply_to.strip()}
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=12) as response:
res_body = response.read().decode("utf-8")
print(f"[BREVO SUCCESS] Sent '{subject}' → {to_email}: {res_body}")
return True, f"Sent via Brevo to {to_email}"
except urllib.error.HTTPError as e:
err = e.read().decode("utf-8")
print(f"[BREVO HTTP ERROR {e.code}] {err}")
# Automatic retry with alternative sender email if Brevo rejects sender
alt_senders = ["ahmedyoussefmansourbosha@gmail.com"]
for alt in alt_senders:
if alt != sender_email_val:
try:
print(f"[BREVO RETRY] Retrying Brevo with sender '{alt}'...")
payload["sender"]["email"] = alt
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=12) as response:
res_body = response.read().decode("utf-8")
print(f"[BREVO RETRY SUCCESS] Sent '{subject}' → {to_email}: {res_body}")
return True, f"Sent via Brevo to {to_email}"
except Exception as ex:
print(f"[BREVO RETRY ERROR for {alt}] {ex}")
except Exception as e:
print(f"[BREVO ERROR] {e}")
# 2. Try Resend HTTPS API if key configured
if resend_key:
try:
url = "https://api.resend.com/emails"
headers = {
"Authorization": f"Bearer {resend_key}",
"Content-Type": "application/json",
"User-Agent": "Portfolio-App/1.0",
}
payload = {
"from": "Ahmed Youssef Bosha Portfolio <onboarding@resend.dev>",
"to": [to_email],
"subject": subject,
"html": html_body,
}
if reply_to:
payload["reply_to"] = reply_to.strip()
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=12) as response:
res_body = response.read().decode("utf-8")
print(f"[RESEND SUCCESS] Sent '{subject}' → {to_email}: {res_body}")
return True, f"Sent via Resend to {to_email}"
except urllib.error.HTTPError as e:
err = e.read().decode("utf-8")
print(f"[RESEND HTTP ERROR {e.code}] {err}")
except Exception as e:
print(f"[RESEND ERROR] {e}")
# 2. Try Gmail SMTP Fallback (SSL port 465 or TLS port 587)
if mail_user and mail_pass:
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = f"Ahmed Youssef Bosha Portfolio <{mail_user}>"
msg["To"] = to_email
if reply_to:
msg["Reply-To"] = reply_to.strip()
msg.attach(MIMEText(html_body, "html"))
try:
server = smtplib.SMTP_SSL("smtp.gmail.com", 465, timeout=10)
server.login(mail_user, mail_pass)
server.send_message(msg)
server.quit()
print(f"[SMTP SSL SUCCESS] Sent '{subject}' → {to_email}")
return True, f"Sent via SMTP SSL to {to_email}"
except Exception as e_ssl:
try:
server = smtplib.SMTP("smtp.gmail.com", 587, timeout=10)
server.starttls()
server.login(mail_user, mail_pass)
server.send_message(msg)
server.quit()
print(f"[SMTP TLS SUCCESS] Sent '{subject}' → {to_email}")
return True, f"Sent via SMTP TLS to {to_email}"
except Exception as e_tls:
err_msg = f"SMTP Error: {e_tls}"
print(f"[SMTP ERROR] {err_msg}")
return False, err_msg
print(f"[EMAIL SIMULATION] (No API Key or SMTP credentials set) To: {to_email} | Subject: {subject}")
return False, "Neither RESEND_API_KEY nor MAIL_USERNAME/PASSWORD are configured."
def send_email_async(to_email, subject, html_body, reply_to=None):
"""Fire-and-forget background thread for sending email asynchronously."""
thread = threading.Thread(
target=send_custom_email,
args=(to_email, subject, html_body, reply_to),
)
thread.daemon = True
thread.start()
def send_otp_email(to_email, full_name, otp_code):
"""Send a mobile-responsive OTP verification email."""
safe_name = html_lib.escape(str(full_name))
safe_code = html_lib.escape(str(otp_code))
subject = f"Portfolio verification code: {otp_code}"
html = f"""
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; width: 100%; max-width: 480px; margin: 0 auto; background: #0d0e15; color: #f0f0f8; border-radius: 16px; overflow: hidden; border: 1px solid rgba(108, 99, 255, 0.25); box-shadow: 0 15px 40px rgba(0, 0, 0, 0.5); box-sizing: border-box;">
<div style="background: linear-gradient(135deg, #6c63ff 0%, #3b82f6 100%); padding: 24px 16px; text-align: center;">
<h1 style="color: #ffffff; margin: 0; font-size: 22px; font-weight: 800; letter-spacing: -0.5px;">Ahmed Youssef Bosha</h1>
<p style="color: rgba(255, 255, 255, 0.9); margin: 4px 0 0 0; font-size: 13px; font-weight: 500;">Account Verification System</p>
</div>
<div style="padding: 24px 16px; box-sizing: border-box;">
<h2 style="color: #ffffff; margin-top: 0; font-size: 18px; font-weight: 700; text-align: center;">Welcome, {safe_name}! 👋</h2>
<p style="font-size: 14px; line-height: 1.6; color: #a0a0b8; margin-bottom: 20px; text-align: center;">
Please use the 6-digit verification code below to activate your portfolio account:
</p>
<div style="text-align: center; margin: 20px 0;">
<div style="display: inline-block; width: 100%; max-width: 280px; background: #161722; border: 2px solid #6c63ff; border-radius: 14px; padding: 14px 10px; box-shadow: 0 8px 24px rgba(108, 99, 255, 0.25); box-sizing: border-box;">
<span style="font-size: 2.2rem; font-weight: 900; letter-spacing: 6px; color: #6c63ff; font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace; display: block; text-align: center;">{safe_code}</span>
</div>
</div>
<div style="background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.3); border-radius: 10px; padding: 12px 14px; margin: 20px 0; text-align: center;">
<p style="margin: 0; font-size: 13px; color: #fbbf24; font-weight: 600;">
⏱ Code Expires in 5 Minutes
</p>
</div>
<p style="font-size: 12px; color: #6e6e86; line-height: 1.5; text-align: center; margin-top: 24px; border-top: 1px solid #1f2030; padding-top: 16px;">
If you did not request this registration, please ignore this email.
</p>
</div>
</div>
"""
send_email_async(to_email, subject, html)
def send_password_reset_email(to_email, username, reset_url):
"""Send a password-reset email."""
safe_username = html_lib.escape(str(username))
safe_reset_url = html_lib.escape(str(reset_url), quote=True)
subject = "Portfolio password reset"
html = f"""
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; max-width: 540px; margin: 0 auto; background: #0d0e15; color: #f0f0f8; border-radius: 18px; overflow: hidden; border: 1px solid rgba(239, 68, 68, 0.25); box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);">
<div style="background: linear-gradient(135deg, #ef4444 0%, #f59e0b 100%); padding: 32px 28px; text-align: center;">
<h1 style="color: #ffffff; margin: 0; font-size: 24px; font-weight: 800; letter-spacing: -0.5px;">Ahmed Youssef Bosha</h1>
<p style="color: rgba(255, 255, 255, 0.9); margin: 6px 0 0 0; font-size: 14px; font-weight: 500;">Password Recovery Center</p>
</div>
<div style="padding: 32px 28px;">
<h2 style="color: #ffffff; margin-top: 0; font-size: 20px; font-weight: 700;">Password Reset Request</h2>
<p style="font-size: 15px; line-height: 1.7; color: #a0a0b8; margin-bottom: 24px;">
Hi <strong>{safe_username}</strong>, we received a request to reset your portfolio password. Click the button below to set a new password:
</p>
<div style="text-align: center; margin: 32px 0;">
<a href="{safe_reset_url}" style="display: inline-block; background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); color: #ffffff; text-decoration: none; padding: 16px 36px; border-radius: 12px; font-weight: 700; font-size: 16px; box-shadow: 0 10px 25px rgba(239, 68, 68, 0.35);">
🔒 Reset My Password
</a>
</div>
<div style="background: rgba(255, 255, 255, 0.04); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 12px; padding: 14px 18px; margin: 24px 0; word-break: break-all; font-size: 12px; color: #8e8ea6;">
<strong>Direct Link:</strong> <a href="{safe_reset_url}" style="color: #ef4444; text-decoration: underline;">{safe_reset_url}</a>
</div>
<div style="background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.3); border-radius: 12px; padding: 12px 16px; text-align: center;">
<p style="margin: 0; font-size: 13px; color: #fbbf24; font-weight: 600;">
⏱ Link Expires in 15 Minutes
</p>
</div>
</div>
</div>
"""
send_email_async(to_email, subject, html)
def notify_new_message(sender_name, sender_email, message_content, recipient_email=None):
"""Send a portfolio contact notification email."""
clean_subject_name = re.sub(r"[\r\n]+", " ", str(sender_name)).strip()[:80]
safe_name = html_lib.escape(str(sender_name))
safe_email = html_lib.escape(str(sender_email or ""), quote=True)
safe_message = html_lib.escape(str(message_content))
subject = f"New portfolio message from {clean_subject_name or 'visitor'}"
html = f"""
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; max-width: 540px; margin: 0 auto; background: #0d0e15; color: #f0f0f8; border-radius: 18px; overflow: hidden; border: 1px solid rgba(16, 185, 129, 0.25); box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);">
<div style="background: linear-gradient(135deg, #10b981 0%, #06b6d4 100%); padding: 32px 28px; text-align: center;">
<h1 style="color: #ffffff; margin: 0; font-size: 24px; font-weight: 800;">Ahmed Youssef Bosha</h1>
<p style="color: rgba(255, 255, 255, 0.9); margin: 6px 0 0 0; font-size: 14px; font-weight: 500;">New Contact Form Submission</p>
</div>
<div style="padding: 32px 28px;">
<h2 style="color: #ffffff; margin-top: 0; font-size: 20px; font-weight: 700;">📬 You Have a New Message</h2>
<div style="background: #161722; padding: 18px; border-radius: 12px; margin: 20px 0; border: 1px solid rgba(255, 255, 255, 0.08);">
<p style="margin: 0 0 8px 0; font-size: 15px; color: #ffffff;"><strong>From:</strong> {safe_name}</p>
<p style="margin: 0; font-size: 15px; color: #10b981;"><strong>Email:</strong> <a href="mailto:{safe_email}" style="color: #10b981; text-decoration: underline;">{safe_email or 'Not provided'}</a></p>
</div>
<div style="background: #08090e; padding: 20px; border-radius: 12px; border-left: 4px solid #10b981;">
<p style="margin: 0; white-space: pre-wrap; line-height: 1.7; font-size: 15px; color: #e4e4eb;">{safe_message}</p>
</div>
</div>
</div>
"""
send_email_async(recipient_email, subject, html, reply_to=sender_email)
# ---------------------------------------------------------------------------
# Database Helpers & Initialization
# ---------------------------------------------------------------------------
def get_db():
if "db" not in g:
g.db = sqlite3.connect(DATABASE, timeout=15.0)
g.db.row_factory = sqlite3.Row
g.db.execute("PRAGMA foreign_keys = ON")
try:
g.db.execute("PRAGMA journal_mode = DELETE")
g.db.execute("PRAGMA busy_timeout = 5000")
except Exception:
pass
return g.db
@app.teardown_appcontext
def close_db(exc):
db = g.pop("db", None)
if db is not None:
db.close()
def get_settings(user_id=None, db=None):
if db is None:
db = get_db()
if user_id is None:
user_id = session.get("user_id", 1)
s = db.execute("SELECT * FROM site_settings WHERE user_id = ?", (user_id,)).fetchone()
if not s:
# Fallback to default user 1 settings
s = db.execute("SELECT * FROM site_settings WHERE user_id = 1 OR id = 1").fetchone()
return s
def init_db():
"""Create all 9 tables and insert high quality seed data."""
db = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
db.executescript("""
CREATE TABLE IF NOT EXISTS site_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
name TEXT DEFAULT 'Ahmed Youssef Bosha',
logo_text TEXT DEFAULT 'Ahmed Bosha',
site_title TEXT DEFAULT 'Ahmed Youssef Bosha — Computer & Control Engineering Portfolio',
greeting TEXT DEFAULT 'Hi, I''m',
tagline TEXT DEFAULT 'Computer & Control Engineering Student',
typing_texts TEXT DEFAULT 'AI & Machine Learning,Computer Vision,Software Development,Control Systems & Robotics',
bio TEXT DEFAULT 'Third-year Computer & Control Engineering student at Tanta University, ranked 1st in the department and 1st overall in the Faculty of Engineering with a CGPA of 3.986/4.00. I build practical projects across AI, machine learning, computer vision, control systems, and backend software.',
footer_text TEXT DEFAULT '© 2026 Ahmed Youssef Bosha',
profile_photo TEXT,
email TEXT DEFAULT 'ahmedyoussefmansourbosha@gmail.com',
github_url TEXT DEFAULT 'https://github.com/R3Dzf',
linkedin_url TEXT,
twitter_url TEXT,
resume_url TEXT,
color_primary TEXT DEFAULT '#6c63ff',
color_accent TEXT DEFAULT '#ff6b6b',
color_bg TEXT DEFAULT '#0c0c12',
color_surface TEXT DEFAULT '#161622',
color_text TEXT DEFAULT '#f0f0f8',
admin_user TEXT DEFAULT 'admin',
admin_pass_hash TEXT
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT DEFAULT 'user',
account_status TEXT DEFAULT 'active',
plan_tier TEXT DEFAULT 'free',
verification_code TEXT,
code_expires_at TIMESTAMP,
reset_token TEXT,
reset_token_expires_at TIMESTAMP,
is_verified INTEGER DEFAULT 1,
pending_email TEXT,
email_change_code TEXT,
email_change_expires_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS education (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
institution TEXT NOT NULL,
degree TEXT NOT NULL,
field_of_study TEXT NOT NULL,
start_year TEXT NOT NULL,
end_year TEXT NOT NULL,
grade_or_details TEXT,
sort_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS skills (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'Programming & Backend',
level_tag TEXT,
icon TEXT,
sort_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS experiences (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
title TEXT NOT NULL,
company TEXT NOT NULL,
location TEXT,
start_date TEXT NOT NULL,
end_date TEXT,
description TEXT NOT NULL,
is_current INTEGER DEFAULT 0,
sort_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS services (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
title TEXT NOT NULL,
description TEXT NOT NULL,
icon TEXT DEFAULT '⚙️',
sort_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
title TEXT NOT NULL,
description TEXT NOT NULL,
tech_stack TEXT NOT NULL,
github_link TEXT,
live_demo_link TEXT,
certificate_url TEXT,
image TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS achievements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
title TEXT NOT NULL,
issuer TEXT,
date_earned TEXT,
credential_url TEXT,
credential_id TEXT,
image TEXT,
icon TEXT DEFAULT '🏆',
description TEXT,
sort_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS testimonials (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
client_name TEXT NOT NULL,
client_role TEXT NOT NULL,
quote TEXT NOT NULL,
avatar TEXT,
sort_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
sender_name TEXT NOT NULL,
sender_email TEXT NOT NULL,
message TEXT NOT NULL,
is_read INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
CREATE INDEX IF NOT EXISTS idx_site_settings_user_id ON site_settings(user_id);
CREATE INDEX IF NOT EXISTS idx_projects_user_id ON projects(user_id);
CREATE INDEX IF NOT EXISTS idx_skills_user_id ON skills(user_id);
CREATE INDEX IF NOT EXISTS idx_messages_user_id ON messages(user_id);
""")
# Safe Schema Migrations (for backwards compatibility & multi-tenancy)
cursor = db.cursor()
# Rebuild site_settings if it has legacy CHECK (id = 1) constraint
sqlite_master_row = cursor.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='site_settings'").fetchone()
if sqlite_master_row and "CHECK" in sqlite_master_row[0]:
cursor.execute("""
CREATE TABLE site_settings_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER DEFAULT 1,
name TEXT DEFAULT 'Ahmed Youssef Bosha',
logo_text TEXT DEFAULT 'Ahmed Bosha',
site_title TEXT DEFAULT 'Ahmed Youssef Bosha — Computer & Control Engineering Portfolio',
greeting TEXT DEFAULT 'Hi, I''m',
tagline TEXT DEFAULT 'Computer & Control Engineering Student',
typing_texts TEXT DEFAULT 'AI & Machine Learning,Computer Vision,Software Development,Control Systems & Robotics',
bio TEXT DEFAULT 'Third-year Computer & Control Engineering student at Tanta University, ranked 1st in the department and 1st overall in the Faculty of Engineering with a CGPA of 3.986/4.00. I build practical projects across AI, machine learning, computer vision, control systems, and backend software.',
footer_text TEXT DEFAULT '© 2026 Ahmed Youssef Bosha',
profile_photo TEXT,
email TEXT DEFAULT 'ahmedyoussefmansourbosha@gmail.com',
github_url TEXT DEFAULT 'https://github.com/R3Dzf',
linkedin_url TEXT,
twitter_url TEXT,
resume_url TEXT,
color_primary TEXT DEFAULT '#6c63ff',
color_accent TEXT DEFAULT '#ff6b6b',
color_bg TEXT DEFAULT '#0c0c12',
color_surface TEXT DEFAULT '#161622',
color_text TEXT DEFAULT '#f0f0f8',
admin_user TEXT DEFAULT 'admin',
admin_pass_hash TEXT,
theme_name TEXT DEFAULT 'default'
)
""")
try:
cursor.execute("INSERT INTO site_settings_new (id, name, logo_text, site_title, greeting, tagline, typing_texts, bio, footer_text, profile_photo, email, github_url, linkedin_url, twitter_url, resume_url, color_primary, color_accent, color_bg, color_surface, color_text, admin_user, admin_pass_hash) SELECT id, name, logo_text, site_title, greeting, tagline, typing_texts, bio, footer_text, profile_photo, email, github_url, linkedin_url, twitter_url, resume_url, color_primary, color_accent, color_bg, color_surface, color_text, admin_user, admin_pass_hash FROM site_settings")
except Exception:
pass
cursor.execute("DROP TABLE site_settings")
cursor.execute("ALTER TABLE site_settings_new RENAME TO site_settings")
commit_and_sync(db)
# Ensure user_id column exists across all data tables
target_tables = [
"site_settings", "projects", "skills", "experiences",
"education", "services", "achievements", "testimonials", "messages"
]
for table in target_tables:
cursor.execute(f"PRAGMA table_info({table})")
cols = [row[1] for row in cursor.fetchall()]
if "user_id" not in cols:
cursor.execute(f"ALTER TABLE {table} ADD COLUMN user_id INTEGER DEFAULT 1")
# Safe Schema Migrations for users table
cursor.execute("PRAGMA table_info(users)")
user_cols = [row[1] for row in cursor.fetchall()]
needed_user_cols = [
("verification_code", "TEXT"),
("code_expires_at", "TIMESTAMP"),
("reset_token", "TEXT"),
("reset_token_expires_at", "TIMESTAMP"),
("is_verified", "INTEGER DEFAULT 1"),
("pending_email", "TEXT"),
("email_change_code", "TEXT"),
("email_change_expires_at", "TIMESTAMP"),
]
for col, definition in needed_user_cols:
if col not in user_cols:
cursor.execute(f"ALTER TABLE users ADD COLUMN {col} {definition}")
cursor.execute("PRAGMA table_info(site_settings)")
existing_cols = [row[1] for row in cursor.fetchall()]
needed_cols = [
("logo_text", "TEXT DEFAULT 'Ahmed Bosha'"),
("site_title", "TEXT DEFAULT 'Ahmed Youssef Bosha — Computer & Control Engineering Portfolio'"),
("footer_text", "TEXT DEFAULT '© 2026 Ahmed Youssef Bosha'"),
("admin_user", "TEXT DEFAULT 'admin'"),
("admin_pass_hash", "TEXT"),
("theme_name", "TEXT DEFAULT 'default'"),
]
for col, definition in needed_cols:
if col not in existing_cols:
cursor.execute(f"ALTER TABLE site_settings ADD COLUMN {col} {definition}")
# Check achievements table columns
cursor.execute("PRAGMA table_info(achievements)")
ach_cols = [row[1] for row in cursor.fetchall()]
if "credential_id" not in ach_cols:
cursor.execute("ALTER TABLE achievements ADD COLUMN credential_id TEXT")
if "image" not in ach_cols:
cursor.execute("ALTER TABLE achievements ADD COLUMN image TEXT")
# Reserve user id 1 for the portfolio owner.
if db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 0:
admin_pass = os.environ.get("ADMIN_PASS")
admin_user = os.environ.get("ADMIN_USER", "admin").strip() or "admin"
admin_email = os.environ.get(
"ADMIN_EMAIL", "ahmedyoussefmansourbosha@gmail.com"
).strip() or "ahmedyoussefmansourbosha@gmail.com"
if admin_pass:
password_hash = generate_password_hash(admin_pass)
account_status = "active"
else:
# Keep the owner id reserved without exposing a default password.
password_hash = generate_password_hash(secrets.token_urlsafe(48))
account_status = "suspended"
db.execute(
"""INSERT INTO users (id, username, email, password_hash, role, account_status, plan_tier)
VALUES (1, ?, ?, ?, 'admin', ?, 'pro')""",
(admin_user, admin_email, password_hash, account_status),
)
if not admin_pass:
print("[SECURITY] ADMIN_PASS is not set; owner login is disabled until configured.")
commit_and_sync(db)
# ---- 1. Seed site settings ----
if db.execute("SELECT COUNT(*) FROM site_settings").fetchone()[0] == 0:
db.execute(
"""INSERT INTO site_settings
(id, user_id, name, logo_text, site_title, greeting, tagline, typing_texts,
bio, footer_text, profile_photo, email, github_url, theme_name)
VALUES (1, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'default')""",
(
"Ahmed Youssef Bosha",
"Ahmed Bosha",
"Ahmed Youssef Bosha — Computer & Control Engineering Portfolio",
"Hi, I'm",
"Computer & Control Engineering Student",
"AI & Machine Learning,Computer Vision,Software Development,Control Systems & Robotics",
(
"Third-year Computer & Control Engineering student at Tanta University, "
"ranked 1st in the department and 1st overall in the Faculty of Engineering "
"with a CGPA of 3.986/4.00. I build practical projects across AI, machine "
"learning, computer vision, control systems, and backend software."
),
"© 2026 Ahmed Youssef Bosha",
"profile_013e2965.png",
"ahmedyoussefmansourbosha@gmail.com",
"https://github.com/R3Dzf",
),
)
commit_and_sync(db)
# ---- 2. Seed education ----
if db.execute("SELECT COUNT(*) FROM education").fetchone()[0] == 0:
db.executemany(
"INSERT INTO education (institution, degree, field_of_study, start_year, end_year, grade_or_details, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)",
[
(
"Tanta University — Faculty of Engineering",
"Bachelor of Engineering (B.Eng.)",
"Computer & Control Engineering",
"2024",
"2029 (Expected)",
"CGPA: 3.986/4.00 (97.68%). Completed 68 credit hours. Ranked 1st in the Computer & Control Department and 1st overall in the Faculty of Engineering.",
1,
),
],
)
commit_and_sync(db)
# ---- 3. Seed skills ----
if db.execute("SELECT COUNT(*) FROM skills").fetchone()[0] == 0:
db.executemany(
"INSERT INTO skills (name, category, level_tag, icon, sort_order) VALUES (?, ?, ?, ?, ?)",