74 lines
1.9 KiB
Python
74 lines
1.9 KiB
Python
"""Password hashing + JWT access/refresh tokens."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import secrets
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Any, Literal
|
|
|
|
import bcrypt
|
|
import jwt
|
|
|
|
from .config import settings
|
|
|
|
TokenKind = Literal["access", "refresh"]
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
|
|
|
|
|
def verify_password(password: str, hashed: str | None) -> bool:
|
|
if not hashed:
|
|
return False
|
|
try:
|
|
return bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8"))
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def new_token_id() -> str:
|
|
return uuid.uuid4().hex
|
|
|
|
|
|
def create_token(
|
|
subject: str | int,
|
|
kind: TokenKind = "access",
|
|
*,
|
|
extra: dict[str, Any] | None = None,
|
|
jti: str | None = None,
|
|
expires: timedelta | None = None,
|
|
) -> tuple[str, str, datetime]:
|
|
"""Return ``(token, jti, expires_at)``."""
|
|
now = datetime.now(timezone.utc)
|
|
ttl = expires or (
|
|
timedelta(minutes=settings.access_token_minutes)
|
|
if kind == "access"
|
|
else timedelta(days=settings.refresh_token_days)
|
|
)
|
|
expires_at = now + ttl
|
|
jti = jti or new_token_id()
|
|
payload: dict[str, Any] = {
|
|
"sub": str(subject),
|
|
"typ": kind,
|
|
"jti": jti,
|
|
"iat": int(now.timestamp()),
|
|
"exp": int(expires_at.timestamp()),
|
|
}
|
|
if extra:
|
|
payload.update(extra)
|
|
token = jwt.encode(payload, settings.secret_key, algorithm="HS256")
|
|
return token, jti, expires_at
|
|
|
|
|
|
def decode_token(token: str, kind: TokenKind = "access") -> dict[str, Any]:
|
|
payload = jwt.decode(token, settings.secret_key, algorithms=["HS256"])
|
|
if payload.get("typ") != kind:
|
|
raise jwt.InvalidTokenError(f"expected a {kind} token")
|
|
return payload
|
|
|
|
|
|
def random_string(n: int = 32) -> str:
|
|
return secrets.token_urlsafe(n)
|