import secrets from datetime import datetime, timezone, timedelta import asyncio import hashlib import bcrypt from argon2 import PasswordHasher from argon2.exceptions import VerificationError, InvalidHashError from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from sqlalchemy import select from app.database import async_session_maker from app.models.user import User from app.redis_client import redis_client from app.config import SESSION_TTL_SECONDS pwd_context = PasswordHasher( memory_cost=19456, time_cost=2, parallelism=1, ) password_slots = asyncio.Semaphore(2) bearer_scheme = HTTPBearer(auto_error=False) async def get_password_hash(password: str) -> str: async with password_slots: return await asyncio.to_thread(pwd_context.hash, password) def verify_password(plain: str, hashed: str) -> bool: try: if hashed.startswith(("$2b$", "$2a$", "$2y$")): password = plain.encode() return len(password) <= 72 and bcrypt.checkpw(password, hashed.encode()) return pwd_context.verify(hashed, plain) except (VerificationError, InvalidHashError, ValueError): return False async def check_password(plain: str, hashed: str) -> bool: async with password_slots: return await asyncio.to_thread(verify_password, plain, hashed) def session_key(token: str) -> str: return "session:" + hashlib.sha256(token.encode()).hexdigest() async def create_session(user_id: str) -> dict: token = secrets.token_urlsafe(32) expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS) await redis_client.setex( name=session_key(token), time=SESSION_TTL_SECONDS, value=str(user_id), ) return { "token": token, "token_type": "Bearer", "expires_at": expires_at.isoformat().replace("+00:00", "Z"), } async def delete_session(token: str) -> None: await redis_client.delete(session_key(token)) async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)): if not credentials: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, ) token = credentials.credentials try: user_id = await redis_client.get(session_key(token)) except Exception: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Внутренняя ошибка сервера" ) if not user_id: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired token", headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, ) async with async_session_maker() as session: result = await session.execute(select(User).where(User.id == user_id)) user = result.scalar_one_or_none() if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found", headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, ) return user