Django通过电子邮件进行身份验证

时间:2016-05-05 11:23:06

标签: python django django-authentication

我在文件project/emailauth.py中编写了我自己的身份验证后端,内容为:

from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User

class EmailBackend(object):
    def authenticate(self, username=None, password=None):
        print("Email auth")
        try:
            user = User._default_manager.get(email=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None
        except:
            return None

    def get_user(self, user_id):
        try:
            return User._default_manager.get(pk=user_id)
        except User.DoesNotExist:
            return None

在文件末尾的project/settings.py我添加了内容:

AUTHENTICATION_BACKENDS = (
    'project.emailauth.EmailBackend',
    'django.contrib.auth.backends.ModelBackend',
)

我在userprofile/views.py中使用了验证方法:

from django.contrib.auth import authenticate, login, logout
#...
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            profile = authenticate(username=username, password=password)
            if profile is not None:
                login(request, profile)
                return HttpResponseRedirect(redirect_to)
#...

最有趣的是我注意到控制台输出Email auth只有当我尝试使用用户名和密码登录时,如果我使用电子邮件和密码,则控制台中没有输出。看起来我的自定义身份验证在标准方法后启动...

有人能告诉我我犯了哪个错误吗?

1 个答案:

答案 0 :(得分:0)

原来我的表单验证阻止通过电子邮件登录(因为它在尝试验证之前检查用户是否存在于数据库中)

相关问题