From e801b37502586af13fedda27f18f9d4cf1d18b64 Mon Sep 17 00:00:00 2001 From: SKairinos Date: Tue, 19 Sep 2023 12:12:24 +0100 Subject: [PATCH] fix: add session expired path --- codeforlife/settings/django.py | 7 ++++++- codeforlife/urls.py | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/codeforlife/settings/django.py b/codeforlife/settings/django.py index 654bba4c..5ee4d201 100644 --- a/codeforlife/settings/django.py +++ b/codeforlife/settings/django.py @@ -7,7 +7,7 @@ from django.utils.translation import gettext_lazy as _ -from .custom import SERVICE_NAME +from .custom import SERVICE_API_URL, SERVICE_NAME # SECURITY WARNING: don't run with debug turned on in production! DEBUG = bool(int(os.getenv("DEBUG", "1"))) @@ -15,6 +15,11 @@ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv("SECRET_KEY", "replace-me") +# Auth +# https://docs.djangoproject.com/en/3.2/topics/auth/default/ + +LOGIN_URL = f"{SERVICE_API_URL}/session/expired/" + # Authentication backends # https://docs.djangoproject.com/en/3.2/ref/settings/#authentication-backends diff --git a/codeforlife/urls.py b/codeforlife/urls.py index 73141698..9a0217bd 100644 --- a/codeforlife/urls.py +++ b/codeforlife/urls.py @@ -29,6 +29,19 @@ def service_urlpatterns( LogoutView.as_view(), name="logout", ), + # Django's default behavior with the @login_required decorator is to + # redirect users to the login template found in setting LOGIN_URL. + # Because we're using a React frontend, we want to return a + # 401-Unauthorized whenever a user's session-cookie expires so we can + # redirect them to the login page. Therefore, all login redirects will + # direct to this view which will return the desired 401. + path( + "api/session/expired/", + lambda request: HttpResponse( + status=status.HTTP_401_UNAUTHORIZED, + ), + name="session-expired", + ), path( "api/", include(api_urls_path),