import hashlib from fastapi import APIRouter, Request from fastapi.responses import Response from app.api.deps import current_session from app.api.serialize import user_out from app.core.config import settings from app.core.errors import ApiError from app.core.security import parse_basic, verify_password from app.repositories.memory import iso_z router = APIRouter() BASIC_CHALLENGE = {'WWW-Authenticate': 'Basic realm="messenger", charset="UTF-8"'} @router.post('/api/v1/auth/sessions', status_code=201) async def login(request: Request): # Общий фиксированный интервал защищает все API-реплики от перебора пароля. creds = parse_basic(request.headers.get('authorization', '')) remote = request.client.host if request.client else 'unknown' identity = creds[0] if creds else 'malformed' account_hash = hashlib.sha256(identity.casefold().encode('utf-8')).hexdigest() key = 'login-rate:' + hashlib.sha256(remote.encode('utf-8')).hexdigest() + ':' + account_hash try: count = await request.app.state.redis.incr(key) if count == 1: await request.app.state.redis.expire(key, 60) if count > 10: ttl = max(1, int(await request.app.state.redis.ttl(key))) raise ApiError(429, 'Too many login attempts', headers={'Retry-After': str(ttl)}) except ApiError: raise except Exception: raise ApiError(503, 'Login rate limiter is unavailable') from None storage = request.app.state.storage row = await storage.user_by_username(creds[0]) if creds else None if creds is None or row is None or not verify_password(row.password_hash, creds[1]): raise ApiError(401, 'Invalid credentials', headers=BASIC_CHALLENGE) session = await storage.create_session(row.id, settings.session_ttl_seconds) return {'token': session.token, 'token_type': 'Bearer', 'expires_at': iso_z(session.expires_at), 'user': user_out(row)} @router.delete('/api/v1/auth/sessions/current', status_code=204) async def logout(request: Request): session = await current_session(request) await request.app.state.storage.revoke(session.token) return Response(status_code=204)