import hashlib import secrets from datetime import datetime, timezone, timedelta from fastapi import Depends, Request from sqlalchemy.orm import Session from argon2 import PasswordHasher from argon2.exceptions import VerifyMismatchError from . import config from .db import get_db from .models import User, Session as DbSession from .errors import ApiError _ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1, hash_len=32, salt_len=16) _BEARER = 'Bearer realm="messenger"' def hash_password(p: str) -> str: return _ph.hash(p) def verify_password(h: str, p: str) -> bool: try: return _ph.verify(h, p) except VerifyMismatchError: return False def new_session(db: Session, user: User) -> tuple[str, datetime]: token = secrets.token_urlsafe(48) token_hash = hashlib.sha256(token.encode()).hexdigest() expires = datetime.now(timezone.utc) + timedelta(seconds=config.SESSION_TTL_SECONDS) db.add(DbSession(token_hash=token_hash, user_id=user.id, expires_at=expires)) db.commit() return token, expires def current_user(request: Request, db: Session = Depends(get_db)) -> User: auth = request.headers.get("authorization", "") if not auth.lower().startswith("bearer "): raise ApiError(401, "unauthorized", "missing bearer token", challenge=_BEARER) token = auth[7:].strip() token_hash = hashlib.sha256(token.encode()).hexdigest() s = db.get(DbSession, token_hash) if not s: raise ApiError(401, "unauthorized", "invalid session", challenge=_BEARER) if s.expires_at <= datetime.now(timezone.utc): raise ApiError(401, "unauthorized", "expired session", challenge=_BEARER) u = db.get(User, s.user_id) if not u: raise ApiError(401, "unauthorized", "user gone", challenge=_BEARER) return u