From d7608df5574584faacb9cf3ff4f105ab08db2446 Mon Sep 17 00:00:00 2001 From: Richard Tibbles Date: Wed, 3 Jul 2024 16:02:01 -0700 Subject: [PATCH] Redirect a logged out user back to the last page they were on. --- kolibri/core/assets/src/heartbeat.js | 2 +- kolibri/core/assets/src/utils/redirectBrowser.js | 9 +++++++-- kolibri/core/views.py | 11 +++++++++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/kolibri/core/assets/src/heartbeat.js b/kolibri/core/assets/src/heartbeat.js index 9c78fe954c..93eba89efe 100644 --- a/kolibri/core/assets/src/heartbeat.js +++ b/kolibri/core/assets/src/heartbeat.js @@ -266,7 +266,7 @@ export class HeartBeat { Lockr.set(SIGNED_OUT_DUE_TO_INACTIVITY, true); // Redirect the user to let the server sort out where they should // be now - redirectBrowser(); + redirectBrowser(null, true); } _sessionUrl(id) { return urls['kolibri:core:session-detail'](id); diff --git a/kolibri/core/assets/src/utils/redirectBrowser.js b/kolibri/core/assets/src/utils/redirectBrowser.js index 00ad647732..9d7bc913e2 100644 --- a/kolibri/core/assets/src/utils/redirectBrowser.js +++ b/kolibri/core/assets/src/utils/redirectBrowser.js @@ -1,5 +1,10 @@ import urls from 'kolibri.urls'; -export default function redirectBrowser(url) { - window.location.href = url || urls['kolibri:core:redirect_user'](); +export default function redirectBrowser(url, next = false) { + url = url || urls['kolibri:core:redirect_user'](); + const urlObject = new URL(url, window.location.origin); + if (next) { + urlObject.searchParams.set('next', encodeURIComponent(window.location.href)); + } + window.location.href = urlObject.href; } diff --git a/kolibri/core/views.py b/kolibri/core/views.py index 4b59d063cc..b810a27ed3 100644 --- a/kolibri/core/views.py +++ b/kolibri/core/views.py @@ -10,6 +10,7 @@ from django.urls import reverse from django.urls import translate_url from django.utils.decorators import method_decorator +from django.utils.http import url_has_allowed_host_and_scheme from django.utils.translation import check_for_language from django.utils.translation import gettext_lazy as _ from django.utils.translation import LANGUAGE_SESSION_KEY @@ -179,6 +180,16 @@ def get(self, request): else: url = get_url_by_role(user_kinds.ANONYMOUS) if url: + next_url = request.GET.get("next") + if next_url: + # Step 2: Validate the next_url + if url_has_allowed_host_and_scheme( + next_url, + allowed_hosts={request.get_host()}, + require_https=request.is_secure(), + ): + # Step 3: Append next_url to the base url if it's valid + url = f"{url}?next={next_url}" return HttpResponseRedirect(url) raise Http404( _(