Django global login middleware


/ Published in: Python
Save to your folder(s)

Django's middleware for global app login. With this middleware you don't have to decorate views by login_required decorator.


Copy this code and paste it in your HTML
  1. from django.conf import settings
  2. from django.shortcuts import redirect
  3. from re import compile
  4.  
  5. EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
  6.  
  7. if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
  8. EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
  9.  
  10. class AccountsMiddleware():
  11. def process_request(self, request):
  12. if request.user.is_anonymous():
  13. path = request.path_info.lstrip('/')
  14. if not any(m.match(path) for m in EXEMPT_URLS):
  15. return redirect(settings.LOGIN_URL)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.