ZeroNinerOne commited on
Commit
83e65cb
Β·
verified Β·
1 Parent(s): 4aa03f2

Upload 2 files

Browse files
Files changed (2) hide show
  1. api/database.py +68 -0
  2. api/main.py +1 -2
api/database.py CHANGED
@@ -87,6 +87,16 @@ def init_db() -> None:
87
  CREATE INDEX IF NOT EXISTS idx_sessions_user ON chat_sessions(user_id);
88
  CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_uuid);
89
 
 
 
 
 
 
 
 
 
 
 
90
  CREATE TABLE IF NOT EXISTS user_logs (
91
  id INTEGER PRIMARY KEY AUTOINCREMENT,
92
  user_id INTEGER REFERENCES users(id),
@@ -461,3 +471,61 @@ def migrate_add_logs_table() -> None:
461
  conn.execute("CREATE INDEX IF NOT EXISTS idx_logs_time ON user_logs(created_at)")
462
  except Exception:
463
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  CREATE INDEX IF NOT EXISTS idx_sessions_user ON chat_sessions(user_id);
88
  CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_uuid);
89
 
90
+ CREATE TABLE IF NOT EXISTS password_reset_otps (
91
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
92
+ user_id INTEGER NOT NULL REFERENCES users(id),
93
+ email TEXT NOT NULL,
94
+ otp_hash TEXT NOT NULL,
95
+ expires_at TEXT NOT NULL,
96
+ used INTEGER NOT NULL DEFAULT 0,
97
+ created_at TEXT NOT NULL
98
+ );
99
+
100
  CREATE TABLE IF NOT EXISTS user_logs (
101
  id INTEGER PRIMARY KEY AUTOINCREMENT,
102
  user_id INTEGER REFERENCES users(id),
 
471
  conn.execute("CREATE INDEX IF NOT EXISTS idx_logs_time ON user_logs(created_at)")
472
  except Exception:
473
  pass
474
+
475
+
476
+ # ── Password Reset OTP ────────────────────────────────────────────────────────
477
+
478
+ def save_otp(user_id: int, email: str, otp_hash: str, expires_at: str) -> None:
479
+ """Save a new OTP for password reset. Invalidates any previous OTPs."""
480
+ now = _now()
481
+ with get_conn() as conn:
482
+ # Invalidate old OTPs for this user
483
+ conn.execute("UPDATE password_reset_otps SET used=1 WHERE user_id=?", (user_id,))
484
+ conn.execute(
485
+ "INSERT INTO password_reset_otps (user_id, email, otp_hash, expires_at, used, created_at) "
486
+ "VALUES (?,?,?,?,0,?)",
487
+ (user_id, email, otp_hash, expires_at, now)
488
+ )
489
+
490
+
491
+ def get_valid_otp(email: str) -> dict | None:
492
+ """Get the latest unused, unexpired OTP for an email."""
493
+ from datetime import datetime, timezone
494
+ now = datetime.now(timezone.utc).isoformat()
495
+ with get_conn() as conn:
496
+ row = conn.execute(
497
+ "SELECT * FROM password_reset_otps "
498
+ "WHERE email=? AND used=0 AND expires_at > ? "
499
+ "ORDER BY id DESC LIMIT 1",
500
+ (email.lower(), now)
501
+ ).fetchone()
502
+ return dict(row) if row else None
503
+
504
+
505
+ def mark_otp_used(otp_id: int) -> None:
506
+ with get_conn() as conn:
507
+ conn.execute("UPDATE password_reset_otps SET used=1 WHERE id=?", (otp_id,))
508
+
509
+
510
+ def update_user_password(user_id: int, new_hash: str) -> None:
511
+ with get_conn() as conn:
512
+ conn.execute("UPDATE users SET password_hash=? WHERE id=?", (new_hash, user_id))
513
+
514
+
515
+ def migrate_add_otp_table() -> None:
516
+ """Safe migration β€” adds OTP table to existing databases."""
517
+ try:
518
+ with get_conn() as conn:
519
+ conn.execute("""
520
+ CREATE TABLE IF NOT EXISTS password_reset_otps (
521
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
522
+ user_id INTEGER NOT NULL REFERENCES users(id),
523
+ email TEXT NOT NULL,
524
+ otp_hash TEXT NOT NULL,
525
+ expires_at TEXT NOT NULL,
526
+ used INTEGER NOT NULL DEFAULT 0,
527
+ created_at TEXT NOT NULL
528
+ )
529
+ """)
530
+ except Exception:
531
+ pass
api/main.py CHANGED
@@ -68,9 +68,8 @@ async def lifespan(app: FastAPI):
68
  from api.database import init_db, migrate_add_admin_column, set_admin, get_user_by_username, DB_PATH
69
  init_db()
70
  migrate_add_admin_column()
71
- from api.database import migrate_add_logs_table, migrate_add_otp_table
72
  migrate_add_logs_table()
73
- migrate_add_otp_table()
74
  # Log exact DB path so we can verify persistent storage is mounted
75
  logger.info("[NeuroCheck] SQLite database initialized at: {}", str(DB_PATH))
76
  logger.info("[NeuroCheck] DB exists on disk: {}", DB_PATH.exists())
 
68
  from api.database import init_db, migrate_add_admin_column, set_admin, get_user_by_username, DB_PATH
69
  init_db()
70
  migrate_add_admin_column()
71
+ from api.database import migrate_add_logs_table
72
  migrate_add_logs_table()
 
73
  # Log exact DB path so we can verify persistent storage is mounted
74
  logger.info("[NeuroCheck] SQLite database initialized at: {}", str(DB_PATH))
75
  logger.info("[NeuroCheck] DB exists on disk: {}", DB_PATH.exists())