forked from mtusi2026/mtusi2026lab2
84 lines
2.7 KiB
Python
84 lines
2.7 KiB
Python
import base64
|
|
import binascii
|
|
from collections.abc import AsyncIterator
|
|
from typing import Annotated
|
|
|
|
from fastapi import Depends, Header, Request
|
|
from redis.asyncio import Redis
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.config import Settings
|
|
from app.domain.auth import authenticate_token
|
|
from app.errors.exceptions import unauthorized_basic, unauthorized_bearer
|
|
from app.schemas.user import User
|
|
|
|
|
|
async def get_settings(request: Request) -> Settings:
|
|
settings: Settings = request.app.state.settings
|
|
return settings
|
|
|
|
|
|
async def get_db(request: Request) -> AsyncIterator[AsyncSession]:
|
|
"""Одна AsyncSession на HTTP-запрос; незакоммиченная транзакция откатывается."""
|
|
session_factory = request.app.state.session_factory
|
|
async with session_factory() as session:
|
|
yield session
|
|
|
|
|
|
async def get_redis(request: Request) -> Redis:
|
|
redis: Redis = request.app.state.redis
|
|
return redis
|
|
|
|
|
|
def _split_authorization(authorization: str | None) -> tuple[str, str] | None:
|
|
if authorization is None:
|
|
return None
|
|
scheme, _, value = authorization.partition(" ")
|
|
if not value.strip():
|
|
return None
|
|
return scheme.lower(), value.strip()
|
|
|
|
|
|
async def get_bearer_token(
|
|
authorization: Annotated[str | None, Header()] = None,
|
|
) -> str:
|
|
parts = _split_authorization(authorization)
|
|
if parts is None or parts[0] != "bearer":
|
|
raise unauthorized_bearer()
|
|
return parts[1]
|
|
|
|
|
|
async def get_basic_credentials(
|
|
authorization: Annotated[str | None, Header()] = None,
|
|
) -> tuple[str, str]:
|
|
"""(username, password) из `Authorization: Basic`; пароль может содержать ':'."""
|
|
parts = _split_authorization(authorization)
|
|
if parts is None or parts[0] != "basic":
|
|
raise unauthorized_basic()
|
|
|
|
try:
|
|
decoded = base64.b64decode(parts[1], validate=True).decode("utf-8")
|
|
except (binascii.Error, UnicodeDecodeError, ValueError):
|
|
raise unauthorized_basic() from None
|
|
|
|
username, separator, password = decoded.partition(":")
|
|
if not separator or not username:
|
|
raise unauthorized_basic()
|
|
return username, password
|
|
|
|
|
|
DbSession = Annotated[AsyncSession, Depends(get_db)]
|
|
RedisClient = Annotated[Redis, Depends(get_redis)]
|
|
AppSettings = Annotated[Settings, Depends(get_settings)]
|
|
BearerToken = Annotated[str, Depends(get_bearer_token)]
|
|
BasicCredentials = Annotated[tuple[str, str], Depends(get_basic_credentials)]
|
|
|
|
|
|
async def get_current_user(
|
|
token: BearerToken, session: DbSession, redis: RedisClient
|
|
) -> User:
|
|
return await authenticate_token(session, redis, token)
|
|
|
|
|
|
CurrentUser = Annotated[User, Depends(get_current_user)]
|