from __future__ import annotations import base64 from binascii import Error as Base64Error from fastapi import APIRouter, Depends, Header, HTTPException, status from ...auth.tokens import create_token from ...db.redis import RedisSessionStore from ...domain.models import User from ...services.users import UserService from ..deps import bearer_token, current_user, session_store, user_service from ..schemas import SessionOut, UserOut from ..timefmt import to_rfc3339 router = APIRouter(prefix='/api/v1/auth/sessions', tags=['auth']) _BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' def _unauthorized_basic() -> HTTPException: return HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail='неверные учётные данные', headers={'WWW-Authenticate': _BASIC_CHALLENGE}, ) def _parse_basic(authorization: str | None) -> tuple[str, str]: if not authorization: raise _unauthorized_basic() scheme, separator, encoded = authorization.partition(' ') if scheme.lower() != 'basic' or not separator or not encoded: raise _unauthorized_basic() try: decoded = base64.b64decode(encoded, validate=True).decode('utf-8') except (Base64Error, UnicodeDecodeError): raise _unauthorized_basic() from None username, separator, password = decoded.partition(':') if not separator or not username: raise _unauthorized_basic() return username, password @router.post('', status_code=status.HTTP_201_CREATED, response_model=SessionOut) async def create_session( authorization: str | None = Header(None), users: UserService = Depends(user_service), sessions: RedisSessionStore = Depends(session_store), ) -> SessionOut: username, password = _parse_basic(authorization) user = await users.authenticate(username, password) if user is None: raise _unauthorized_basic() token = create_token() expires_at = await sessions.create(user.id, token) return SessionOut( token=token, token_type='Bearer', expires_at=to_rfc3339(expires_at), user=UserOut.from_domain(user), ) @router.delete('/current', status_code=status.HTTP_204_NO_CONTENT, response_model=None) async def revoke_session( token: str = Depends(bearer_token), _: User = Depends(current_user), sessions: RedisSessionStore = Depends(session_store), ) -> None: await sessions.revoke(token)