StatistaAmeri/backend/auth.py

81 lines
2.6 KiB
Python

"""
Server-side auth helpers: password hashing (stdlib PBKDF2, no external deps)
and opaque session tokens stored in the DB. Used by main.py for the
register -> admin-approval -> login flow.
"""
import hashlib
import hmac
import secrets
from datetime import datetime, timedelta, timezone
from db import get_conn
_ITER = 600_000 # new hashes; verify_password honours the iters stored per-hash, so old 200k hashes still work
SESSION_DAYS = 7
def hash_password(pw: str) -> str:
salt = secrets.token_bytes(16)
dk = hashlib.pbkdf2_hmac("sha256", pw.encode("utf-8"), salt, _ITER)
return f"pbkdf2_sha256${_ITER}${salt.hex()}${dk.hex()}"
def verify_password(pw: str, stored: str | None) -> bool:
if not stored:
return False
try:
algo, iters, salt_hex, dk_hex = stored.split("$")
if algo != "pbkdf2_sha256":
return False
dk = hashlib.pbkdf2_hmac("sha256", pw.encode("utf-8"), bytes.fromhex(salt_hex), int(iters))
return hmac.compare_digest(dk.hex(), dk_hex)
except Exception:
return False
def create_session(user_id: int) -> str:
token = secrets.token_urlsafe(32)
now = datetime.now(timezone.utc)
exp = now + timedelta(days=SESSION_DAYS)
with get_conn() as c:
c.execute(
"INSERT INTO sessions(token, user_id, created_at, expires_at) VALUES(?,?,?,?)",
(token, user_id, now.isoformat(), exp.isoformat()),
)
return token
def delete_session(token: str | None) -> None:
if not token:
return
with get_conn() as c:
c.execute("DELETE FROM sessions WHERE token=?", (token,))
def revoke_all_sessions(user_id: int) -> None:
"""Kill every active session for a user (e.g. on password change/compromise)."""
with get_conn() as c:
c.execute("DELETE FROM sessions WHERE user_id=?", (user_id,))
def user_for_token(token: str | None):
"""Return the user row for a valid, unexpired session token, else None."""
if not token:
return None
with get_conn() as c:
row = c.execute(
"""SELECT u.id, u.name, u.email, u.phone, u.status, s.expires_at
FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token = ?""",
(token,),
).fetchone()
if not row:
return None
try:
if datetime.fromisoformat(row["expires_at"]) < datetime.now(timezone.utc):
delete_session(token)
return None
except Exception:
return None
return row