/
tinypot
/
integr
Обзор
Документация
Войти
/
tinypot
/
integr
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
task_management_api/app/core/dependencies.py
82 строки
2 KB
Tim Polus
lab1
21 янв 2026, 23:15
21 янв 2026, 23:15
dd1578c
Код
Авторство
О чём код?
""" FastAPI dependencies """ from typing import Generator, Optional from fastapi import Depends, HTTPException, status, Request from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from sqlalchemy.ext.asyncio import AsyncSession from app.core.database import get_db from app.core.security import verify_token from app.models.user import User from app.services.user_service import UserService security = HTTPBearer() async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), db: AsyncSession = Depends(get_db) ) -> User: """Get current authenticated user""" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) token = credentials.credentials username = verify_token(token) if username is None: raise credentials_exception user = await UserService.get_by_username(db, username=username) if user is None: raise credentials_exception if not await UserService.is_active(user): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user" ) return user async def get_current_active_superuser( current_user: User = Depends(get_current_user), ) -> User: """Get current authenticated superuser""" if not await UserService.is_superuser(current_user): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="The user doesn't have enough privileges" ) return current_user async def get_current_user_optional( request: Request, db: AsyncSession = Depends(get_db) ) -> Optional[User]: """Get current user if authenticated, None otherwise""" try: authorization = request.headers.get("authorization") if not authorization or not authorization.startswith("Bearer "): return None token = authorization.split(" ")[1] username = verify_token(token) if username is None: return None user = await UserService.get_by_username(db, username=username) if user is None or not await UserService.is_active(user): return None # Store user_id in request state for idempotency request.state.user_id = user.id return user except Exception: return None