import base64 import binascii import os from fastapi import APIRouter, Depends, HTTPException, Request from fastapi.security import HTTPBasic, HTTPBasicCredentials from ..models.schemas import Session from ..storage.postgres import storage router = APIRouter(prefix="/api/v1/auth", tags=["auth"]) DEFAULT_TTL_SECONDS = 3600 def _ttl_seconds() -> int: try: return int(os.environ.get("SESSION_TTL_SECONDS", DEFAULT_TTL_SECONDS)) except ValueError: return DEFAULT_TTL_SECONDS def _parse_basic_header(request: Request) -> tuple[str, str] | None: """Ручной разбор Basic: base64 -> UTF-8 -> split по первому ':'. HTTPBasic из Starlette декодирует latin-1 и ломает кириллицу. Здесь пароль читается как UTF-8 (RFC 7617 разрешает UTF-8 charset). Username остаётся ASCII по контракту. """ raw = request.headers.get("Authorization", "") if not raw.lower().startswith("basic "): return None try: decoded = base64.b64decode(raw[6:].strip(), validate=True).decode("utf-8") except (binascii.Error, UnicodeDecodeError): return None if ":" not in decoded: return None username, password = decoded.split(":", 1) if not username or not password: return None try: username.encode("ascii") except UnicodeEncodeError: return None return username, password @router.post( path="/sessions", summary="Вход: Basic username:password; выдаёт сессию", response_model=Session, status_code=201, ) def create_session(request: Request) -> Session: parsed = _parse_basic_header(request) if parsed is None: raise HTTPException(status_code=401, detail="unauthorized") username, password = parsed user = storage.verify_credentials(username, password) if user is None: raise HTTPException(status_code=401, detail="unauthorized") token, expires_at = storage.create_session(user.id, _ttl_seconds()) return Session(token=token, token_type="Bearer", expires_at=expires_at, user=user) @router.delete( path="/sessions/current", summary="Отозвать текущую сессию", status_code=204, ) def revoke_session(request: Request) -> None: auth = request.headers.get("Authorization", "") if not auth.lower().startswith("bearer "): raise HTTPException(status_code=401, detail="unauthorized") token = auth[7:].strip() if not token or storage.get_session_user(token) is None: raise HTTPException(status_code=401, detail="unauthorized") storage.revoke_session(token) return None