37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
"""Утилиты безопасности: JWT и хеширование токенов."""
|
|
import hashlib
|
|
import secrets
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
from jose import jwt
|
|
|
|
from app.core.config import settings
|
|
|
|
|
|
def create_access_token(user_id: int, session_id: str) -> str:
|
|
"""Создать access-токен (JWT)."""
|
|
now = datetime.now(timezone.utc)
|
|
payload = {
|
|
"sub": str(user_id),
|
|
"sid": session_id,
|
|
"type": "access",
|
|
"iat": int(now.timestamp()),
|
|
"exp": int((now + timedelta(days=settings.access_token_ttl_days)).timestamp()),
|
|
}
|
|
return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
|
|
|
|
|
|
def decode_access_token(token: str) -> dict:
|
|
"""Декодировать и проверить access-токен."""
|
|
return jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
|
|
|
|
|
|
def generate_opaque_token() -> str:
|
|
"""Сгенерировать случайный opaque-токен (refresh, одноразовая ссылка)."""
|
|
return secrets.token_urlsafe(48)
|
|
|
|
|
|
def hash_token(token: str) -> str:
|
|
"""SHA-256 хеш токена (для хранения в БД)."""
|
|
return hashlib.sha256(token.encode()).hexdigest()
|