2014-01-14 56 views
3

我有一個包含許多網址和瀏覽量的django網站。現在我要求將所有未經過身份驗證的用戶重定向到某個登錄頁面。所以,所有視圖都必須檢查是否user.is_authenticated()並返回到一組新的着陸頁。Django,將所有未經過身份驗證的用戶重定向到登錄頁

它可以用漂亮的方式完成,而不是與我的views.py/urls.py搞得那麼糟糕?

+0

Django的據點(https://github.com/mgrouchy/django-stronghold)使默認 – RemcoGerlich

回答

11

您可以使用中間件

像這樣的事情會檢查用戶身份驗證每一個請求:

class AuthRequiredMiddleware(object): 
    def process_request(self, request): 
     if not request.user.is_authenticated(): 
      return HttpResponseRedirect(reverse('landing_page')) # or http response 
     return None 

文檔:process_request

另外,不要忘記使其能夠在settings.py

MIDDLEWARE_CLASSES = (
    ... 
    'path.to.your.AuthRequiredMiddleware', 
) 
4

看到的文檔爲login required decorator

from django.contrib.auth.decorators import login_required 

@login_required 
def my_view(request): 
    ... 

另一種選擇是將其添加到您的urls.py模式,看到this answer

urlpatterns = patterns('', 
    (r'^foo/$', login_required(direct_to_template), {'template': 'foo_index.html'}), 
) 
+0

這是我想什麼,以避免login_required所有的意見。將裝飾器添加到我的所有視圖並更改我的所有網址操作。另一方面,我不想重定向到登錄,而是到另一個頁面。如果用戶想要從該頁面可以去登錄離開。 – xpanta

2

這可以用中間件完成。

我發現了一個非常漂亮的djangosnippet,它完全符合你的要求。你可以找到它here,它看起來像:

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) 

所有你所要做的就是將文件保存爲middleware.py,幷包含類在你settings.py,即

MIDDLEWARE_CLASSES += ('projectname.common.middleware.RequireLoginMiddleware',) 

您還可以在settings.py中定義LOGIN_URL,以便您將被重定向到您的自定義登錄頁面。默認LOGIN_URL'/accounts/login/'

7

從Django 1.10起,自定義中間件類必須實現新的樣式語法。您可以使用以下類來驗證用戶在嘗試訪問任何視圖時是否已登錄。

from django.shortcuts import HttpResponseRedirect 


class AuthRequiredMiddleware(object): 
    def __init__(self, get_response): 
     self.get_response = get_response 

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

     response = self.get_response(request) 
     if not request.user.is_authenticated(): 
      return HttpResponseRedirect('login') 

     # Code to be executed for each request/response after 
     # the view is called. 

     return response 
2

還有就是要做到這一點,只需添加「LOGIN_URL」參數@login_required,如果用戶沒有登錄,他將被重定向到登錄頁面簡單的方法。你可以找到它here

from django.contrib.auth.decorators import login_required 

@login_required(login_url='/accounts/login/') 
def my_view(request): 
    ... 
相關問題