/
misha_dev
/
game_guild_backend
Обзор
Документация
Войти
/
misha_dev
/
game_guild_backend
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
fastapi-application/utils/auth.py
72 строки
2 KB
misha-dev
feat: token expiration
23 мар 2025, 19:43
23 мар 2025, 19:43
87849b3
Код
Авторство
О чём код?
from datetime import datetime, timedelta, timezone import bcrypt import jwt from fastapi import HTTPException from jwt import ExpiredSignatureError from starlette import status from core.config import settings def encode_jwt( payload: dict, private_key: str = settings.auth_jwt.private_key_path.read_text(), algorithm: str = settings.auth_jwt.algorithm, expire_minutes: int = settings.auth_jwt.access_token_expire_minutes, expire_timedelta: timedelta | None = None, ) -> str: to_encode = payload.copy() now = datetime.now(timezone.utc) if expire_timedelta: expire = now + expire_timedelta else: expire = now + timedelta(minutes=expire_minutes) to_encode.update( exp=expire, iat=now, ) encoded = jwt.encode( to_encode, private_key, algorithm=algorithm, ) return encoded def decode_jwt( token: str | bytes, public_key: str = settings.auth_jwt.public_key_path.read_text(), algorithm: str = settings.auth_jwt.algorithm, ) -> dict: try: decoded = jwt.decode( token, public_key, algorithms=[algorithm], ) return decoded except ExpiredSignatureError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has expired", ) def hash_password( password: str, ) -> str: salt = bcrypt.gensalt() pwd_bytes: bytes = password.encode() hashed_password: bytes = bcrypt.hashpw(pwd_bytes, salt) return hashed_password.decode() def validate_password( password: str, hashed_password: str, ) -> bool: return bcrypt.checkpw( password=password.encode(), hashed_password=hashed_password.encode(), )