0

我有一个正在使用的自定义身份验证后端。我想允许非活动用户登录。将supports_inactive_user标志设置为 true 似乎并没有解决问题,即使我可以验证是否user正在返回。

class AuthenticationBackend(ModelBackend):

    supports_object_permissions = False
    supports_anonymous_user = True
    supports_inactive_user = True

    def authenticate(self, username=None, password=None):
        """
        Allow login with email inplace of username

        """
        user = None
        if username is not None:
            username = username.strip()

        if email_re.search(username):
            try:
                user = User.objects.get(email__iexact=username)
            except User.DoesNotExist:
                pass

        if not user:
            try:
                user = User.objects.get(username__iexact=username)
            except User.DoesNotExist:
                return None

        if user.check_password(password):
            return user

    def get_user(self, user_id):

        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

我正在使用 django 1.4。我错过了什么?

4

1 回答 1

2

您的用户已成功通过身份验证,但是当用户处于非活动状态时AuthenticationForm会引发 a 。ValidationError您可以覆盖子类中的 clean 方法以捕获相应的ValidationError

class InactiveAuthenticationForm(AuthenticationForm):
    # a bit messy but it should work
    def clean(self):
        try:
            return super(InactiveAuthenticationForm, self).clean()
        except ValidationError as e:
            if self.cached_user is not None: # user exists but is not active
                # behavior that's skipped because of the validation error
                self.check_for_test_cookie()
                return self.cleaned_data
            else:
                raise e

但是,考虑到用户的is_active标志是实际删除用户的替代品。您可能需要重新考虑使用is_active. 如果您希望用户能够在创建帐户后立即登录,那么有更好的方法可以实现这一目标。

于 2013-08-13T12:41:22.027 回答