3

我正在使用自定義身份驗證後端與Django,以自動創建和從舊系統登錄用戶。我的Backend類是這樣的:Django - 閱讀當前的用戶認證後端類

from django.contrib.auth.backends import ModelBackend 
from django.contrib.auth.models import User 
from sfi.models import Employee 
import base64, hashlib 

class SFIUserBackend(ModelBackend): 
    def authenticate(self, username=None, password=None): 
     if not username or not password: 
      return 

     digest = base64.standard_b64encode(hashlib.md5(password).digest()) 
     user = None 
     try: 
      employee = Employee.objects.get(login=username, passwd=digest) 
      user, created = User.objects.get_or_create(username=username) 
      if created: 
       # setting attributes 
       user.first_name = employee.names[:30] 
       user.last_name = employee.surnames[:30] 
       user.is_staff = True 
       user.save() 
     except Employee.DoesNotExist: 
      pass 

     return user 

到目前爲止,它工作正常。但是,我需要在模板中讀取當前記錄的用戶的後端類。

使用request.user.backenduser沒有屬性的後端...和(使用request.session._auth_user_backend),因爲Django的模板系統抱怨「和屬性的變量可能與下劃線開頭」我無法從會話讀取它。

我正在使用django.contrib.auth.views.login來允許用戶登錄。我錯過了什麼?

+0

btw此認證方案看起來真的不安全。 – mak 2015-02-08 19:24:00

回答

0

您應該在視圖中閱讀它,並將該類名稱的適當人體形式作爲消息發送。當用戶認證使用django.contrib.auth.authenticate(username='foo',password='bar')函數

3

backend屬性被添加到user對象。

該功能反過來會調用您在settings.py文件中指定的所有AUTHENTICATION_BACKENDS,直到它能夠使用其中一個文件成功進行驗證。

如果您的用戶「已登錄」,但沒有backend屬性,可能意味着您沒有正確驗證它們。也許你直接打電話給你的SFIUserBackend.authenticate函數,當你應該調用django.contrib.auth.authenticate函數?

查看這些custom authentication docs