2

我正在使用 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))
4

1 回答 1

4

问题是当您创建自定义用户时,您以开放方式保存密码(没有散列)。你能给我你的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/

于 2014-11-30T17:08:35.553 回答