Files
mtusi2026lab5-fork/src/app/routes/sessions.py
T
2026-11-20 13:05:30 +03:00

112 lines
4.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import base64
import json
import redis
from fastapi import APIRouter, Depends, Request
from fastapi.responses import Response
from psycopg.rows import dict_row
from ..config import get_settings
from ..db import connection
from ..errors import ApiError
from ..security import (
new_session_token,
session_expiry,
token_digest,
verify_password,
)
from ..serializers import row_to_user
router = APIRouter(prefix="/api/v1")
WWW_BASIC = 'Basic realm="messenger", charset="UTF-8"'
WWW_BEARER = 'Bearer realm="messenger"'
# Подключение к Redis
redis_client = redis.Redis.from_url(get_settings().redis_url, decode_responses=True)
def _parse_basic(header: str | None) -> tuple[str, str]:
if not header or not header.lower().startswith("basic "):
raise ApiError(401, "unauthorized", "Требуется Basic", {"WWW-Authenticate": WWW_BASIC})
try:
decoded = base64.b64decode(header[6:].strip(), validate=True).decode("utf-8")
except Exception:
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
if ":" not in decoded:
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
username, password = decoded.split(":", 1)
return username, password
@router.post("/auth/sessions", status_code=201)
def create_session(request: Request):
header = request.headers.get("Authorization")
username, password = _parse_basic(header)
with connection() as conn:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"SELECT id, username, display_name, created_at, password_hash "
"FROM users WHERE username = %s",
(username,),
)
row = cur.fetchone()
if row is None or not verify_password(password, row["password_hash"]):
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
settings = get_settings()
token = new_session_token()
ttl = settings.session_ttl_seconds
digest = token_digest(token)
# СОХРАНЯЕМ В REDIS
redis_client.setex(f"session:{digest}", ttl, str(row["id"]))
return {
"token": token,
"token_type": "Bearer",
"expires_at": session_expiry(ttl).isoformat().replace("+00:00", "Z"),
"user": row_to_user(row),
}
def _extract_bearer(request: Request) -> str:
header = request.headers.get("Authorization")
if not header or not header.lower().startswith("bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer", {"WWW-Authenticate": WWW_BEARER})
token = header[7:].strip()
if not token:
raise ApiError(401, "unauthorized", "Требуется Bearer", {"WWW-Authenticate": WWW_BEARER})
return token
def require_actor(request: Request) -> dict:
token = _extract_bearer(request)
digest = token_digest(token)
# ЧИТАЕМ ИЗ REDIS
user_id = redis_client.get(f"session:{digest}")
if user_id is None:
raise ApiError(401, "unauthorized", "Сессия недействительна или истекла", {"WWW-Authenticate": WWW_BEARER})
with connection() as conn:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
(user_id,),
)
row = cur.fetchone()
if row is None:
raise ApiError(401, "unauthorized", "Пользователь не найден", {"WWW-Authenticate": WWW_BEARER})
return {
"user": row_to_user(row),
"user_id": user_id,
"token_hash": digest,
}
@router.delete("/auth/sessions/current", status_code=204)
def revoke_session(request: Request, actor: dict = Depends(require_actor)):
# УДАЛЯЕМ ИЗ REDIS
redis_client.delete(f"session:{actor['token_hash']}")
return Response(status_code=204)