import secrets from datetime import datetime, timezone, timedelta from passlib.context import CryptContext 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 = CryptContext(schemes=["bcrypt"], deprecated="auto") bearer_scheme = HTTPBearer(auto_error=False) def get_password_hash(password: str) -> str: return pwd_context.hash(password) def verify_password(plain: str, hashed: str) -> bool: return pwd_context.verify(plain, hashed) 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=f"session:{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(f"session:{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(f"session:{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