keyvault-api / src /utils /security.py
hashir-qt's picture
Upload folder using huggingface_hub
e656014 verified
Raw History Blame Contribute Delete
1.58 kB
from datetime import datetime, timedelta, timezone
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from src.config import settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(plain_password: str) -> str:
"""Hash a plain-text password using bcrypt."""
return pwd_context.hash(plain_password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify a plain-text password against its bcrypt hash."""
return pwd_context.verify(plain_password, hashed_password)
def create_access_token(subject: str, extra_claims: dict = {}) -> str:
"""
Create a signed JWT access token.
Args:
subject: The user ID to embed as the 'sub' claim.
extra_claims: Additional payload fields (e.g. role).
Returns:
Encoded JWT string.
"""
expire = datetime.now(timezone.utc) + timedelta(hours=settings.jwt_expiry_hours)
payload = {
"sub": subject,
"exp": expire,
"iat": datetime.now(timezone.utc),
**extra_claims,
}
return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
def decode_access_token(token: str) -> Optional[dict]:
"""
Decode and validate a JWT access token.
Returns:
Decoded payload dict, or None if invalid/expired.
"""
try:
return jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
except JWTError:
return None