Advertisement
Guest User

Untitled

a guest
Apr 21st, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1.  
  2. class RequireLoginMiddleware(object):
  3.     """
  4.    Middleware component that wraps the login_required decorator around
  5.    matching URL patterns. To use, add the class to MIDDLEWARE_CLASSES and
  6.    define LOGIN_REQUIRED_URLS and LOGIN_REQUIRED_URLS_EXCEPTIONS in your
  7.    settings.py. For example:
  8.    ------
  9.    LOGIN_REQUIRED_URLS = (
  10.        r'/topsecret/(.*)$',
  11.    )
  12.    LOGIN_REQUIRED_URLS_EXCEPTIONS = (
  13.        r'/topsecret/login(.*)$',
  14.        r'/topsecret/logout(.*)$',
  15.    )
  16.    ------
  17.    LOGIN_REQUIRED_URLS is where you define URL patterns; each pattern must
  18.    be a valid regex.
  19.  
  20.    LOGIN_REQUIRED_URLS_EXCEPTIONS is, conversely, where you explicitly
  21.    define any exceptions (like login and logout URLs).
  22.    """
  23.     def __init__(self):
  24.         self.required = tuple([re.compile(url) for url in settings.LOGIN_REQUIRED_URLS])
  25.         self.exceptions = tuple([re.compile(url) for url in
  26.                                  settings.LOGIN_REQUIRED_URLS_EXCEPTIONS])
  27.  
  28.     def process_view(self, request, view_func, view_args, view_kwargs):
  29.         # No need to process URLs if user already logged in
  30.         if request.user.is_authenticated():
  31.             return None
  32.         # An exception match should immediately return None
  33.         for url in self.exceptions:
  34.             if url.match(request.path):
  35.                 return None
  36.             # Requests matching a restricted URL pattern are returned
  37.         # wrapped with the login_required decorator
  38.         for url in self.required:
  39.             if url.match(request.path):
  40.                 return login_required(view_func)(request, *view_args, **view_kwargs)
  41.             # Explicitly return None for all non-matching requests
  42.         return None
  43.  
  44.  
  45.  
  46. # LoginRequiredMiddleware
  47. LOGIN_REQUIRED_URLS = (
  48.     r'^/(.*)$',
  49.  
  50. )
  51. LOGIN_REQUIRED_URLS_EXCEPTIONS = (
  52.     r'^/admin/(.*)$',
  53.     r'^/accounts/login/$',
  54.     r'^/accounts/logout/$',
  55.     # r'^/accounts/password_reset/$',
  56.     # r'^/accounts/password_reset/done/$',
  57.     # r'^/accounts/reset/.*/$',
  58. )
  59. LOGIN_REDIRECT_URL = '/'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement