-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.py
More file actions
2705 lines (2257 loc) · 87.3 KB
/
Copy pathbackend.py
File metadata and controls
2705 lines (2257 loc) · 87.3 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
# Dateizweck: Modul "backend" im Bereich "root".
# Hinweis: Zentrale Logik fuer LearnHub-Funktionen.
# =========================================
# LearnHub Backend
# Autor: Backend-Team
# Technologie: FastAPI + SQLite
# =========================================
from fastapi import UploadFile, File, Form
from fastapi.responses import FileResponse
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, Field, field_validator
from typing import List, Optional
from datetime import datetime, timedelta
import sqlite3
import uuid
import hashlib
import os
import re
import secrets
import smtplib
import ssl
import json
import bcrypt
from email.message import EmailMessage
UPLOAD_DIR = "uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
# Funktion: load_local_env_files - verarbeitet die zugehoerige Backend-Operation.
def load_local_env_files():
"""Lädt lokale .env-Dateien und übernimmt fehlende Variablen in die Umgebung."""
env_paths = [".venv/.env", ".env"]
for env_path in env_paths:
if not os.path.exists(env_path):
continue
with open(env_path, "r", encoding="utf-8") as f:
for raw_line in f:
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
value = value.strip().strip('"').strip("'")
if key and key not in os.environ:
os.environ[key] = value
load_local_env_files()
# =========================================
# APP INITIALISIERUNG
# =========================================
app = FastAPI(
title="LearnHub API",
description="Backend für die LearnHub Lernplattform",
version="1.0.0"
)
# CORS erlauben, damit das PHP‑Frontend (oder andere Hosts) die API ansprechen kann
# während der Entwicklung ist "*" ok, später enger einschränken.
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:8080",
"http://127.0.0.1:8080",
"https://localhost:8080",
"https://127.0.0.1:8080",
],
allow_origin_regex=r"https://.*\.app\.github\.dev",
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
allow_headers=["Content-Type", "Authorization"],
)
DB_NAME = "learnhub.db"
VERIFICATION_TTL_MINUTES = 10
# =========================================
# DATABASE SETUP
# =========================================
# Funktion: get_db - verarbeitet die zugehoerige Backend-Operation.
def get_db():
"""Erzeugt eine SQLite-Verbindung mit Row-Factory für Dict-ähnlichen Zugriff."""
conn = sqlite3.connect(DB_NAME)
conn.row_factory = sqlite3.Row
return conn
# Funktion: init_db - verarbeitet die zugehoerige Backend-Operation.
def init_db():
"""Initialisiert alle Tabellen und führt einfache Datenbank-Migrationen aus."""
db = get_db()
cursor = db.cursor()
# FILES
cursor.execute("""
CREATE TABLE IF NOT EXISTS files (
id TEXT PRIMARY KEY,
user_id TEXT,
filename TEXT,
original_name TEXT,
subject TEXT,
uploaded_at TEXT
)
""")
# USERS
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT UNIQUE,
email TEXT,
password TEXT,
role TEXT,
created_at TEXT
)
""")
# TODOS
cursor.execute("""
CREATE TABLE IF NOT EXISTS todos (
id TEXT PRIMARY KEY,
user_id TEXT,
title TEXT,
subject TEXT,
due_date TEXT,
priority TEXT,
done INTEGER
)
""")
# HOMEWORK
cursor.execute("""
CREATE TABLE IF NOT EXISTS homework_entries (
id TEXT PRIMARY KEY,
user_id TEXT,
day TEXT,
period INTEGER,
title TEXT,
created_at TEXT
)
""")
# EXAMS
cursor.execute("""
CREATE TABLE IF NOT EXISTS exams (
id TEXT PRIMARY KEY,
user_id TEXT,
subject TEXT,
date TEXT,
topic TEXT,
period INTEGER,
end_period INTEGER,
grade REAL,
created_at TEXT
)
""")
# CALENDAR EXTRAS
cursor.execute("""
CREATE TABLE IF NOT EXISTS calendar_extras (
id TEXT PRIMARY KEY,
user_id TEXT,
title TEXT,
date TEXT,
repeat_weekly INTEGER DEFAULT 0,
recurrence TEXT DEFAULT 'none',
exception_dates TEXT DEFAULT '[]',
description TEXT,
color TEXT DEFAULT '#0d6efd',
start_time TEXT,
end_time TEXT,
created_at TEXT
)
""")
try:
cursor.execute("ALTER TABLE calendar_extras ADD COLUMN repeat_weekly INTEGER DEFAULT 0")
except Exception:
pass
try:
cursor.execute("ALTER TABLE calendar_extras ADD COLUMN recurrence TEXT DEFAULT 'none'")
except Exception:
pass
try:
cursor.execute("ALTER TABLE calendar_extras ADD COLUMN exception_dates TEXT DEFAULT '[]'")
except Exception:
pass
try:
cursor.execute("ALTER TABLE calendar_extras ADD COLUMN color TEXT DEFAULT '#0d6efd'")
except Exception:
pass
try:
cursor.execute("ALTER TABLE calendar_extras ADD COLUMN start_time TEXT")
except Exception:
pass
try:
cursor.execute("ALTER TABLE calendar_extras ADD COLUMN end_time TEXT")
except Exception:
pass
cursor.execute(
"""
UPDATE calendar_extras
SET recurrence='weekly'
WHERE repeat_weekly=1 AND (recurrence IS NULL OR recurrence='' OR recurrence='none')
"""
)
# GRADES
cursor.execute("""
CREATE TABLE IF NOT EXISTS grades (
id TEXT PRIMARY KEY,
user_id TEXT,
subject TEXT,
value REAL,
description TEXT,
date TEXT,
weight REAL DEFAULT 1,
source_exam_id TEXT
)
""")
# Add weight column if it doesn't exist yet (migration path for existing DBs)
try:
cursor.execute("ALTER TABLE grades ADD COLUMN weight REAL DEFAULT 1")
except Exception:
pass # column already present
try:
cursor.execute("ALTER TABLE grades ADD COLUMN source_exam_id TEXT")
except Exception:
pass # column already present
# Add grade column to exams if it doesn't exist yet (migration path for existing DBs)
try:
cursor.execute("ALTER TABLE exams ADD COLUMN grade REAL")
except Exception:
pass # column already present
# Add end_period column to exams if it doesn't exist yet (migration path for existing DBs)
try:
cursor.execute("ALTER TABLE exams ADD COLUMN end_period INTEGER")
except Exception:
pass # column already present
# TIMETABLE
# original structure contained only day/time/subject; we extend with period and room
cursor.execute("""
CREATE TABLE IF NOT EXISTS timetable (
id TEXT PRIMARY KEY,
user_id TEXT,
day TEXT,
period INTEGER,
time TEXT,
subject TEXT,
room TEXT
)
""")
# ensure new columns exist in older databases
try:
cursor.execute("ALTER TABLE timetable ADD COLUMN period INTEGER")
except Exception:
pass # column already present
try:
cursor.execute("ALTER TABLE timetable ADD COLUMN room TEXT")
except Exception:
pass # column already present
# Repair rows that were written with a wrong column order.
# Old buggy writes stored values as:
# - time <- period
# - subject<- time
# - period <- subject
cursor.execute("SELECT id, time, subject, period FROM timetable")
timetable_rows = cursor.fetchall()
def _parse_period(value):
"""Parst einen möglichen Stundenwert und akzeptiert nur gültige Perioden."""
if value is None:
return None
try:
p = int(str(value).strip())
return p if 1 <= p <= 10 else None
except Exception:
return None
def _looks_like_time(value):
"""Prüft, ob ein Wert wie eine Uhrzeit im Format HH:MM aussieht."""
if value is None:
return False
return bool(re.match(r"^\d{1,2}:\d{2}$", str(value).strip()))
for row in timetable_rows:
existing_period = _parse_period(row["period"])
time_as_period = _parse_period(row["time"])
if existing_period is not None:
continue
if time_as_period is None:
continue
if not _looks_like_time(row["subject"]):
continue
fixed_subject = "" if row["period"] is None else str(row["period"]).strip()
fixed_time = str(row["subject"]).strip()
cursor.execute(
"""
UPDATE timetable
SET time=?, subject=?, period=?
WHERE id=?
""",
(fixed_time, fixed_subject, time_as_period, row["id"])
)
# separate table for storing period times; this allows the user to configure slot times even if
# no classes are set in that period
cursor.execute("""
CREATE TABLE IF NOT EXISTS timetable_times (
user_id TEXT,
period INTEGER,
time TEXT,
PRIMARY KEY(user_id, period)
)
""")
# FLASHCARD DECKS
cursor.execute("""
CREATE TABLE IF NOT EXISTS flashcard_decks (
id TEXT PRIMARY KEY,
user_id TEXT,
name TEXT,
subject TEXT,
description TEXT,
public INTEGER,
created_at TEXT
)
""")
# FLASHCARDS
cursor.execute("""
CREATE TABLE IF NOT EXISTS flashcards (
id TEXT PRIMARY KEY,
user_id TEXT,
subject TEXT,
front TEXT,
back TEXT,
public INTEGER
)
""")
# Add deck_id column if it doesn't exist yet
try:
cursor.execute("ALTER TABLE flashcards ADD COLUMN deck_id TEXT")
except Exception:
pass # Column already exists
# E-MAIL VERIFICATION CODES
cursor.execute("""
CREATE TABLE IF NOT EXISTS email_verifications (
id TEXT PRIMARY KEY,
user_id TEXT,
email TEXT,
purpose TEXT,
code_hash TEXT,
payload TEXT,
expires_at TEXT,
created_at TEXT
)
""")
# LOGIN ATTEMPTS (for security/admin analytics)
cursor.execute("""
CREATE TABLE IF NOT EXISTS login_attempts (
id TEXT PRIMARY KEY,
user_id TEXT,
username TEXT,
success INTEGER,
created_at TEXT
)
""")
# USER ACTIVITY (lightweight event log for admin analytics)
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_activity (
id TEXT PRIMARY KEY,
user_id TEXT,
event_type TEXT,
created_at TEXT
)
""")
# ADMIN MESSAGES
cursor.execute("""
CREATE TABLE IF NOT EXISTS admin_messages (
id TEXT PRIMARY KEY,
sender_user_id TEXT,
recipient_user_id TEXT,
title TEXT,
body TEXT,
created_at TEXT
)
""")
# SUBJECTS (Fächer)
cursor.execute("""
CREATE TABLE IF NOT EXISTS subjects (
id TEXT PRIMARY KEY,
user_id TEXT,
name TEXT,
color TEXT,
created_at TEXT
)
""")
# Ensure there is at least one admin in existing databases.
cursor.execute("SELECT COUNT(*) AS total FROM users WHERE lower(role)='admin'")
admin_count = cursor.fetchone()["total"]
if admin_count == 0:
cursor.execute("SELECT id FROM users ORDER BY created_at ASC LIMIT 1")
first_user = cursor.fetchone()
if first_user:
cursor.execute("UPDATE users SET role='admin' WHERE id=?", (first_user["id"],))
db.commit()
db.close()
init_db()
# =========================================
# HILFSFUNKTIONEN
# =========================================
# bcrypt-Kontext für sicheres Passwort-Hashing
# Funktion: hash_password - verarbeitet die zugehoerige Backend-Operation.
def hash_password(password: str) -> str:
"""Erstellt einen sicheren bcrypt-Hash des Passworts."""
salt = bcrypt.gensalt(rounds=12)
return bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8')
# Funktion: verify_password - prüft Passwort gegen gespeicherten Hash.
def verify_password(plain_password: str, hashed_password: str, db=None, user_id: str = None) -> bool:
"""Vergleicht Klartextpasswort mit gespeichertem Hash.
Unterstützt Migration von alten SHA-256-Hashes zu bcrypt."""
# Bcrypt-Hash erkennen (beginnt mit $2b$, $2a$ oder $2y$)
if hashed_password.startswith(("$2b$", "$2a$", "$2y$")):
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
# Fallback: SHA-256 für alte Accounts (Migration)
old_hash = hashlib.sha256(plain_password.encode()).hexdigest()
if old_hash == hashed_password:
# Automatische Migration zu bcrypt beim nächsten Login
if db is not None and user_id is not None:
new_hash = hash_password(plain_password)
_cursor = db.cursor()
_cursor.execute("UPDATE users SET password=? WHERE id=?", (new_hash, user_id))
db.commit()
return True
return False
# Funktion: generate_id - verarbeitet die zugehoerige Backend-Operation.
def generate_id() -> str:
"""Erzeugt eine neue UUID als String."""
return str(uuid.uuid4())
# Funktion: is_valid_email - verarbeitet die zugehoerige Backend-Operation.
def is_valid_email(email: str) -> bool:
"""Prüft eine E-Mail-Adresse mit einer einfachen Strukturvalidierung."""
if not email or "@" not in email:
return False
local, _, domain = email.partition("@")
return bool(local and domain and "." in domain)
# Funktion: normalize_hex_color - verarbeitet die zugehoerige Backend-Operation.
def normalize_hex_color(value: Optional[str], default: str = "#0d6efd") -> str:
"""Normalisiert erlaubte Hex-Farben und fällt sonst auf einen Standardwert zurück."""
color = str(value or "").strip()
if re.fullmatch(r"#[0-9a-fA-F]{6}", color):
return color.lower()
return default
# Funktion: normalize_time_value - verarbeitet die zugehoerige Backend-Operation.
def normalize_time_value(value: Optional[str]) -> str:
"""Validiert eine Uhrzeit im 24-Stunden-Format und gibt sonst einen Leerstring zurück."""
time_value = str(value or "").strip()
if re.fullmatch(r"([01]\d|2[0-3]):[0-5]\d", time_value):
return time_value
return ""
# Funktion: hash_verification_code - verarbeitet die zugehoerige Backend-Operation.
def hash_verification_code(code: str) -> str:
"""Hasht einen Verifizierungscode für die sichere Speicherung in der Datenbank."""
return hashlib.sha256(code.encode()).hexdigest()
# Funktion: log_login_attempt - verarbeitet die zugehoerige Backend-Operation.
def log_login_attempt(db, username: str, success: bool, user_id: Optional[str] = None):
"""Speichert einen erfolgreichen oder fehlgeschlagenen Login-Versuch."""
cursor = db.cursor()
cursor.execute(
"""
INSERT INTO login_attempts VALUES (?, ?, ?, ?, ?)
""",
(
generate_id(),
user_id,
username,
1 if success else 0,
datetime.utcnow().isoformat()
)
)
db.commit()
# Funktion: log_user_activity - verarbeitet die zugehoerige Backend-Operation.
def log_user_activity(db, user_id: str, event_type: str):
"""Protokolliert ein leichtgewichtiges Benutzerereignis für Auswertungen."""
cursor = db.cursor()
cursor.execute(
"""
INSERT INTO user_activity VALUES (?, ?, ?, ?)
""",
(
generate_id(),
user_id,
event_type,
datetime.utcnow().isoformat()
)
)
db.commit()
# Funktion: require_admin_user - verarbeitet die zugehoerige Backend-Operation.
def require_admin_user(cursor, user_id: str):
"""Stellt sicher, dass eine vorhandene Nutzer-ID zur Admin-Rolle gehört."""
cursor.execute("SELECT id, role FROM users WHERE id=?", (user_id,))
user_row = cursor.fetchone()
if not user_row:
raise HTTPException(status_code=404, detail="User nicht gefunden")
if (user_row["role"] or "").lower() != "admin":
raise HTTPException(status_code=403, detail="Nur Admins haben Zugriff")
# Funktion: send_verification_email - verarbeitet die zugehoerige Backend-Operation.
def send_verification_email(receiver_email: str, code: str, purpose: str):
"""Versendet einen Verifizierungscode per SMTP."""
smtp_host = os.getenv("LEARNHUB_SMTP_HOST", "smtp.web.de")
smtp_port = int(os.getenv("LEARNHUB_SMTP_PORT", "465"))
smtp_email = os.getenv("LEARNHUB_SMTP_EMAIL")
smtp_password = os.getenv("LEARNHUB_SMTP_PASSWORD")
sender_name = os.getenv("LEARNHUB_SMTP_SENDER_NAME", "LearnHub")
use_ssl = os.getenv("LEARNHUB_SMTP_USE_SSL", "1") == "1"
use_starttls = os.getenv("LEARNHUB_SMTP_USE_STARTTLS", "0") == "1"
if not smtp_email or not smtp_password:
raise HTTPException(
status_code=500,
detail="E-Mail-Versand ist nicht konfiguriert (LEARNHUB_SMTP_EMAIL/LEARNHUB_SMTP_PASSWORD fehlen)"
)
subject_map = {
"register": "Dein LearnHub Verifizierungscode (Registrierung)",
"change_email": "Dein LearnHub Verifizierungscode (E-Mail-Aenderung)",
"delete_account": "Dein LearnHub Verifizierungscode (Account-Loeschung)"
}
subject = subject_map.get(purpose, "LearnHub Verifizierungscode")
text_content = (
f"Hallo,\n\n"
f"dein Verifizierungscode lautet: {code}\n"
f"Der Code ist {VERIFICATION_TTL_MINUTES} Minuten gueltig.\n\n"
"Wenn du diese Aktion nicht gestartet hast, ignoriere diese E-Mail.\n\n"
"LearnHub"
)
message = EmailMessage()
message["Subject"] = subject
message["From"] = f"{sender_name} <{smtp_email}>"
message["To"] = receiver_email
message.set_content(text_content)
try:
context = ssl.create_default_context()
if use_ssl:
with smtplib.SMTP_SSL(smtp_host, smtp_port, context=context, timeout=20) as server:
server.login(smtp_email, smtp_password)
server.send_message(message)
else:
with smtplib.SMTP(smtp_host, smtp_port, timeout=20) as server:
if use_starttls:
server.starttls(context=context)
server.login(smtp_email, smtp_password)
server.send_message(message)
except Exception as exc:
raise HTTPException(status_code=502, detail=f"SMTP Versand fehlgeschlagen: {exc}") from exc
# Funktion: cleanup_expired_verifications - verarbeitet die zugehoerige Backend-Operation.
def cleanup_expired_verifications(db):
"""Entfernt abgelaufene Verifizierungsdatensätze aus der Datenbank."""
cursor = db.cursor()
cursor.execute(
"DELETE FROM email_verifications WHERE expires_at < ?",
(datetime.utcnow().isoformat(),)
)
# Funktion: create_verification - verarbeitet die zugehoerige Backend-Operation.
def create_verification(db, user_id: Optional[str], email: str, purpose: str, payload: dict):
"""Erzeugt einen Verifizierungseintrag, speichert ihn und verschickt den Code."""
cleanup_expired_verifications(db)
cursor = db.cursor()
verification_id = generate_id()
code = f"{secrets.randbelow(1000000):06d}"
now = datetime.utcnow()
expires_at = now + timedelta(minutes=VERIFICATION_TTL_MINUTES)
cursor.execute("""
INSERT INTO email_verifications VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (
verification_id,
user_id,
email,
purpose,
hash_verification_code(code),
json.dumps(payload),
expires_at.isoformat(),
now.isoformat()
))
db.commit()
send_verification_email(email, code, purpose)
return verification_id
# Funktion: consume_verification - verarbeitet die zugehoerige Backend-Operation.
def consume_verification(db, verification_id: str, code: str, purpose: str, user_id: Optional[str]):
"""Validiert einen Verifizierungscode, verbraucht ihn und gibt den Datensatz zurück."""
cleanup_expired_verifications(db)
cursor = db.cursor()
cursor.execute(
"SELECT * FROM email_verifications WHERE id=? AND purpose=?",
(verification_id, purpose)
)
verification = cursor.fetchone()
if not verification:
raise HTTPException(status_code=400, detail="Verifizierung ungültig oder abgelaufen")
if user_id is not None and verification["user_id"] != user_id:
raise HTTPException(status_code=403, detail="Verifizierung gehört zu einem anderen User")
if verification["code_hash"] != hash_verification_code(code):
raise HTTPException(status_code=400, detail="Verifizierungscode ist falsch")
cursor.execute("DELETE FROM email_verifications WHERE id=?", (verification_id,))
db.commit()
return verification
# =========================================
# Pydantic MODELS (Request / Response)
# =========================================
# Datenmodell: ChangeUsername - definiert den erwarteten Request-Body.
class ChangeUsername(BaseModel):
new_username: str
# Datenmodell: ChangePassword - definiert den erwarteten Request-Body.
class ChangePassword(BaseModel):
old_password: str
new_password: str
# Datenmodell: ChangeEmail - definiert den erwarteten Request-Body.
class ChangeEmail(BaseModel):
new_email: str
# Datenmodell: UserRegister - definiert den erwarteten Request-Body.
class UserRegister(BaseModel):
username: str
email: str
password: str
# Datenmodell: RegisterCodeConfirm - definiert den erwarteten Request-Body.
class RegisterCodeConfirm(BaseModel):
verification_id: str
code: str
# Datenmodell: ChangeEmailCodeConfirm - definiert den erwarteten Request-Body.
class ChangeEmailCodeConfirm(BaseModel):
verification_id: str
code: str
# Datenmodell: DeleteAccountRequest - definiert den erwarteten Request-Body.
class DeleteAccountRequest(BaseModel):
password: str
# Datenmodell: DeleteAccountCodeConfirm - definiert den erwarteten Request-Body.
class DeleteAccountCodeConfirm(BaseModel):
verification_id: str
code: str
# Datenmodell: UserLogin - definiert den erwarteten Request-Body.
class UserLogin(BaseModel):
username: str
password: str
# Datenmodell: TodoCreate - definiert den erwarteten Request-Body.
class TodoCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=200)
subject: str = Field("", max_length=100)
due_date: str = Field("", max_length=20)
priority: str = Field("medium")
@field_validator('priority')
@classmethod
def validate_priority(cls, v):
"""Beschränkt die To-do-Priorität auf die unterstützten Werte."""
allowed = ('low', 'medium', 'high')
if v not in allowed:
raise ValueError(f'Prioritaet muss eines von {allowed} sein')
return v
# Datenmodell: HomeworkCreate - definiert den erwarteten Request-Body.
class HomeworkCreate(BaseModel):
day: str = Field(..., min_length=1, max_length=20)
period: int = Field(..., ge=1, le=15)
title: str = Field(..., min_length=1, max_length=200)
# Datenmodell: ExamCreate - definiert den erwarteten Request-Body.
class ExamCreate(BaseModel):
subject: str = Field(..., min_length=1, max_length=100)
date: str = Field(..., min_length=1, max_length=20)
topic: Optional[str] = Field("", max_length=300)
period: Optional[int] = Field(None, ge=1, le=15)
period_end: Optional[int] = Field(None, ge=1, le=15)
# Datenmodell: CalendarExtraCreate - definiert den erwarteten Request-Body.
class CalendarExtraCreate(BaseModel):
title: str
date: str
recurrence: str = "none"
description: Optional[str] = ""
color: Optional[str] = "#0d6efd"
start_time: Optional[str] = None
end_time: Optional[str] = None
# Datenmodell: AdminMessageCreate - definiert den erwarteten Request-Body.
class AdminMessageCreate(BaseModel):
title: str
body: str
recipient_user_id: Optional[str] = None
# Datenmodell: AdminRoleUpdate - definiert den erwarteten Request-Body.
class AdminRoleUpdate(BaseModel):
role: str
@field_validator('role')
@classmethod
def validate_role(cls, v):
"""Normalisiert Rollenangaben auf die erlaubten Werte admin oder user."""
allowed = ('admin', 'user')
if v.lower() not in allowed:
raise ValueError(f'Rolle muss eines von {allowed} sein')
return v.lower()
# Datenmodell: GradeCreate - definiert den erwarteten Request-Body.
class GradeCreate(BaseModel):
subject: str = Field(..., min_length=1, max_length=100)
value: float = Field(..., ge=0, le=15)
weight: float = Field(1.0, gt=0, le=100)
description: Optional[str] = Field("", max_length=500)
source_exam_id: Optional[str] = Field(None, max_length=64)
# Datenmodell: SubjectCreate - definiert den erwarteten Request-Body.
class SubjectCreate(BaseModel):
name: str
color: str
# Datenmodell: FlashcardCreate - definiert den erwarteten Request-Body.
class FlashcardCreate(BaseModel):
subject: str
front: str
back: str
public: bool = False
# Datenmodell: FlashcardDeckCreate - definiert den erwarteten Request-Body.
class FlashcardDeckCreate(BaseModel):
name: str
subject: Optional[str] = ""
description: Optional[str] = ""
public: bool = False
# Datenmodell: FlashcardDeckUpdate - definiert den erwarteten Request-Body.
class FlashcardDeckUpdate(BaseModel):
name: Optional[str] = None
subject: Optional[str] = None
description: Optional[str] = None
public: Optional[bool] = None
# Datenmodell: FlashcardCardCreate - definiert den erwarteten Request-Body.
class FlashcardCardCreate(BaseModel):
front: str
back: str
# Datenmodell: TimetableCreate - definiert den erwarteten Request-Body.
class TimetableCreate(BaseModel):
day: str = Field(...) # monday, tuesday, ...
period: int = Field(..., ge=1, le=15) # 1..10 (Stunde im Raster)
time: str = Field("", max_length=30) # "08:00 - 09:30" (eingetragene Zeit für diese Stunde)
subject: str = Field(..., min_length=1, max_length=100)
room: Optional[str] = Field("", max_length=50)
@field_validator('day')
@classmethod
def validate_day(cls, v):
"""Prüft, dass ein Wochentag als unterstützter englischer Key vorliegt."""
allowed = ('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday')
if v.lower() not in allowed:
raise ValueError(f'Tag muss eines von {allowed} sein')
return v.lower()
# Datenmodell: TimetableBulk - definiert den erwarteten Request-Body.
class TimetableBulk(BaseModel):
entries: List[TimetableCreate] = []
times: Optional[dict] = {}
# =========================================
# AUTH ROUTES
# =========================================
# Endpoint: POST /auth/register - API-Route mit Validierung und Datenverarbeitung.
@app.post("/auth/register")
# Funktion: register - verarbeitet die zugehoerige Backend-Operation.
def register(user: UserRegister):
"""Startet die Registrierung und legt eine E-Mail-Verifizierung für neue Nutzer an."""
db = get_db()
cursor = db.cursor()
if not is_valid_email(user.email):
raise HTTPException(status_code=400, detail="Ungültige E-Mail-Adresse")
cursor.execute("SELECT id FROM users WHERE username=?", (user.username,))
if cursor.fetchone():
raise HTTPException(status_code=400, detail="Username existiert bereits")
verification_id = create_verification(
db=db,
user_id=None,
email=user.email,
purpose="register",
payload={
"username": user.username,
"email": user.email,
"password_hash": hash_password(user.password)
}
)
return {
"message": "Verifizierungscode wurde versendet",
"verification_id": verification_id,
"expires_in_minutes": VERIFICATION_TTL_MINUTES
}
# Endpoint: POST /auth/register/confirm - API-Route mit Validierung und Datenverarbeitung.
@app.post("/auth/register/confirm")
# Funktion: register_confirm - verarbeitet die zugehoerige Backend-Operation.
def register_confirm(data: RegisterCodeConfirm):
"""Bestätigt die Registrierung und erstellt den Benutzer nach erfolgreicher Codeprüfung."""
db = get_db()
cursor = db.cursor()
verification = consume_verification(
db=db,
verification_id=data.verification_id,
code=data.code,
purpose="register",
user_id=None
)
payload = json.loads(verification["payload"])
cursor.execute("SELECT id FROM users WHERE username=?", (payload["username"],))
if cursor.fetchone():
raise HTTPException(status_code=400, detail="Username existiert bereits")
cursor.execute("SELECT COUNT(*) AS total FROM users")
users_total = cursor.fetchone()["total"]
new_role = "admin" if users_total == 0 else "user"
try:
cursor.execute("""
INSERT INTO users VALUES (?, ?, ?, ?, ?, ?)
""", (
generate_id(),
payload["username"],
payload["email"],
payload["password_hash"],
new_role,
datetime.utcnow().isoformat()
))
db.commit()
except sqlite3.IntegrityError:
raise HTTPException(status_code=400, detail="Username existiert bereits")
return {"message": "Registrierung erfolgreich"}
# Endpoint: PUT /auth/change-username/{user_id} - API-Route mit Validierung und Datenverarbeitung.
@app.put("/auth/change-username/{user_id}")
# Funktion: change_username - verarbeitet die zugehoerige Backend-Operation.
def change_username(user_id: str, data: ChangeUsername):
"""Ändert den Benutzernamen eines vorhandenen Nutzers, sofern er noch frei ist."""
db = get_db()
cursor = db.cursor()
# Prüfen ob Username bereits existiert
cursor.execute(
"SELECT id FROM users WHERE username=?",
(data.new_username,)
)
if cursor.fetchone():
raise HTTPException(status_code=400, detail="Username bereits vergeben")
cursor.execute("""
UPDATE users
SET username=?
WHERE id=?
""", (data.new_username, user_id))
if cursor.rowcount == 0:
raise HTTPException(status_code=404, detail="User nicht gefunden")
db.commit()
db.close()
return {"message": "Username erfolgreich geändert"}
# Endpoint: PUT /auth/change-password/{user_id} - API-Route mit Validierung und Datenverarbeitung.
@app.put("/auth/change-password/{user_id}")
# Funktion: change_password - verarbeitet die zugehoerige Backend-Operation.
def change_password(user_id: str, data: ChangePassword):
"""Aktualisiert das Passwort nach Prüfung des bisherigen Kennworts."""
db = get_db()
cursor = db.cursor()
cursor.execute("""
SELECT password FROM users WHERE id=?
""", (user_id,))
user = cursor.fetchone()
if not user:
raise HTTPException(status_code=404, detail="User nicht gefunden")
if not verify_password(data.old_password, user["password"], db, user_id):
raise HTTPException(status_code=401, detail="Altes Passwort ist falsch")
cursor.execute("""
UPDATE users
SET password=?
WHERE id=?
""", (hash_password(data.new_password), user_id))
db.commit()
db.close()