Django: How can I apply the login_required decorator to my entire site (excluding static media)?

前端 未结 10 1999
日久生厌
日久生厌 2020-12-24 07:21

The example provides a snippet for an application level view, but what if I have lots of different (and some non-application) entries in my \"urls.py\" file, including templ

相关标签:
10条回答
  • 2020-12-24 08:00

    If you have lots of views and you do not want to touch any one you can just use Middleware for this issue. Try code below:

    
    import traceback
    from django.contrib.auth.decorators import login_required
    
    
    class RejectAnonymousUsersMiddleware(object):
    
        def process_view(self, request, view_func, view_args, view_kwargs):
            current_route_name = resolve(request.path_info).url_name
    
            if current_route_name in settings.AUTH_EXEMPT_ROUTES:
                return
    
            if  request.user.is_authenticated:
                return
    
            return login_required(view_func)(request, *view_args, **view_kwargs)
    

    Cautions:

    • You must add this middleware to the bottommost of middleware section of settings.py
    • You should put this variable in settings.py
      • AUTH_EXEMPT_ROUTES = ('register', 'login', 'forgot-password')
    0 讨论(0)
  • 2020-12-24 08:01

    Use middleware.

    http://www.djangobook.com/en/2.0/chapter17/ and http://docs.djangoproject.com/en/1.2/topics/http/middleware/#topics-http-middleware

    I'm assuming this didn't change a whole lot in 1.2

    Middleware allows you to create a class with methods who will process every request at various times/conditions, as you define.

    for example process_request(request) would fire before your view, and you can force authentication and authorization at this point.

    0 讨论(0)
  • 2020-12-24 08:02

    Dropped this into a middleware.py file in my project root (taken from http://onecreativeblog.com/post/59051248/django-login-required-middleware)

    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)
    

    Then appended projectname.middleware.LoginRequiredMiddleware to my MIDDLEWARE_CLASSES in settings.py.

    0 讨论(0)
  • 2020-12-24 08:09

    In addition to meder omuraliev answer if you want exempt url like this (with regexp):

    url(r'^my/url/(?P<pk>[0-9]+)/$', views.my_view, name='my_url')
    

    add it to EXEMPT_URLS list like this:

    LOGIN_EXEMPT_URLS = [r'^my/url/([0-9]+)/$']
    

    r'..' in the beginning of the string necessary.

    0 讨论(0)
提交回复
热议问题