forked from mtusi2026/mtusi2026lab2
73 lines
2.3 KiB
Python
73 lines
2.3 KiB
Python
import base64
|
|
import binascii
|
|
from collections.abc import AsyncIterator
|
|
|
|
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: str | None = Header(default=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: str | None = Header(default=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
|
|
|
|
|
|
async def get_current_user(
|
|
token: str = Depends(get_bearer_token),
|
|
session: AsyncSession = Depends(get_db),
|
|
redis: Redis = Depends(get_redis),
|
|
) -> User:
|
|
return await authenticate_token(session, redis, token)
|