forked from mtusi2026/mtusi2026lab7
51 lines
2.0 KiB
Python
51 lines
2.0 KiB
Python
# Что сервер пишет в WWW-Authenticate при 401: какую схему входа он ждёт.
|
|
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' # только POST /auth/sessions
|
|
BEARER_CHALLENGE = 'Bearer realm="messenger"' # все остальные защищённые запросы
|
|
|
|
|
|
class ApiError(Exception):
|
|
def __init__(self, status_code: int, code: str, message: str, headers: dict | None = None):
|
|
super().__init__(message)
|
|
self.status_code = status_code
|
|
self.code = code
|
|
self.message = message
|
|
self.headers = headers or {}
|
|
|
|
|
|
def bad_request(message: str) -> ApiError:
|
|
return ApiError(400, "invalid_request", message)
|
|
|
|
|
|
def unauthorized(message: str = "Unauthorized", challenge: str = BEARER_CHALLENGE) -> ApiError:
|
|
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
|
|
|
|
|
|
def not_found(message: str) -> ApiError:
|
|
return ApiError(404, "not_found", message)
|
|
|
|
|
|
def conflict(message: str) -> ApiError:
|
|
return ApiError(409, "conflict", message)
|
|
|
|
|
|
def unavailable(message: str = "Service temporarily unavailable") -> ApiError:
|
|
return ApiError(503, "unavailable", message)
|
|
|
|
|
|
def payload_too_large(message: str) -> ApiError:
|
|
return ApiError(413, "payload_too_large", message)
|
|
|
|
|
|
def unsupported_media_type(message: str) -> ApiError:
|
|
return ApiError(415, "unsupported_media_type", message)
|
|
|
|
|
|
def rate_limited(retry_after: int, message: str = "Too many attempts, retry later") -> ApiError:
|
|
"""lab7: 429 + Retry-After (секунды до конца окна общего счётчика в Redis)."""
|
|
return ApiError(429, "rate_limited", message, {"Retry-After": str(max(1, int(retry_after)))})
|
|
|
|
|
|
def busy(retry_after: int = 1) -> ApiError:
|
|
"""lab7: бюджет одновременных Argon2id-хешей реплики исчерпан — 503 + Retry-After, без очереди."""
|
|
return ApiError(503, "unavailable", "Server is busy, retry later", {"Retry-After": str(max(1, int(retry_after)))})
|