|
| 1 | +# Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. |
| 2 | +# |
| 3 | +# This software is licensed under the Apache License, Version 2.0 (the |
| 4 | +# "License") as published by the Apache Software Foundation. |
| 5 | +# |
| 6 | +# You may not use this file except in compliance with the License. You may |
| 7 | +# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | +# License for the specific language governing permissions and limitations |
| 13 | +# under the License. |
| 14 | +import asyncio |
| 15 | +from typing import Any |
| 16 | + |
| 17 | +from litestar import Request, Response |
| 18 | + |
| 19 | +from supertokens_python.exceptions import SuperTokensError |
| 20 | + |
| 21 | + |
| 22 | +def supertokens_exception_handler( |
| 23 | + request: Request[Any, Any, Any], exc: SuperTokensError |
| 24 | +) -> Response[Any]: |
| 25 | + """ |
| 26 | + Exception handler for SuperTokens errors in Litestar applications. |
| 27 | +
|
| 28 | + This handler intercepts SuperTokens exceptions and converts them to proper |
| 29 | + HTTP responses with session management. |
| 30 | +
|
| 31 | + Note: This is a synchronous wrapper around async SuperTokens error handling. |
| 32 | + Litestar requires exception handlers to be synchronous, so we run the async |
| 33 | + logic in the event loop. |
| 34 | +
|
| 35 | + Args: |
| 36 | + request: The Litestar request object |
| 37 | + exc: The SuperTokens exception |
| 38 | +
|
| 39 | + Returns: |
| 40 | + A Litestar Response object with proper status code and session cookies |
| 41 | + """ |
| 42 | + from supertokens_python import Supertokens |
| 43 | + from supertokens_python.framework.litestar.litestar_request import LitestarRequest |
| 44 | + from supertokens_python.framework.litestar.litestar_response import LitestarResponse |
| 45 | + from supertokens_python.utils import default_user_context |
| 46 | + |
| 47 | + async def handle_async() -> Response[Any]: |
| 48 | + """Async logic for handling the SuperTokens error""" |
| 49 | + st = Supertokens.get_instance() |
| 50 | + custom_request = LitestarRequest(request) |
| 51 | + user_context = default_user_context(custom_request) |
| 52 | + |
| 53 | + # Create a response for SuperTokens to populate |
| 54 | + response_obj = Response(content=None) |
| 55 | + response = LitestarResponse(response_obj) |
| 56 | + |
| 57 | + # Handle the error through SuperTokens |
| 58 | + # This will modify the response object with proper status code, |
| 59 | + # clear tokens, and set appropriate headers |
| 60 | + result = await st.handle_supertokens_error( |
| 61 | + custom_request, |
| 62 | + exc, |
| 63 | + response, |
| 64 | + user_context, # type: ignore |
| 65 | + ) |
| 66 | + |
| 67 | + # Return the modified Litestar response |
| 68 | + # The response object has been updated by SuperTokens error handlers |
| 69 | + if isinstance(result, LitestarResponse): |
| 70 | + litestar_response = result.response |
| 71 | + |
| 72 | + # Clear the session from request.state to prevent the middleware |
| 73 | + # from re-applying session cookies after we've cleared them |
| 74 | + if hasattr(request.state, "supertokens"): |
| 75 | + delattr(request.state, "supertokens") |
| 76 | + |
| 77 | + # Litestar stores cookies separately from headers. When an exception |
| 78 | + # handler returns a response, Litestar will automatically convert cookies |
| 79 | + # to Set-Cookie headers. So we can just return the response as-is. |
| 80 | + return litestar_response |
| 81 | + |
| 82 | + # Fallback to a generic error response |
| 83 | + return Response( |
| 84 | + content={"message": str(exc)}, |
| 85 | + status_code=500, |
| 86 | + ) |
| 87 | + |
| 88 | + # Run the async logic in the event loop |
| 89 | + try: |
| 90 | + loop = asyncio.get_running_loop() |
| 91 | + except RuntimeError: |
| 92 | + # No event loop running, create one |
| 93 | + loop = asyncio.new_event_loop() |
| 94 | + asyncio.set_event_loop(loop) |
| 95 | + try: |
| 96 | + return loop.run_until_complete(handle_async()) |
| 97 | + finally: |
| 98 | + loop.close() |
| 99 | + else: |
| 100 | + # Event loop is already running (which is the case in Litestar) |
| 101 | + # Create a task and run it |
| 102 | + import nest_asyncio # type: ignore |
| 103 | + |
| 104 | + nest_asyncio.apply() |
| 105 | + return loop.run_until_complete(handle_async()) |
| 106 | + |
| 107 | + |
| 108 | +def get_exception_handlers() -> dict[int | type[Exception], Any]: |
| 109 | + """ |
| 110 | + Get exception handlers for SuperTokens errors. |
| 111 | +
|
| 112 | + Returns: |
| 113 | + A dictionary mapping exception types to handler functions. |
| 114 | +
|
| 115 | + Example: |
| 116 | + ```python |
| 117 | + from litestar import Litestar |
| 118 | + from supertokens_python.framework.litestar import ( |
| 119 | + get_exception_handlers, |
| 120 | + get_supertokens_plugin, |
| 121 | + create_supertokens_middleware, |
| 122 | + ) |
| 123 | +
|
| 124 | + app = Litestar( |
| 125 | + route_handlers=[...], |
| 126 | + middleware=[create_supertokens_middleware()], |
| 127 | + plugins=[get_supertokens_plugin(api_base_path="/auth")], |
| 128 | + exception_handlers=get_exception_handlers(), |
| 129 | + ) |
| 130 | + ``` |
| 131 | + """ |
| 132 | + return {SuperTokensError: supertokens_exception_handler} # type: ignore |
0 commit comments