85 lines
2.5 KiB
Python
85 lines
2.5 KiB
Python
import hashlib
|
||
import os
|
||
import secrets
|
||
from datetime import datetime, timezone
|
||
from uuid import UUID
|
||
|
||
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
|
||
|
||
import redis.asyncio as redis
|
||
|
||
redis_client = redis.from_url(os.getenv("REDIS_URL", "redis://redis:6379/0"))
|
||
|
||
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 create_session(user_id: str) -> str:
|
||
token = generate_token()
|
||
await redis_client.setex(
|
||
f"session:{hash_token(token)}", SESSION_TTL, str(user_id)
|
||
)
|
||
return token
|
||
|
||
|
||
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)
|
||
user_id_raw = await redis_client.get(f"session:{token_hash}")
|
||
if user_id_raw is None:
|
||
raise _unauthorized_bearer()
|
||
user = await db.get(User, UUID(user_id_raw.decode()))
|
||
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:]
|
||
deleted = await redis_client.delete(f"session:{hash_token(token)}")
|
||
if deleted == 0:
|
||
raise _unauthorized_bearer() |