import base64 import secrets from datetime import datetime, timedelta, timezone from argon2 import PasswordHasher from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHash from fastapi import Header, HTTPException, Request _hasher = PasswordHasher() def hash_password(password: str) -> str: return _hasher.hash(password) def verify_password(password: str, password_hash: str) -> bool: try: _hasher.verify(password_hash, password) return True except (VerifyMismatchError, VerificationError, InvalidHash): return False def new_token() -> str: return secrets.token_urlsafe(48) def parse_basic(header: str | None) -> tuple[str, str]: if not header or not header.lower().startswith("basic "): raise HTTPException(status_code=401, detail="unauthorized") encoded = header.split(" ", 1)[1].strip() try: decoded = base64.b64decode(encoded).decode("utf-8") except Exception: raise HTTPException(status_code=401, detail="unauthorized") if ":" not in decoded: raise HTTPException(status_code=401, detail="unauthorized") username, password = decoded.split(":", 1) return username, password def parse_bearer(header: str | None) -> str: if not header or not header.lower().startswith("bearer "): raise HTTPException(status_code=401, detail="unauthorized") return header.split(" ", 1)[1].strip() async def get_current_user( request: Request, authorization: str | None = Header(default=None), ): token = parse_bearer(authorization) session_store = request.app.state.session_store storage = request.app.state.storage session = await session_store.get(token) if session is None: raise HTTPException(status_code=401, detail="unauthorized") expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00")) if expires_at <= datetime.now(timezone.utc): await session_store.delete(token) raise HTTPException(status_code=401, detail="unauthorized") user = await storage.get_user(session["user_id"]) if user is None: raise HTTPException(status_code=401, detail="unauthorized") return user, token def session_expires_at(ttl_seconds: int) -> datetime: return datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds)