You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
1018 B
36 lines
1018 B
import hashlib
|
|
import hmac
|
|
import os
|
|
import secrets
|
|
from datetime import datetime, timedelta
|
|
|
|
from jose import jwt
|
|
|
|
from .config import settings
|
|
|
|
|
|
ALGORITHM = "HS256"
|
|
|
|
|
|
def hash_secret(value: str) -> str:
|
|
salt = os.urandom(16)
|
|
digest = hashlib.pbkdf2_hmac("sha256", value.encode(), salt, 120_000)
|
|
return f"pbkdf2_sha256$120000${salt.hex()}${digest.hex()}"
|
|
|
|
|
|
def verify_secret(value: str, encoded: str) -> bool:
|
|
try:
|
|
_, rounds, salt_hex, digest_hex = encoded.split("$")
|
|
digest = hashlib.pbkdf2_hmac("sha256", value.encode(), bytes.fromhex(salt_hex), int(rounds))
|
|
return hmac.compare_digest(digest.hex(), digest_hex)
|
|
except (ValueError, TypeError):
|
|
return False
|
|
|
|
|
|
def create_access_token(user_id: int) -> str:
|
|
expires = datetime.utcnow() + timedelta(minutes=settings.jwt_expire_minutes)
|
|
return jwt.encode({"sub": str(user_id), "exp": expires}, settings.jwt_secret, algorithm=ALGORITHM)
|
|
|
|
|
|
def create_refresh_token() -> str:
|
|
return secrets.token_urlsafe(48)
|
|
|