django login required for the entire site not working

897 views Asked by At

I am trying to use a code to force login if a user is not authenticated yet. I have tried too many codes and I could not get them working since most of them written in older versions of django. I am using django 1.10.3.

I am not getting any errors when running the server, but I am not getting redirected to the login page too while I am not logged in. I am not even sure we can have both MIDDLEWARE AND MIDDLEWARE_ClASSES in the setting file. Any help would be appreciated. I also would like to have exceptions where I can make some of the views public that requires no login

middleware.py:

from builtins import hasattr, any
from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile

EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]

class LoginRequiredMiddleware:
    """
    Middleware that requires a user to be authenticated to view any page other
    than LOGIN_URL. Exemptions to this requirement can optionally be specified
    in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
    you can copy from your urls.py).

    Requires authentication middleware and template context processors to be
    loaded. You'll get an error if they aren't.
    """
    def process_request(self, request):
        assert hasattr(request, 'user'), "The Login Required middleware\
 requires authentication middleware to be installed. Edit your\
 MIDDLEWARE_CLASSES setting to insert\
 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
 work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
 'django.core.context_processors.auth'."
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(settings.LOGIN_URL)

setting.py:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'heaven.LoginRequiredMiddleware',
]
1

There are 1 answers

0
Elnur Mammadli On BEST ANSWER

Django changed middleware logic at Django 1.10 . Django 1.10 has a new approach. here

My middleware class. It is working

# Below middleware class for Django1.10
  class StatisticMiddleware:
      def __init__(self, get_response):
          self.get_response = get_response
      # One-time configuration and initialization.

      def __call__(self, request):
          # Code to be executed for each request before
          # the view (and later middleware) are called.

          response = self.get_response(request)

          self.__model_object_statistics(request, response)

          return response
      def __model_object_statistics(self, request, response):
          # My algorithms