当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Django 1.10 authentication on all apps

问题描述:

My Django project is a single web site which has the following directory structure:

project

-- main_folder

-- settings.py

-- views.py

-- urls.py [1]

-- ...

-- app_folder

-- views.py

-- urls.py [2]

-- ...

-- not_app_folder

-- views.py

-- urls.py [3]

-- ...

-- manage.py

I use this code in urls.py [1] to authenticate a user:

from django.contrib.auth import views as auth_views

...

urlpatterns = [

url(r'^login/$', auth_views.login),

...

]

I have a code that successfully worked on all of my web-site pages with Django 1.9 (a template method {% if user.is_authenticated %} returns true on all pages).

After upgrade authentication works well on all urls from urls.py [1] file, but when I move to pages mentioned in urls.py [2] (it is an application directory) or urls.py [3] (it is a simple directory), template method {% if user.is_authenticated %} returns false (I have the same template for all pages).

What has changed in Django 1.10 and how to keep authentication alive on any page of a web-site?

网友答案:

One should be very careful when upgrading Django. Many functions become deprecated but are still working and not as expected.

This code worked fine in Django 1.9:

vars = RequestContext(request, {'key': 'value'})
return render_to_response('template.html', vars)

But render_to_response will be deprecated soon and for Django 1.10 you should write:

return render(request, 'template.html', {'key': 'value'})

There was no difference in how many apps or views.py files you have. User authentication works properly now.

网友答案:

I use this middleware I found at https://djangosnippets.org/snippets/2845/. It even have regular expression whitelist on URLs(LOGIN_EXEMPT_URLS)

# -*- coding: UTF-8 -*-

# django dependencies
from django.contrib.auth.views import redirect_to_login
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.conf import settings

# python dependencies
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):            
                path = request.get_full_path()
                return redirect_to_login(path, settings.LOGIN_URL,
                                         REDIRECT_FIELD_NAME)

Just put it after django.contrib.auth.middleware.*AuthenticationMiddleware to your MIDDLEWARE_CLASSES in settings. If you don't have it there you have to add it.

MIDDLEWARE_CLASSES = (
    'django.middleware.security.SecurityMiddleware',
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'sis_tools.middleware.LoginRequiredMiddleware', # <-- HERE
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
)

The white list works like the urls.py so you can use it like this:

LOGIN_EXEMPT_URLS = ( r'^about.html$', r'^legal/',)

This allows user to visit page sample.com/about.html and everything in section sample.com/legal/*


Also you have to set in your settings LOGIN_URL to your login page like this:

LOGIN_PAGE = "/accounts/login"

Also it's handy to set LOGIN_REDIRECT_URL url where to jump if user enters the site on login page.

LOGIN_REDIRECT_URL = "/"
分享给朋友:
您可能感兴趣的文章:
随机阅读: