【问题标题】:Django authenticate by emailDjango 通过电子邮件进行身份验证
【发布时间】:2016-05-05 11:23:06
【问题描述】:

我在文件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 只有当我尝试使用用户名和密码登录时,如果我使用电子邮件和密码,控制台中没有输出。看起来我的自定义身份验证在标准方法之后启动......

谁能告诉我哪里出错了?

【问题讨论】:

    标签: python django django-authentication


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-25
      • 2012-08-10
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 2018-02-12
      • 1970-01-01
      • 2011-12-08
      相关资源
      最近更新 更多