自定义身份验证后端。 Django的 [英] Custom authentication backend. Django
问题描述
我想创建一个身份验证后端,该后端仅允许用户使用电子邮件登录(无用户名,无密码)。
这是我尝试过的。 / p>
backends.py:
来自django.conf导入设置$ b来自django.contrib.auth.models的$ b导入用户
类EmailAuthBackend(object):
def authenticate(self,username = None,password = None):
试试:
用户= User.objects.get(电子邮件=用户名)
如果用户:
返回用户
,但User.DoesNotExist除外:
返回None
settings.py:
AUTHENTICATION_BACKENDS =(
'path_to.backends.EmailAuthBackend',
'django.contrib.auth.backends.ModelBackend',
)
html:
< form method = post action = {%url myproject.views.test%}>
{%csrf_token%}
<输入类型= text name =电子邮件 value = />
< button type = submit> Valider< / button>
< / form>
视图:
def test(request):
email =''
如果请求中有'email'.POST:
email = request.POST.get('email')
如果不是User.objects.filter(email = email):
User.objects.create(email = email)
user = authenticate(username = email)
如果user不为None :
if user.is_active:
auth_login(请求,用户)
return HttpResponseRedirect(reverse('home'))
它不起作用,用户未通过身份验证。而且,当我转到/ admin时,也会遇到此错误:
AttributeError在/ admin / logout /
' EmailAuthBackend'对象没有属性'get_user'
自定义后端,您需要指定 get_user
函数。请参阅文档。 get_user
实现可以简单地使用现有的User表,就像您这样:
def get_user(self,user_id):
尝试:
返回User.objects.get(pk = user_id)
除了User.DoesNotExist:
返回None
之所以需要这样做,是因为在某些情况下,您需要通过用户主键从其他来源获取用户
I would like to create an authentication backend that allows users to log_in only using their email (no username, no password).
Here is what I tried.
backends.py:
from django.conf import settings
from django.contrib.auth.models import User
class EmailAuthBackend(object):
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(email=username)
if user:
return user
except User.DoesNotExist:
return None
settings.py:
AUTHENTICATION_BACKENDS = (
'path_to.backends.EmailAuthBackend',
'django.contrib.auth.backends.ModelBackend',
)
html:
<form method="post" action="{% url myproject.views.test %}">
{% csrf_token %}
<input type="text" name="email" value=""/>
<button type="submit">Valider</button>
</form>
view:
def test(request):
email = ''
if 'email' in request.POST:
email = request.POST.get('email')
if not User.objects.filter(email=email):
User.objects.create(email=email)
user = authenticate(username=email)
if user is not None:
if user.is_active:
auth_login(request, user)
return HttpResponseRedirect(reverse('home'))
It doesn't work, the user is not authenticated. And I also have this error when I go to the /admin:
AttributeError at /admin/logout/
'EmailAuthBackend' object has no attribute 'get_user'
For each custom backend in Django, you need to specify the get_user
function. See the documentation. The get_user
implementation can simply use the existing User table, like you are:
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
The reason this is required is for situations where you'd need to fetch the User via its primary key from a different source.
这篇关于自定义身份验证后端。 Django的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!