重定義django
的認(rèn)證登錄
django
提供了用戶認(rèn)證功能嗦锐,即驗(yàn)證用戶名以及密碼是否正確,一般需要username
、password
兩個(gè)關(guān)鍵字參數(shù)扰法。
如果認(rèn)證成功(用戶名和密碼正確有效),便會(huì)返回一個(gè) User 對(duì)象衅鹿。
authenticate()會(huì)在該 User 對(duì)象上設(shè)置一個(gè)屬性來(lái)標(biāo)識(shí)后端已經(jīng)認(rèn)證了該用戶撒踪,且該信息在后續(xù)的登錄過(guò)程中是需要的
user = authenticate(username='theuser',password='thepassword')
但是存在一些缺陷,只能是使用username
進(jìn)行驗(yàn)證大渤,這不太符合我們的需求制妄,我們希望可以同時(shí)使用email
或username
等進(jìn)行驗(yàn)證
首先在views.py
中我們需要重寫(xiě)authenticate
方法
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import UserProfile
class CustomBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
try:
user = UserProfile.objects.get(Q(username=username) | Q(email=username))
if user.check_password(password):
return user
except Exception as e:
return None
在settings.py
中配置
AUTHENTICATION_BACKENDS = (
'users.views.CustomBackend',
)