feat: Phase 2 - Authentication and authorization (T-010 to T-013)
This commit is contained in:
50
backend/app/auth.py
Normal file
50
backend/app/auth.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
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)
|
||||
Reference in New Issue
Block a user