|
1 | 1 | from __future__ import annotations
|
2 | 2 |
|
| 3 | +import asyncio |
| 4 | +from logging import getLogger |
3 | 5 | from typing import TYPE_CHECKING
|
| 6 | +from uuid import uuid4 |
4 | 7 |
|
| 8 | +from django.urls import reverse |
5 | 9 | from reactpy import component, hooks
|
6 | 10 |
|
| 11 | +from reactpy_django.javascript_components import HttpRequest |
| 12 | +from reactpy_django.models import AuthSession |
| 13 | + |
7 | 14 | if TYPE_CHECKING:
|
8 | 15 | from django.contrib.sessions.backends.base import SessionBase
|
9 | 16 |
|
10 |
| -from reactpy_django.javascript_components import HttpRequest |
| 17 | +_logger = getLogger(__name__) |
11 | 18 |
|
12 | 19 |
|
13 | 20 | @component
|
14 | 21 | def auth_manager():
|
15 |
| - session_cookie, set_session_cookie = hooks.use_state("") |
| 22 | + """Component that can force the client to switch HTTP sessions to match the websocket session. |
| 23 | +
|
| 24 | + Used to force persistent authentication between Django's websocket and HTTP stack.""" |
| 25 | + from reactpy_django import config |
| 26 | + |
| 27 | + switch_sessions, set_switch_sessions = hooks.use_state(False) |
| 28 | + uuid = hooks.use_ref(str(uuid4())).current |
16 | 29 | scope = hooks.use_connection().scope
|
17 | 30 |
|
18 |
| - @hooks.use_effect(dependencies=None) |
19 |
| - async def _session_check(): |
20 |
| - """Generate a session cookie if `login` was called in a user's component.""" |
21 |
| - from django.conf import settings |
| 31 | + @hooks.use_effect(dependencies=[]) |
| 32 | + def setup_asgi_scope(): |
| 33 | + """Store a trigger function in websocket scope so that ReactPy-Django's hooks can command a session synchronization.""" |
| 34 | + scope["reactpy-synchronize-session"] = synchronize_session |
| 35 | + print("configure_asgi_scope") |
| 36 | + |
| 37 | + @hooks.use_effect(dependencies=[switch_sessions]) |
| 38 | + async def synchronize_session_timeout(): |
| 39 | + """Ensure that the ASGI scope is available to this component.""" |
| 40 | + if switch_sessions: |
| 41 | + await asyncio.sleep(config.REACTPY_AUTH_TIMEOUT + 0.1) |
| 42 | + await asyncio.to_thread( |
| 43 | + _logger.warning, |
| 44 | + f"Client did not switch sessions within {config.REACTPY_AUTH_TIMEOUT} (REACTPY_AUTH_TIMEOUT) seconds.", |
| 45 | + ) |
| 46 | + set_switch_sessions(False) |
22 | 47 |
|
| 48 | + async def synchronize_session(): |
| 49 | + """Entrypoint where the server will command the client to switch HTTP sessions |
| 50 | + to match the websocket session. This function is stored in the websocket scope so that |
| 51 | + ReactPy-Django's hooks can access it.""" |
| 52 | + print("sync command ", uuid) |
23 | 53 | session: SessionBase | None = scope.get("session")
|
24 |
| - login_required: bool = scope.get("reactpy-login", False) |
25 |
| - if not login_required or not session or not session.session_key: |
| 54 | + if not session or not session.session_key: |
| 55 | + print("sync error") |
26 | 56 | return
|
27 | 57 |
|
28 |
| - # Begin generating a cookie string |
29 |
| - key = session.session_key |
30 |
| - domain: str | None = settings.SESSION_COOKIE_DOMAIN |
31 |
| - httponly: bool = settings.SESSION_COOKIE_HTTPONLY |
32 |
| - name: str = settings.SESSION_COOKIE_NAME |
33 |
| - path: str = settings.SESSION_COOKIE_PATH |
34 |
| - samesite: str | bool = settings.SESSION_COOKIE_SAMESITE |
35 |
| - secure: bool = settings.SESSION_COOKIE_SECURE |
36 |
| - new_cookie = f"{name}={key}" |
37 |
| - if domain: |
38 |
| - new_cookie += f"; Domain={domain}" |
39 |
| - if httponly: |
40 |
| - new_cookie += "; HttpOnly" |
41 |
| - if isinstance(path, str): |
42 |
| - new_cookie += f"; Path={path}" |
43 |
| - if samesite: |
44 |
| - new_cookie += f"; SameSite={samesite}" |
45 |
| - if secure: |
46 |
| - new_cookie += "; Secure" |
47 |
| - if not session.get_expire_at_browser_close(): |
48 |
| - session_max_age: int = session.get_expiry_age() |
49 |
| - session_expiration: str = session.get_expiry_date().strftime("%a, %d-%b-%Y %H:%M:%S GMT") |
50 |
| - if session_expiration: |
51 |
| - new_cookie += f"; Expires={session_expiration}" |
52 |
| - if isinstance(session_max_age, int): |
53 |
| - new_cookie += f"; Max-Age={session_max_age}" |
| 58 | + await AuthSession.objects.aget_or_create(uuid=uuid, session_key=session.session_key) |
| 59 | + set_switch_sessions(True) |
54 | 60 |
|
55 |
| - # Save the cookie within this component's state so that the client-side component can ingest it |
56 |
| - scope.pop("reactpy-login") |
57 |
| - if new_cookie != session_cookie: |
58 |
| - set_session_cookie(new_cookie) |
59 |
| - |
60 |
| - def http_request_callback(status_code: int, response: str): |
61 |
| - """Remove the cookie from server-side memory if it was successfully set. |
62 |
| - Doing this will subsequently remove the client-side HttpRequest component from the DOM.""" |
63 |
| - set_session_cookie("") |
64 |
| - # if status_code >= 300: |
65 |
| - # print(f"Unexpected status code {status_code} while trying to login user.") |
| 61 | + async def synchronize_sessions_callback(status_code: int, response: str): |
| 62 | + """This callback acts as a communication bridge between the client and server, notifying the server |
| 63 | + of the client's response to the session switch command.""" |
| 64 | + print("callback") |
| 65 | + set_switch_sessions(False) |
| 66 | + if status_code >= 300 or status_code < 200: |
| 67 | + await asyncio.to_thread( |
| 68 | + _logger.warning, |
| 69 | + f"Client returned unexpected HTTP status code ({status_code}) while trying to sychronize sessions.", |
| 70 | + ) |
66 | 71 |
|
67 | 72 | # If a session cookie was generated, send it to the client
|
68 |
| - if session_cookie: |
69 |
| - # print("Session Cookie: ", session_cookie) |
| 73 | + print("render") |
| 74 | + if switch_sessions: |
| 75 | + print("switching to ", uuid) |
70 | 76 | return HttpRequest(
|
71 | 77 | {
|
72 |
| - "method": "POST", |
73 |
| - "url": "", |
74 |
| - "body": {}, |
75 |
| - "callback": http_request_callback, |
| 78 | + "method": "GET", |
| 79 | + "url": reverse("reactpy:switch_session", args=[uuid]), |
| 80 | + "body": None, |
| 81 | + "callback": synchronize_sessions_callback, |
76 | 82 | },
|
77 | 83 | )
|
78 |
| - |
79 | 84 | return None
|
0 commit comments