30 lines
975 B
Python
30 lines
975 B
Python
from datetime import datetime, timedelta, timezone
|
|
|
|
import bcrypt
|
|
import jwt
|
|
|
|
from app.config import settings
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
|
|
|
|
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
|
|
|
|
|
|
def create_access_token(data: dict) -> str:
|
|
to_encode = data.copy()
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
|
to_encode.update({"exp": expire})
|
|
return jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm)
|
|
|
|
|
|
def decode_access_token(token: str) -> dict | None:
|
|
"""Декодирует JWT-токен. Возвращает payload или None при ошибке."""
|
|
try:
|
|
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
|
except jwt.PyJWTError:
|
|
return None
|