diff --git a/app/auth.py b/app/auth.py new file mode 100644 index 00000000..8535d735 --- /dev/null +++ b/app/auth.py @@ -0,0 +1,78 @@ +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")).digest() + + +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:] + await db.execute( + delete(SessionRow).where(SessionRow.token_hash == hash_token(token)) + ) + await db.commit() \ No newline at end of file