113 lines
3.7 KiB
Python
113 lines
3.7 KiB
Python
import base64
|
|
import binascii
|
|
from collections.abc import AsyncIterator
|
|
from typing import Annotated
|
|
|
|
from fastapi import Depends, Request, Security
|
|
from fastapi.openapi.models import HTTPBase, HTTPBearer
|
|
from fastapi.security.base import SecurityBase
|
|
from redis.asyncio import Redis
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.config import Settings
|
|
from app.core.request_capacity import RequestCapacity
|
|
from app.domain.auth import authenticate_token
|
|
from app.errors.exceptions import unauthorized_basic, unauthorized_bearer
|
|
from app.schemas.user import User
|
|
from app.storage.s3 import MinioStorage
|
|
|
|
|
|
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 get_s3(request: Request) -> MinioStorage | None:
|
|
return request.app.state.s3
|
|
|
|
|
|
def get_upload_capacity(request: Request) -> RequestCapacity:
|
|
return request.app.state.upload_capacity
|
|
|
|
|
|
class AuthorizationHeader(SecurityBase):
|
|
"""Отдаёт сырой заголовок Authorization и описывает схему для OpenAPI."""
|
|
|
|
def __init__(self, model: HTTPBase, scheme_name: str) -> None:
|
|
self.model = model
|
|
self.scheme_name = scheme_name
|
|
|
|
async def __call__(self, request: Request) -> str | None:
|
|
return request.headers.get("Authorization")
|
|
|
|
|
|
basic_auth = AuthorizationHeader(HTTPBase(scheme="basic"), "BasicAuth")
|
|
bearer_auth = AuthorizationHeader(HTTPBearer(), "BearerAuth")
|
|
|
|
|
|
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, Security(bearer_auth)],
|
|
) -> 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, Security(basic_auth)],
|
|
) -> 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)]
|
|
S3Storage = Annotated[MinioStorage | None, Depends(get_s3)]
|
|
UploadCapacity = Annotated[RequestCapacity, Depends(get_upload_capacity)]
|
|
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)]
|