| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from importlib import import_module |
| 4 |
from urllib.parse import urlparse |
| 5 |
|
| 6 |
from django.conf import settings |
| 7 |
from django.contrib.sessions.backends.base import SessionBase |
| 8 |
from django.http import HttpRequest |
| 9 |
from django.utils.cache import patch_vary_headers |
| 10 |
|
| 11 |
|
| 12 |
engine = import_module(settings.SESSION_ENGINE) |
| 13 |
SessionStore = engine.SessionStore |
| 14 |
|
| 15 |
|
| 16 |
class LoginSession: |
| 17 |
"""Some providers sometimes POST their responses, which due to |
| 18 |
CORS/Samesite-cookie rules means that this request cannot access the session |
| 19 |
as its session cookie is unavailable. |
| 20 |
|
| 21 |
We work around this by storing the response in a separate, temporary session |
| 22 |
and redirecting to a different endpoint that can pick up the flow. |
| 23 |
""" |
| 24 |
|
| 25 |
def __init__(self, request: HttpRequest, attribute_name, cookie_name) -> None: |
| 26 |
""" |
| 27 |
Prepares an provider specific session. |
| 28 |
""" |
| 29 |
self.request = request |
| 30 |
self.attribute_name = attribute_name |
| 31 |
self.cookie_name = cookie_name |
| 32 |
store = getattr(request, attribute_name, None) |
| 33 |
if store is None: |
| 34 |
session_key = request.COOKIES.get(cookie_name) |
| 35 |
store = SessionStore(session_key) |
| 36 |
setattr(request, attribute_name, store) |
| 37 |
self.store: SessionBase = store |
| 38 |
|
| 39 |
def save(self, response) -> None: |
| 40 |
""" |
| 41 |
Save the session and set a cookie. |
| 42 |
""" |
| 43 |
patch_vary_headers(response, ("Cookie",)) |
| 44 |
self.store.save() |
| 45 |
kwargs = {} |
| 46 |
samesite = getattr(settings, "SESSION_COOKIE_SAMESITE", None) |
| 47 |
if samesite: |
| 48 |
kwargs["samesite"] = samesite |
| 49 |
response.set_cookie( |
| 50 |
self.cookie_name, |
| 51 |
self.store.session_key, |
| 52 |
max_age=None, |
| 53 |
expires=None, |
| 54 |
domain=settings.SESSION_COOKIE_DOMAIN, |
| 55 |
# The cookie is only needed on this endpoint |
| 56 |
path=urlparse(response.url).path, |
| 57 |
secure=settings.SESSION_COOKIE_SECURE, |
| 58 |
httponly=None, |
| 59 |
**kwargs, |
| 60 |
) |
| 61 |
|
| 62 |
def delete(self) -> None: |
| 63 |
self.store.delete() |