Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3from django.conf import settings
4from django.http import HttpResponseRedirect
5from django.utils.http import is_safe_url
6from django.contrib.auth.views import REDIRECT_FIELD_NAME
7import re
8from superdjango.conf import SUPERDJANGO
9from superdjango.exceptions import NoUserInRequest
11# Exports
13__all__ = (
14 "LoginRequiredMiddleware",
15)
17# Constants
19# Get the default redirect URL.
20LOGIN_REDIRECT_URL = settings.LOGIN_REDIRECT_URL
22# Get the LOGIN_URL in case we need to redirect.
23LOGIN_URL = settings.LOGIN_URL
25# The login URL must be excluded or you'd never be able to get to it.
26EXCLUDED_URLS = [re.compile(LOGIN_URL.lstrip('/'))]
28# Additional URLs may be added in settings.
29if SUPERDJANGO.USER_LOGIN_EXCLUDED_URLS:
30 EXCLUDED_URLS += [re.compile(expr) for expr in SUPERDJANGO.USER_LOGIN_EXCLUDED_URLS]
32# Middleware
35class LoginRequiredMiddleware(object):
36 """Require a user login for the whole site, except certain URLs.
38 .. code-block:: python
40 # settings.py
41 MIDDLEWARE = [
42 # ...
43 'superdjango.accounts.middleware.LoginRequiredMiddleware',
44 ]
46 .. note::
47 This requires ``django.contrib.auth.middleware.AuthenticationMiddleware`` in ``MIDDLEWARE_CLASSES`` and
48 ``django.core.context_processors.auth`` in your ``TEMPLATES`` configuration.
50 """
52 # noinspection PyMethodMayBeStatic
53 def process_request(self, request):
55 if not hasattr(request, "user"):
56 raise NoUserInRequest()
58 if not request.user.is_authenticated:
59 path = request.path_info.lstrip('/')
61 if not any(m.match(path) for m in EXCLUDED_URLS):
62 redirect_url = LOGIN_URL
64 if len(path) > 0 and is_safe_url(request.path_info, [request.get_host()]):
65 redirect_url = "%s?%s=%s" % (LOGIN_URL, REDIRECT_FIELD_NAME, request.path_info)
67 return HttpResponseRedirect(redirect_url)