Files
mtusi2026lab2/app/auth.py
T

80 lines
2.4 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 hashlib
import os
import secrets
from datetime import datetime, timezone
import bcrypt
from fastapi import Depends, Header, HTTPException
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
from .db.models import SessionRow, User
from .db.session import get_db
SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
def _prehash(password: str) -> bytes:
# bcrypt работает с ≤72 байт, SHA-256 даёт 32 байта и снимает ограничение
return hashlib.sha256(password.encode("utf-8")).hexdigest().encode("ascii")
def hash_password(password: str) -> str:
return bcrypt.hashpw(_prehash(password), bcrypt.gensalt(rounds=12)).decode("ascii")
def verify_password(password: str, password_hash: str) -> bool:
try:
return bcrypt.checkpw(_prehash(password), password_hash.encode("ascii"))
except ValueError:
return False
def generate_token() -> str:
return secrets.token_urlsafe(32)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode("ascii")).hexdigest()
def _unauthorized_bearer() -> HTTPException:
return HTTPException(
status_code=401,
detail="Unauthorized",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
async def get_current_user(
authorization: str | None = Header(None, alias="Authorization"),
db: AsyncSession = Depends(get_db),
) -> User:
if not authorization or not authorization.startswith("Bearer "):
raise _unauthorized_bearer()
token = authorization[7:]
token_hash = hash_token(token)
now = datetime.now(timezone.utc)
stmt = select(SessionRow).where(
SessionRow.token_hash == token_hash,
SessionRow.expires_at > now,
)
session = (await db.execute(stmt)).scalar_one_or_none()
if session is None:
raise _unauthorized_bearer()
user = await db.get(User, session.user_id)
if user is None:
raise _unauthorized_bearer()
return user
async def revoke_current_session(authorization: str, db: AsyncSession) -> None:
if not authorization or not authorization.startswith("Bearer "):
raise _unauthorized_bearer()
token = authorization[7:]
result = await db.execute(
delete(SessionRow).where(SessionRow.token_hash == hash_token(token))
)
await db.commit()
if result.rowcount == 0:
raise _unauthorized_bearer()