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"]) basic_scheme = HTTPBasic(auto_error=False) 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(credentials: HTTPBasicCredentials | None) -> tuple[str, str] | None: """HTTPBasic уже разобрал заголовок; сюда попадают username/password. Дополнительно валидируем кодировку: username — ASCII, пароль — UTF-8. """ if credentials is None: return None username = credentials.username password = credentials.password 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( credentials: HTTPBasicCredentials | None = Depends(basic_scheme), ) -> Session: parsed = _parse_basic(credentials) 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