"""Разбор Basic/Bearer и проверка сессии.""" from __future__ import annotations import base64 import binascii from typing import Optional, Tuple from app.db import Database from app.errors import unauthorized from app.models import User from app.sessions import SessionStore from app.validation import USERNAME_RE BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' BEARER_CHALLENGE = 'Bearer realm="messenger"' def parse_basic(authorization: Optional[str]) -> Tuple[str, str]: if not authorization or not authorization.startswith("Basic "): raise unauthorized("Требуется Basic-аутентификация", challenge=BASIC_CHALLENGE) raw = authorization[6:].strip() if not raw: raise unauthorized("Требуется Basic-аутентификация", challenge=BASIC_CHALLENGE) try: decoded = base64.b64decode(raw, validate=True).decode("utf-8") except (binascii.Error, UnicodeDecodeError, ValueError) as exc: raise unauthorized("Неверные учётные данные", challenge=BASIC_CHALLENGE) from exc if ":" not in decoded: raise unauthorized("Неверные учётные данные", challenge=BASIC_CHALLENGE) username, password = decoded.split(":", 1) if not USERNAME_RE.fullmatch(username): raise unauthorized("Неверные учётные данные", challenge=BASIC_CHALLENGE) n = len(password) if n < 12 or n > 128: raise unauthorized("Неверные учётные данные", challenge=BASIC_CHALLENGE) return username, password def parse_bearer(authorization: Optional[str]) -> str: if not authorization: raise unauthorized(challenge=BEARER_CHALLENGE) if authorization.startswith("Basic "): raise unauthorized(challenge=BEARER_CHALLENGE) if not authorization.startswith("Bearer "): raise unauthorized(challenge=BEARER_CHALLENGE) token = authorization[7:].strip() if not token: raise unauthorized(challenge=BEARER_CHALLENGE) return token def require_actor( db: Database, sessions: SessionStore, authorization: Optional[str], ) -> Tuple[User, str]: token = parse_bearer(authorization) user_id = sessions.resolve(token) if user_id is None: raise unauthorized(challenge=BEARER_CHALLENGE) user = db.get_user(user_id) if user is None: raise unauthorized(challenge=BEARER_CHALLENGE) return user, token