|
| 1 | +""" |
| 2 | +Kinde Session Management |
| 3 | +
|
| 4 | +This module provides a user-friendly interface for session management when using |
| 5 | +the Kinde SDK in standalone mode (without a web framework). It wraps access to |
| 6 | +the NullFramework behind a more intuitive API. |
| 7 | +""" |
| 8 | + |
| 9 | +from typing import Optional, TYPE_CHECKING |
| 10 | +import logging |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from kinde_sdk.core.framework.null_framework import NullFramework |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class KindeSessionManagement: |
| 19 | + """ |
| 20 | + A user-friendly interface for session management in standalone Kinde SDK usage. |
| 21 | + |
| 22 | + This class provides a clean API for managing user sessions when using the Kinde SDK |
| 23 | + without a web framework. It wraps the NullFramework functionality behind a more |
| 24 | + intuitive interface. |
| 25 | + |
| 26 | + Note: This class can only be used when the SDK is running in standalone mode |
| 27 | + (without a web framework). If a framework like FastAPI or Flask is being used, |
| 28 | + this class will raise an exception to prevent misuse. |
| 29 | + """ |
| 30 | + |
| 31 | + def __init__(self): |
| 32 | + """ |
| 33 | + Initialize the Kinde session management. |
| 34 | + |
| 35 | + Raises: |
| 36 | + RuntimeError: If the SDK is not running in standalone mode (NullFramework not active) |
| 37 | + """ |
| 38 | + self._logger = logging.getLogger(__name__) |
| 39 | + self._null_framework = self._get_null_framework() |
| 40 | + |
| 41 | + if not self._null_framework: |
| 42 | + raise RuntimeError( |
| 43 | + "KindeSessionManagement can only be used in standalone mode. " |
| 44 | + "When using a web framework (FastAPI, Flask, etc.), session management " |
| 45 | + "is handled automatically by the framework. Please use the framework's " |
| 46 | + "built-in session management instead." |
| 47 | + ) |
| 48 | + |
| 49 | + def _get_null_framework(self) -> Optional['NullFramework']: |
| 50 | + """ |
| 51 | + Get the current NullFramework instance if it's active. |
| 52 | + |
| 53 | + Returns: |
| 54 | + Optional[NullFramework]: The NullFramework instance if active, None otherwise |
| 55 | + """ |
| 56 | + try: |
| 57 | + from kinde_sdk.core.framework.null_framework import NullFramework |
| 58 | + from kinde_sdk.core.framework.framework_factory import FrameworkFactory |
| 59 | + |
| 60 | + # First, try to get the framework instance from FrameworkFactory |
| 61 | + current_framework = FrameworkFactory.get_framework_instance() |
| 62 | + |
| 63 | + # Check if it's a NullFramework instance |
| 64 | + if current_framework and isinstance(current_framework, NullFramework): |
| 65 | + return current_framework |
| 66 | + |
| 67 | + # If not found in FrameworkFactory, try to get it from the NullFramework singleton |
| 68 | + # This handles the case where OAuth creates NullFramework directly |
| 69 | + try: |
| 70 | + null_framework = NullFramework() |
| 71 | + # Check if this is actually being used (has been initialized) |
| 72 | + if hasattr(null_framework, '_initialized') and null_framework._initialized: |
| 73 | + return null_framework |
| 74 | + except Exception: |
| 75 | + pass |
| 76 | + |
| 77 | + return None |
| 78 | + |
| 79 | + except Exception as e: |
| 80 | + self._logger.debug(f"Could not get NullFramework: {e}") |
| 81 | + return None |
| 82 | + |
| 83 | + def get_user_id(self) -> Optional[str]: |
| 84 | + """ |
| 85 | + Get the current user ID from the session. |
| 86 | + |
| 87 | + Returns: |
| 88 | + Optional[str]: The current user ID, or None if not set |
| 89 | + """ |
| 90 | + if not self._null_framework: |
| 91 | + raise RuntimeError("Session management is not available in this context") |
| 92 | + |
| 93 | + return self._null_framework.get_user_id() |
| 94 | + |
| 95 | + def set_user_id(self, user_id: str) -> None: |
| 96 | + """ |
| 97 | + Set the current user ID for the session. |
| 98 | + |
| 99 | + This method allows you to set the current user session, which is useful |
| 100 | + for applications that need to manage multiple user sessions or when |
| 101 | + integrating with custom session management systems. |
| 102 | + |
| 103 | + Args: |
| 104 | + user_id (str): The user ID to set as current |
| 105 | + |
| 106 | + Raises: |
| 107 | + RuntimeError: If session management is not available in this context |
| 108 | + ValueError: If user_id is empty or None |
| 109 | + """ |
| 110 | + if not self._null_framework: |
| 111 | + raise RuntimeError("Session management is not available in this context") |
| 112 | + |
| 113 | + if not user_id or not user_id.strip(): |
| 114 | + raise ValueError("user_id cannot be empty or None") |
| 115 | + |
| 116 | + self._null_framework.set_user_id(user_id) |
| 117 | + self._logger.debug(f"Set user ID: {user_id}") |
| 118 | + |
| 119 | + def clear_user_id(self) -> None: |
| 120 | + """ |
| 121 | + Clear the current user ID from the session. |
| 122 | + |
| 123 | + This method removes the current user session, effectively logging out |
| 124 | + the user from the current context. |
| 125 | + |
| 126 | + Raises: |
| 127 | + RuntimeError: If session management is not available in this context |
| 128 | + """ |
| 129 | + if not self._null_framework: |
| 130 | + raise RuntimeError("Session management is not available in this context") |
| 131 | + |
| 132 | + self._null_framework.clear_user_id() |
| 133 | + self._logger.debug("Cleared user ID from session") |
| 134 | + |
| 135 | + def is_user_logged_in(self) -> bool: |
| 136 | + """ |
| 137 | + Check if a user is currently logged in. |
| 138 | + |
| 139 | + Returns: |
| 140 | + bool: True if a user is logged in, False otherwise |
| 141 | + """ |
| 142 | + if not self._null_framework: |
| 143 | + raise RuntimeError("Session management is not available in this context") |
| 144 | + |
| 145 | + user_id = self._null_framework.get_user_id() |
| 146 | + return user_id is not None and user_id.strip() != "" |
| 147 | + |
| 148 | + def get_session_info(self) -> dict: |
| 149 | + """ |
| 150 | + Get information about the current session. |
| 151 | + |
| 152 | + Returns: |
| 153 | + dict: A dictionary containing session information |
| 154 | + |
| 155 | + Raises: |
| 156 | + RuntimeError: If session management is not available in this context |
| 157 | + """ |
| 158 | + if not self._null_framework: |
| 159 | + raise RuntimeError("Session management is not available in this context") |
| 160 | + |
| 161 | + user_id = self._null_framework.get_user_id() |
| 162 | + |
| 163 | + return { |
| 164 | + "user_id": user_id, |
| 165 | + "is_logged_in": user_id is not None and user_id.strip() != "", |
| 166 | + "framework": "standalone", |
| 167 | + "session_type": "null_framework" |
| 168 | + } |
| 169 | + |
| 170 | + def __repr__(self) -> str: |
| 171 | + """Return a string representation of the session management object.""" |
| 172 | + if not self._null_framework: |
| 173 | + return "KindeSessionManagement(unavailable - not in standalone mode)" |
| 174 | + |
| 175 | + user_id = self._null_framework.get_user_id() |
| 176 | + status = "logged_in" if user_id else "not_logged_in" |
| 177 | + return f"KindeSessionManagement(user_id={user_id}, status={status})" |
0 commit comments