middleware.py 857 B

12345678910111213141516171819
  1. from django.http import HttpResponseRedirect
  2. from django.conf import settings
  3. BASE_PATH = getattr(settings, 'BASE_PATH', False)
  4. LOGIN_REQUIRED = getattr(settings, 'LOGIN_REQUIRED', False)
  5. class LoginRequiredMiddleware:
  6. """
  7. If LOGIN_REQUIRED is True, redirect all non-authenticated users to the login page.
  8. """
  9. def process_request(self, request):
  10. if LOGIN_REQUIRED and not request.user.is_authenticated():
  11. # Redirect unauthenticated requests to the login page. API requests are exempt from redirection as the API
  12. # performs its own authentication.
  13. api_path = '/{}api/'.format(BASE_PATH)
  14. if not request.path_info.startswith(api_path) and request.path_info != settings.LOGIN_URL:
  15. return HttpResponseRedirect('{}?next={}'.format(settings.LOGIN_URL, request.path_info))