From a16f332481913670fc5ec2c2f4f06d62881278eb Mon Sep 17 00:00:00 2001 From: Vinod Kurup Date: Wed, 19 Aug 2020 11:29:11 -0400 Subject: [PATCH] Support named URL patterns for LOGIN_URL --- .gitignore | 1 + security/middleware.py | 3 ++- testing/tests/tests.py | 16 ++++++++++++++++ tox.ini | 6 ++++-- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index a5464e5..9faa6af 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ # ignore setup.py build dir build/ +*.egg-info/ # ignore sphinx built documentation _build/ diff --git a/security/middleware.py b/security/middleware.py index 870d857..8685c38 100644 --- a/security/middleware.py +++ b/security/middleware.py @@ -12,6 +12,7 @@ from django.core.exceptions import ImproperlyConfigured from django.urls import reverse, resolve from django.http import HttpResponseRedirect, HttpResponse +from django.shortcuts import resolve_url from django.test.signals import setting_changed from django.utils import timezone from django.utils.deprecation import MiddlewareMixin @@ -1208,7 +1209,7 @@ class LoginRequiredMiddleware(BaseMiddleware, CustomLogoutMixin): def load_setting(self, setting, value): if setting == 'LOGIN_URL': - self.login_url = value + self.login_url = resolve_url(value) elif setting == 'LOGIN_EXEMPT_URLS': self.exempt_urls = [compile(expr) for expr in (value or ())] else: diff --git a/testing/tests/tests.py b/testing/tests/tests.py index 523afeb..cb9fc0a 100644 --- a/testing/tests/tests.py +++ b/testing/tests/tests.py @@ -184,6 +184,22 @@ def test_redirects_to_custom_login_url(self): {"login_url": '/custom-login/'}, ) + def test_redirects_to_named_url_pattern(self): + with self.settings( + LOGIN_URL="login", # <- use a named pattern from urls.py + ): + response = self.client.get('/home/') + self.assertRedirects(response, reverse('login') + '?next=/home/') + response = self.client.get( + '/home/', + HTTP_X_REQUESTED_WITH='XMLHttpRequest', + ) + self.assertEqual(response.status_code, 401) + self.assertEqual( + json.loads(response.content.decode('utf-8')), + {"login_url": reverse('login')}, + ) + def test_logs_out_inactive_users(self): user = User.objects.create_user( username="foo", diff --git a/tox.ini b/tox.ini index 3d5d35f..c365326 100644 --- a/tox.ini +++ b/tox.ini @@ -22,6 +22,7 @@ deps = Sphinx django==1.11 ua_parser==0.7.1 + coverage commands = make clean make html @@ -31,10 +32,11 @@ basepython = python3.6 deps= pep8-naming hacking - flake8==2.6.0 + flake8==3.8.3 + coverage commands=flake8 security testing [flake8] -ignore=E131,H306,H301,H404,H405,H101,N802,N812 +ignore=E305,E128,E131,E303,E501,H306,H301,H404,H405,H101,N802,N812,W504, max-complexity=10 exclude=*migrations*