Files
mtusi2026lab2/app/dependencies.py
T

27 lines
995 B
Python

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