2014-05-09 34 views
2

我想重寫Django登錄進行自定義登錄,但我找不到方法。如何重寫Django登錄

原因是有一個特定的情況,我不能使用csrf身份驗證,所以我想創建一個自定義登錄,然後建立一個安全層,以確保我的自定義登錄是安全的。

任何想法?

+0

只是找到了第二個發佈後:https://docs.djangoproject.com/en/1.5/topics/auth/default/#how-to-log -a-user-in – Sascuash

+0

自定義登錄與CSRF不同,完全不相關。自定義登錄與令牌有關,而CSRF則與cookie有關。 –

+0

嗯,是的,我知道,自定義登錄正是爲了避免使用cookie(和CSRF) – Sascuash

回答

2

要覆蓋Django的自定義管理員,你必須創建URL路徑和視圖,你檢查並登錄/註銷用戶。 藉此例如:

urls.py

url(r'^accounts/auth/$', 'auth_view'), 

views.py

from django.contrib import auth 

def auth_view(request): 

    # here you get the post request username and password 
    username = request.POST.get('username', '') 
    password = request.POST.get('password', '') 

    # authentication of the user, to check if it's active or None 
    user = auth.authenticate(username=username, password=password) 

    if user is not None: 
     if user.is_active: 
      # this is where the user login actually happens, before this the user 
      # is not logged in. 
      auth.login(request, user) 

      ... 
      return ... 

    else : 
     return HttpResponseRedirect("Invalid username or password") 

HTML表單:

<form role="form" action="/accounts/auth/" method="POST"> 
0

urls.py

url(r'^$', auth_views.login, {'template_name': 'home/login.html'}, name='login') 

的login.html

<form method="post"> 
{{ form.as_p }} 
{{ form.non_field_errors }} 
<input type="submit"> 
</form>