forked from mtusi2026/mtusi2026lab2
162 lines
3.8 KiB
Python
162 lines
3.8 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import binascii
|
|
import hashlib
|
|
import json
|
|
import secrets
|
|
from datetime import datetime, timezone
|
|
from uuid import UUID
|
|
|
|
from argon2 import PasswordHasher
|
|
from argon2.exceptions import InvalidHashError, VerifyMismatchError
|
|
|
|
|
|
password_hasher = PasswordHasher()
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return password_hasher.hash(password)
|
|
|
|
|
|
def verify_password(password_hash: str, password: str) -> bool:
|
|
try:
|
|
return password_hasher.verify(password_hash, password)
|
|
except (VerifyMismatchError, InvalidHashError):
|
|
return False
|
|
|
|
|
|
def generate_session_token() -> str:
|
|
return secrets.token_urlsafe(32)
|
|
|
|
|
|
def hash_session_token(token: str) -> str:
|
|
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def parse_basic_authorization(value: str | None) -> tuple[str, str] | None:
|
|
if value is None or not value.startswith("Basic "):
|
|
return None
|
|
|
|
try:
|
|
encoded_credentials = value[len("Basic "):]
|
|
decoded = base64.b64decode(
|
|
encoded_credentials,
|
|
validate=True,
|
|
).decode("utf-8")
|
|
|
|
username, password = decoded.split(":", 1)
|
|
except (
|
|
ValueError,
|
|
UnicodeDecodeError,
|
|
binascii.Error,
|
|
):
|
|
return None
|
|
|
|
if not username or not username.isascii():
|
|
return None
|
|
|
|
return username, password
|
|
|
|
|
|
def _encode_cursor_payload(payload: dict[str, str]) -> str:
|
|
raw = json.dumps(
|
|
payload,
|
|
ensure_ascii=False,
|
|
separators=(",", ":"),
|
|
sort_keys=True,
|
|
).encode("utf-8")
|
|
|
|
return base64.urlsafe_b64encode(raw).decode("ascii")
|
|
|
|
|
|
def _decode_cursor_payload(cursor: str) -> dict[str, str] | None:
|
|
try:
|
|
raw = base64.urlsafe_b64decode(cursor.encode("ascii"))
|
|
payload = json.loads(raw.decode("utf-8"))
|
|
|
|
if not isinstance(payload, dict):
|
|
return None
|
|
|
|
return payload
|
|
except (
|
|
ValueError,
|
|
TypeError,
|
|
UnicodeDecodeError,
|
|
binascii.Error,
|
|
):
|
|
return None
|
|
|
|
|
|
def _utc_timestamp(value: datetime) -> str:
|
|
if value.tzinfo is None:
|
|
raise ValueError("Cursor datetime must be timezone-aware.")
|
|
|
|
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
|
|
|
|
def encode_chat_cursor(
|
|
created_at: datetime,
|
|
chat_id: UUID,
|
|
) -> str:
|
|
return _encode_cursor_payload(
|
|
{
|
|
"kind": "chat",
|
|
"created_at": _utc_timestamp(created_at),
|
|
"id": str(chat_id),
|
|
}
|
|
)
|
|
|
|
|
|
def decode_chat_cursor(
|
|
cursor: str,
|
|
) -> tuple[datetime, UUID] | None:
|
|
payload = _decode_cursor_payload(cursor)
|
|
|
|
if payload is None or payload.get("kind") != "chat":
|
|
return None
|
|
|
|
try:
|
|
created_at = datetime.fromisoformat(
|
|
payload["created_at"].replace("Z", "+00:00")
|
|
)
|
|
chat_id = UUID(payload["id"])
|
|
except (KeyError, ValueError, AttributeError):
|
|
return None
|
|
|
|
return created_at, chat_id
|
|
|
|
|
|
def encode_message_cursor(
|
|
chat_id: UUID,
|
|
created_at: datetime,
|
|
message_id: UUID,
|
|
) -> str:
|
|
return _encode_cursor_payload(
|
|
{
|
|
"kind": "message",
|
|
"chat_id": str(chat_id),
|
|
"created_at": _utc_timestamp(created_at),
|
|
"id": str(message_id),
|
|
}
|
|
)
|
|
|
|
|
|
def decode_message_cursor(
|
|
cursor: str,
|
|
) -> tuple[UUID, datetime, UUID] | None:
|
|
payload = _decode_cursor_payload(cursor)
|
|
|
|
if payload is None or payload.get("kind") != "message":
|
|
return None
|
|
|
|
try:
|
|
chat_id = UUID(payload["chat_id"])
|
|
created_at = datetime.fromisoformat(
|
|
payload["created_at"].replace("Z", "+00:00")
|
|
)
|
|
message_id = UUID(payload["id"])
|
|
except (KeyError, ValueError, AttributeError):
|
|
return None
|
|
|
|
return chat_id, created_at, message_id |