Hide keyboard shortcuts

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 

2 

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 

10 

11# Exports 

12 

13__all__ = ( 

14 "LoginRequiredMiddleware", 

15) 

16 

17# Constants 

18 

19# Get the default redirect URL. 

20LOGIN_REDIRECT_URL = settings.LOGIN_REDIRECT_URL 

21 

22# Get the LOGIN_URL in case we need to redirect. 

23LOGIN_URL = settings.LOGIN_URL 

24 

25# The login URL must be excluded or you'd never be able to get to it. 

26EXCLUDED_URLS = [re.compile(LOGIN_URL.lstrip('/'))] 

27 

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] 

31 

32# Middleware 

33 

34 

35class LoginRequiredMiddleware(object): 

36 """Require a user login for the whole site, except certain URLs. 

37 

38 .. code-block:: python 

39 

40 # settings.py 

41 MIDDLEWARE = [ 

42 # ... 

43 'superdjango.accounts.middleware.LoginRequiredMiddleware', 

44 ] 

45 

46 .. note:: 

47 This requires ``django.contrib.auth.middleware.AuthenticationMiddleware`` in ``MIDDLEWARE_CLASSES`` and 

48 ``django.core.context_processors.auth`` in your ``TEMPLATES`` configuration. 

49 

50 """ 

51 

52 # noinspection PyMethodMayBeStatic 

53 def process_request(self, request): 

54 

55 if not hasattr(request, "user"): 

56 raise NoUserInRequest() 

57 

58 if not request.user.is_authenticated: 

59 path = request.path_info.lstrip('/') 

60 

61 if not any(m.match(path) for m in EXCLUDED_URLS): 

62 redirect_url = LOGIN_URL 

63 

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) 

66 

67 return HttpResponseRedirect(redirect_url)