ЛР 2: PostgreSQL и сессии, оценка 3

This commit is contained in:
2026-11-03 17:30:05 +03:00
parent 65003b6119
commit 0cf56ee2b5
21 changed files with 668 additions and 24 deletions
+26
View File
@@ -0,0 +1,26 @@
import hashlib
from fastapi import Header, HTTPException
from app.storage import db
BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'}
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
def unauthorized(basic=False):
raise HTTPException(status_code=401, detail="Unauthorized", headers=BASIC_CHALLENGE if basic else BEARER_CHALLENGE)
def current_user(authorization: str | None = Header(default=None)):
if not authorization or not authorization.startswith("Bearer "):
unauthorized()
token = authorization[7:]
if not token or " " in token:
unauthorized()
with db() as conn:
user = conn.execute("""SELECT 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 AND s.expires_at > now()""",
(hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
if user is None:
unauthorized()
return user