""" Security utilities: password hashing and JWT token generation. """ from datetime import datetime, timedelta, timezone from typing import Any, Union from uuid import uuid4 from jose import jwt from passlib.context import CryptContext from core.config import get_settings settings = get_settings() pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def verify_password(plain_password: str, hashed_password: str) -> bool: """Verifies a plain password against a hashed one.""" try: return pwd_context.verify(plain_password, hashed_password) except ValueError: return False def get_password_hash(password: str) -> str: """Hashes a password using bcrypt.""" return pwd_context.hash(password) def create_access_token(subject: Union[str, Any], workspace_id: Union[str, Any] = None, role: str = None, expires_delta: timedelta = None) -> str: """Creates a short-lived JWT access token with a unique jti for revocation support.""" if expires_delta: expire = datetime.now(timezone.utc) + expires_delta else: expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) to_encode = { "exp": expire, "sub": str(subject), "jti": str(uuid4()), "workspace_id": str(workspace_id) if workspace_id else None, "role": role, "type": "access" } encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) return encoded_jwt def create_refresh_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str: """Creates a long-lived JWT refresh token with a unique jti for revocation support.""" if expires_delta: expire = datetime.now(timezone.utc) + expires_delta else: expire = datetime.now(timezone.utc) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS) to_encode = {"exp": expire, "sub": str(subject), "jti": str(uuid4()), "type": "refresh"} encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) return encoded_jwt def create_reset_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str: """Creates a short-lived password reset token with type 'reset'. Cannot be used as an access token.""" if expires_delta: expire = datetime.now(timezone.utc) + expires_delta else: expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode = {"exp": expire, "sub": str(subject), "jti": str(uuid4()), "type": "reset"} encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) return encoded_jwt def create_ws_ticket(subject: Union[str, Any], workspace_id: Union[str, Any] = None, role: str = None) -> str: """ Creates a 60-second single-use WebSocket authentication ticket. Clients call POST /auth/ws-ticket/ immediately before opening a WebSocket connection so they always authenticate with a fresh credential even when their long-lived access token is near expiry. """ expire = datetime.now(timezone.utc) + timedelta(seconds=60) to_encode = { "exp": expire, "sub": str(subject), "jti": str(uuid4()), "workspace_id": str(workspace_id) if workspace_id else None, "role": role, "type": "ws_ticket", } return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) def decode_access_token(token: str) -> dict: """Decodes and validates a JWT access token.""" return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])