forked from mtusi2026/mtusi2026lab5
lab4_
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
import base64
|
||||
|
||||
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, transaction
|
||||
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"'
|
||||
|
||||
|
||||
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()
|
||||
|
||||
# Одинаковый 401 для «нет пользователя» и «неверный пароль».
|
||||
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()
|
||||
expires_at = session_expiry(settings.session_ttl_seconds)
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO sessions (user_id, token_hash, expires_at)
|
||||
VALUES (%s, %s, %s)
|
||||
""",
|
||||
(row["id"], token_digest(token), expires_at),
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at.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:
|
||||
"""Зависимость: валидирует Bearer и возвращает actor с user и token_hash."""
|
||||
token = _extract_bearer(request)
|
||||
digest = token_digest(token)
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT s.user_id, s.expires_at,
|
||||
u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s
|
||||
""",
|
||||
(digest,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
raise ApiError(401, "unauthorized", "Сессия недействительна", {"WWW-Authenticate": WWW_BEARER})
|
||||
|
||||
# Проверка срока на стороне БД
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM sessions WHERE token_hash = %s AND expires_at > now()",
|
||||
(digest,),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise ApiError(401, "unauthorized", "Сессия истекла", {"WWW-Authenticate": WWW_BEARER})
|
||||
|
||||
return {
|
||||
"user": row_to_user(row),
|
||||
"user_id": row["user_id"],
|
||||
"token_hash": digest,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/auth/sessions/current", status_code=204)
|
||||
def revoke_session(request: Request, actor: dict = Depends(require_actor)):
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM sessions WHERE token_hash = %s", (actor["token_hash"],))
|
||||
return Response(status_code=204)
|
||||
Reference in New Issue
Block a user