"""Security utilities for authentication and authorization.""" from datetime import datetime, timedelta from typing import Optional, Dict, Any import bcrypt from jose import jwt, JWTError from app.core.config import settings def get_password_hash(password: str) -> str: """Hash a password using bcrypt.""" salt = bcrypt.gensalt() hashed = bcrypt.hashpw(password.encode('utf-8'), salt) return hashed.decode('utf-8') def verify_password(plain_password: str, hashed_password: str) -> bool: """Verify a password against its hash.""" return bcrypt.checkpw( plain_password.encode('utf-8'), hashed_password.encode('utf-8') ) def create_access_token( data: Dict[str, Any], expires_delta: Optional[timedelta] = None ) -> str: """Create a JWT access token.""" to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta( minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES ) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode( to_encode, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM ) return encoded_jwt def decode_access_token(token: str) -> Optional[Dict[str, Any]]: """Decode and validate a JWT access token.""" try: payload = jwt.decode( token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM] ) return payload except JWTError: return None