Files
Shubhankar45 8fdd20b29f Production
2026-09-22 06:23:46 +00:00

66 lines
1.8 KiB
Python

"""Password hashing and JWT encoding/decoding."""
import hashlib
import secrets
import uuid
from datetime import UTC, datetime, timedelta
from typing import Any
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError, VerifyMismatchError
from jose import JWTError, jwt
from app.common.exceptions import UnauthorizedError
from app.config.settings import settings
_hasher = PasswordHasher()
def utcnow() -> datetime:
return datetime.now(UTC)
def hash_password(plain: str) -> str:
return _hasher.hash(plain)
def verify_password(plain: str, hashed: str) -> bool:
try:
_hasher.verify(hashed, plain)
return True
except (VerifyMismatchError, VerificationError):
return False
def create_access_token(user_id: uuid.UUID, role: str) -> str:
now = utcnow()
payload: dict[str, Any] = {
"sub": str(user_id),
"role": role,
"type": "access",
"iat": now,
"exp": now + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES),
"jti": secrets.token_urlsafe(16),
}
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
def decode_access_token(token: str) -> dict[str, Any]:
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
except JWTError as exc:
raise UnauthorizedError("Invalid or expired token") from exc
if payload.get("type") != "access":
raise UnauthorizedError("Wrong token type")
return payload
def generate_refresh_token() -> tuple[str, str]:
"""Return (plaintext_token, sha256_hash). Only the hash is stored."""
raw = secrets.token_urlsafe(48)
return raw, hash_refresh_token(raw)
def hash_refresh_token(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()