簡體   English   中英

Django:如何覆蓋authenticate()方法?

[英]Django: How to override authenticate() method?

我使用自定義User ,並且有該用戶的email_verified字段。 我希望用戶登錄時被拒絕(如果此字段為false

我無法在views.py執行此操作,因為用戶可以從各種來源(Django站點,但也包括REST API)登錄。 整個目的是避免為源代碼中的N個符號編寫N倍的邏輯。 我想重寫models.py中的方法( login()authenticate() ?),使其僅執行一次。

我快速閱讀了有關自定義身份驗證的文檔,但是沒有找到我想要的東西。

感謝幫助。

請參考Django Doc: 編寫身份驗證后端 ,可能正是您所追求的。 它涵蓋了您在常規登錄和REST API(如令牌身份驗證)上的用例:

 The authenticate method takes credentials as keyword arguments. Most of the time, it'll just look like this: class MyBackend(object): def authenticate(self, username=None, password=None): # Check the username/password and return a User. ... But it could also authenticate a token, like so: class MyBackend(object): def authenticate(self, token=None): # Check the token and return a User. ... Either way, authenticate should check the credentials it gets, and it should return a User object that matches those credentials, if the credentials are valid. If they're not valid, it should return None. 

編寫自定義身份驗證后端后,只需在settings.py更改默認身份驗證后端,如下所示:

AUTHENTICATION_BACKENDS = ('project.path.to.MyBackend',)

更新資料

可以覆蓋設置中的兩個后端,而不是覆蓋默認的authenticate行為,例如:

AUTHENTICATION_BACKENDS = ('project.path.to.MyBackend',
                           'django.contrib.auth.backends.ModelBackend',)

后端的順序很重要,您可以閱讀源代碼並更好地了解默認authenticate和事物如何協同工作(請參閱此處

AFAIK這是自定義authenticate的首選方法,因為您可能有一天可以將默認后端更改為RemoteUserBackend之類的內容(例如RestFramework中的內容),因此您只需按順序在設置中放置邏輯(MyBackend),而無需擔心破壞代碼。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM