51 lines
1.5 KiB
Python
51 lines
1.5 KiB
Python
"""
|
|
Security utilities: password hashing and JWT token management.
|
|
|
|
This module provides pure functions for:
|
|
- Hashing and verifying passwords using bcrypt via passlib.
|
|
- Creating JWT access tokens using python-jose.
|
|
|
|
No endpoints are defined here.
|
|
"""
|
|
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
from jose import jwt
|
|
from passlib.context import CryptContext
|
|
|
|
from app.config import settings
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Password hashing
|
|
# ---------------------------------------------------------------------------
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
"""Return a bcrypt hash of *password*."""
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
"""Return ``True`` if *plain* matches the bcrypt *hashed* value."""
|
|
return pwd_context.verify(plain, hashed)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# JWT tokens
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def create_access_token(data: dict) -> str:
|
|
"""Create a signed JWT containing *data* plus an ``exp`` claim.
|
|
|
|
The token expires after ``ACCESS_TOKEN_EXPIRE_MINUTES`` (from settings).
|
|
"""
|
|
to_encode = data.copy()
|
|
expire = datetime.now(timezone.utc) + timedelta(
|
|
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES,
|
|
)
|
|
to_encode.update({"exp": expire})
|
|
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|