# app/core/security.py from datetime import datetime, timedelta, timezone from typing import Any, Union, Optional from jose import JWTError, jwt from passlib.context import CryptContext from app.config import settings # Import settings from config # --- Password Hashing --- # Configure passlib context # Using bcrypt as the default hashing scheme # 'deprecated="auto"' will automatically upgrade hashes if needed on verification pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def verify_password(plain_password: str, hashed_password: str) -> bool: """ Verifies a plain text password against a hashed password. Args: plain_password: The password attempt. hashed_password: The stored hash from the database. Returns: True if the password matches the hash, False otherwise. """ try: return pwd_context.verify(plain_password, hashed_password) except Exception: # Handle potential errors during verification (e.g., invalid hash format) return False def hash_password(password: str) -> str: """ Hashes a plain text password using the configured context (bcrypt). Args: password: The plain text password to hash. Returns: The resulting hash string. """ return pwd_context.hash(password) # --- JSON Web Tokens (JWT) --- # FastAPI-Users now handles all tokenization. # You might add a function here later to extract the 'sub' (subject/user id) # specifically, often used in dependency injection for authentication. # def get_subject_from_token(token: str) -> Optional[str]: # # This would need to use FastAPI-Users' token verification if ever implemented # # For example, by decoding the token using the strategy from the auth backend # payload = {} # Placeholder for actual token decoding logic # if payload: # return payload.get("sub") # return None