check_password即使密码正确也总是返回false?

时间:2013-03-20 05:40:44

标签: django django-authentication

我正在使用Django 1.5。我是这样的自定义用户模型:

class User(AbstractBaseUser):
    #id = models.IntegerField(primary_key=True)
    #identifier = models.CharField(max_length=40, unique=True, db_index=True)
    username = models.CharField(max_length=90, unique=True, db_index=True)
    create_time = models.DateTimeField(null=True, blank=True)
    update_time = models.DateTimeField(null=True, blank=True)
    email = models.CharField(max_length=225)
    #password = models.CharField(max_length=120)
    external = models.IntegerField(null=True, blank=True)
    deleted = models.IntegerField(null=True, blank=True)
    purged = models.IntegerField(null=True, blank=True)
    form_values_id = models.IntegerField(null=True, blank=True)
    disk_usage = models.DecimalField(null=True, max_digits=16, decimal_places=0, blank=True)
    objects = UserManager()
    USERNAME_FIELD = 'email'
    class Meta:
        db_table = u'galaxy_user'

我有自定义身份验证:

class AuthBackend:

def authenticate(self, username=None, password=None):
    if '@' in username:
        kwargs = {'email': username}
    else:
        kwargs = {'username': username}
    try:
        user = User.objects.get(**kwargs)
        if user.check_password(password):
            return user
    except User.DoesNotExist:
        return None

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

即使输入了正确的用户名和密码,check_password()也总是返回false,这样我就无法登录。我也在终端试过了:

user.check_password(password)

始终返回False.

#views.py:

def login_backend(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        state = "Username or Password Incorrect!"
        if user is not None:
            login(request, user)
            return HttpResponseRedirect('/overview/')
        else:
            return render_to_response('login_backend.html', {'state':state}, context_instance=RequestContext(request))
    else:
        return render_to_response('login_backend.html', context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:3)

问题是,当您创建CustomUser时,您将以开放方式保存密码(无哈希)。你能给我你的RegistrationForm代码吗?

在我的情况下:

# forms/register.py
class RegistrationForm(forms.ModelForm):
    """
    Form for registering a new account.
    """
    class Meta:
        model = CustomUser
        fields = ['username', 'password', 'email']

注册处理程序:

# views.py
def register(request):
    """
    User registration view.
    """
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            user = form.save() # Save your password as a simple String
            return redirect('/')
    else:
        form = RegistrationForm()
    return render(request, 'news/register.html', {'form': form})

所以当你尝试登录时:

if user.check_password(password):
    return user

check_password 始终返回False。


<强>解决方案: 要正确设置设置密码,您应该在RegistrationForm中重新定义save()方法:

# forms/register.py
class RegistrationForm(forms.ModelForm):
    """
    Form for registering a new account.
    """
    class Meta:
        model = CustomUser
        fields = ['username', 'password', 'email']

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password(user.password) # set password properly before commit
        if commit:
            user.save()
        return user

只需更改处理程序:

def register(request):
    """
    User registration view.
    """
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(request.POST["password"])
            user.save()
            return redirect('/')
    else:
        form = RegistrationForm()
    return render(request, 'news/register.html', {'form': form})

http://www.blackglasses.me/2013/09/17/custom-django-user-model/

了解详情

http://www.blackglasses.me/2013/10/08/custom-django-user-model-part-2/