from datetime import datetime, timedelta from typing import Any, Optional, Union from jose import jwt from passlib.context import CryptContext # Password hashing context pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") # Secret key and algorithm for JWT SECRET_KEY = "a_very_secret_key_that_should_be_in_env_vars" # In production, use env vars ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 def verify_password(plain_password: str, hashed_password: str) -> bool: """ Verify if the provided password matches the stored hashed password """ return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password: str) -> str: """ Hash a password for storing """ return pwd_context.hash(password) def create_access_token( subject: Union[str, Any], expires_delta: Optional[timedelta] = None ) -> str: """ Create a JWT access token """ if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode = {"exp": expire, "sub": str(subject)} return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) def create_refresh_token(subject: Union[str, Any]) -> str: """ Create a JWT refresh token with longer expiry """ expire = datetime.utcnow() + timedelta(days=7) # Refresh tokens are valid for 7 days to_encode = {"exp": expire, "sub": str(subject), "type": "refresh"} return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)