53 lines
1.8 KiB
Python
53 lines
1.8 KiB
Python
import base64
|
|
import binascii
|
|
|
|
from fastapi import Depends
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
from fastapi.security.http import HTTPBase
|
|
|
|
from domain import BasicCredentialsSchema
|
|
from domain.errors import InvalidCredentialsError
|
|
|
|
BASIC_SCHEME = "basic"
|
|
|
|
basic_scheme = HTTPBase(
|
|
scheme=BASIC_SCHEME,
|
|
scheme_name="basicAuth",
|
|
description="Только для POST /auth/sessions",
|
|
auto_error=False,
|
|
)
|
|
|
|
bearer_scheme = HTTPBearer(
|
|
scheme_name="bearerAuth",
|
|
bearerFormat="opaque session token",
|
|
auto_error=False,
|
|
)
|
|
|
|
|
|
async def basic_credentials(
|
|
authorization: HTTPAuthorizationCredentials | None = Depends(basic_scheme),
|
|
) -> BasicCredentialsSchema:
|
|
"""
|
|
Authorization: Basic base64(username:password)
|
|
|
|
username — до первого двоеточия, остальное — пароль
|
|
Любая ошибка формата — тот же 401, что и неверный пароль.
|
|
"""
|
|
if authorization is None or authorization.scheme.lower() != BASIC_SCHEME:
|
|
raise InvalidCredentialsError()
|
|
try:
|
|
decoded = base64.b64decode(authorization.credentials, validate=True)
|
|
username, separator, password = decoded.decode("utf-8").partition(":")
|
|
except (binascii.Error, UnicodeDecodeError):
|
|
raise InvalidCredentialsError() from None
|
|
if not separator or not username.isascii():
|
|
raise InvalidCredentialsError()
|
|
return BasicCredentialsSchema(username=username, password=password)
|
|
|
|
|
|
async def bearer_token(
|
|
authorization: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
|
) -> str | None:
|
|
"""Токен из Authorization: Bearer; другие схемы (Basic) — как отсутствие"""
|
|
return authorization.credentials if authorization is not None else None
|