Spaces:
Running
Running
File size: 2,058 Bytes
fd5dd94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | """Password hashing (argon2) and JWT access/refresh tokens."""
from __future__ import annotations
import uuid
from datetime import UTC, datetime, timedelta
from typing import Any, Literal
import jwt
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError
from core.config import get_settings
_hasher = PasswordHasher()
TokenType = Literal["access", "refresh", "stepup"]
class TokenError(Exception):
pass
def hash_password(password: str) -> str:
return _hasher.hash(password)
def verify_password(password: str, password_hash: str) -> bool:
try:
return _hasher.verify(password_hash, password)
except (VerifyMismatchError, InvalidHashError):
return False
def issue_token(
user_id: uuid.UUID,
tenant_id: uuid.UUID | None,
kind: TokenType,
ttl: timedelta | None = None,
extra: dict[str, Any] | None = None,
) -> str:
s = get_settings()
if ttl is None:
ttl = (
timedelta(minutes=s.access_token_minutes)
if kind == "access"
else timedelta(days=s.refresh_token_days)
)
now = datetime.now(UTC)
payload: dict[str, Any] = {
"sub": str(user_id),
"tid": str(tenant_id) if tenant_id else None,
"typ": kind,
"iat": int(now.timestamp()),
"exp": int((now + ttl).timestamp()),
"jti": str(uuid.uuid4()),
}
if extra:
payload.update(extra)
return jwt.encode(payload, s.jwt_secret.get_secret_value(), algorithm=s.jwt_algorithm)
def decode_token(token: str, expected: TokenType) -> dict[str, Any]:
s = get_settings()
try:
payload: dict[str, Any] = jwt.decode(
token, s.jwt_secret.get_secret_value(), algorithms=[s.jwt_algorithm]
)
except jwt.PyJWTError as exc:
raise TokenError(str(exc)) from exc
if payload.get("typ") != expected:
raise TokenError(f"expected {expected} token")
return payload
|