Files
mtusi2026lab5/src/messenger/identity/entrypoints/authentication.py
T

99 lines
3.4 KiB
Python

import re
from base64 import b64decode
from binascii import Error as Base64Error
from typing import Annotated
from fastapi import Depends, Request
from starlette.types import Scope
from messenger.identity.application.queries import Authenticate, VerifyCredentials
from messenger.identity.domain.models import Session, User
from messenger.shared.entrypoints.errors import Unauthenticated
from messenger.shared.entrypoints.pipeline import Rejection, header
LOGIN_PATH = "/api/v1/auth/sessions"
PROTECTED_PREFIX = "/api/v1/"
PUBLIC_ROUTES = frozenset({("POST", "/api/v1/users")})
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
AUTHORIZATION = b"authorization"
TOKEN = re.compile(r"[A-Za-z0-9\-._~+/]{1,512}=*")
def normalized(path: str) -> str:
return path.rstrip("/") or "/"
def challenge_for(path: str) -> str:
return BASIC_CHALLENGE if normalized(path) == LOGIN_PATH else BEARER_CHALLENGE
def basic_credentials(value: str) -> tuple[str, str] | None:
scheme, _, encoded = value.partition(" ")
if scheme.lower() != "basic" or not encoded.isascii():
return None
try:
decoded = b64decode(encoded.strip(), validate=True).decode("utf-8")
except Base64Error, UnicodeDecodeError:
return None
username, separator, password = decoded.partition(":")
if not separator or not username.isascii() or "\x00" in username:
return None
return username, password
def bearer_token(value: str) -> str | None:
scheme, _, token = value.partition(" ")
token = token.strip()
if scheme.lower() != "bearer" or TOKEN.fullmatch(token) is None:
return None
return token
def rejection(path: str) -> Rejection:
return Rejection(401, "unauthorized", (("www-authenticate", challenge_for(path)),))
async def guard(scope: Scope) -> Rejection | None:
method, path = scope["method"], normalized(scope["path"])
if not path.startswith(PROTECTED_PREFIX) or (method, path) in PUBLIC_ROUTES:
return None
container = scope["app"].state.dishka_container
state = scope.setdefault("state", {})
raw = header(scope, AUTHORIZATION)
if (method, path) == ("POST", LOGIN_PATH):
credentials = basic_credentials(raw)
verify = await container.get(VerifyCredentials)
user = await verify(*credentials) if credentials else None
if user is None:
return rejection(path)
state["user"] = user
state["actor"] = user.id
return None
token = bearer_token(raw)
authenticate = await container.get(Authenticate)
session = await authenticate(token) if token else None
if session is None:
return rejection(path)
state["session"] = session
state["actor"] = session.user_id
return None
async def verified_user(request: Request) -> User:
user = getattr(request.state, "user", None)
if not isinstance(user, User):
raise Unauthenticated("учётные данные не подтверждены")
return user
async def current_session(request: Request) -> Session:
session = getattr(request.state, "session", None)
if not isinstance(session, Session):
raise Unauthenticated("сессия не подтверждена")
return session
type VerifiedUser = Annotated[User, Depends(verified_user)]
type CurrentSession = Annotated[Session, Depends(current_session)]