""" Authentication Utilities Handles JWT token generation, password hashing, and user authentication """ import os import jwt import bcrypt from datetime import datetime, timedelta from typing import Optional, Dict, Any import secrets import logging logger = logging.getLogger(__name__) # JWT Configuration SECRET_KEY = os.getenv("JWT_SECRET_KEY", secrets.token_urlsafe(32)) ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days class AuthManager: """Manage authentication operations""" @staticmethod def hash_password(password: str) -> str: """ Hash a password using bcrypt Args: password: Plain text password Returns: str: Hashed password """ salt = bcrypt.gensalt() hashed = bcrypt.hashpw(password.encode('utf-8'), salt) return hashed.decode('utf-8') @staticmethod def verify_password(plain_password: str, hashed_password: str) -> bool: """ Verify a password against its hash Args: plain_password: Plain text password hashed_password: Hashed password from database Returns: bool: True if password matches """ try: return bcrypt.checkpw( plain_password.encode('utf-8'), hashed_password.encode('utf-8') ) except Exception as e: logger.error(f"Password verification error: {str(e)}") return False @staticmethod def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str: """ Create a JWT access token Args: data: Data to encode in token expires_delta: Optional expiration time delta Returns: str: Encoded JWT token """ to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @staticmethod def decode_access_token(token: str) -> Optional[Dict[str, Any]]: """ Decode and verify a JWT token Args: token: JWT token string Returns: dict: Decoded token data or None if invalid """ try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) return payload except jwt.ExpiredSignatureError: logger.warning("Token has expired") return None except jwt.InvalidTokenError as e: logger.warning(f"Invalid token: {str(e)}") return None @staticmethod def generate_api_key() -> str: """ Generate a secure random API key Returns: str: Random API key """ return secrets.token_urlsafe(32) # Global auth manager instance auth_manager = AuthManager()