允许不活动的用户通过自定义Django后端登录 [英] Allowing inactive users to login via custom django backend

查看:50
本文介绍了允许不活动的用户通过自定义Django后端登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a custom auth backend that I'm playing with. I want to allow inactive users to log in. Setting the supports_inactive_user flag to true doesn't seem to do the trick, even though I can verify that the user is being returned.

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.我想念什么?

I'm using django 1.4. What am I missing?

推荐答案

您的用户已成功通过身份验证,但这是

Your user gets authenticated successfully, but it's the AuthenticationForm that raises a ValidationError when the user is inactive. You can override the clean method in a subclass to catch the corresponding 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 .如果您希望用户能够在创建帐户后立即登录,则有更好的方法来实现.

However, consider that a user's is_active flag is a replacement for actually deleting the user. You might want to reconsider your use of is_active. If you want users to be able to login as soon as they've created an account, there are better ways to achieve that.

这篇关于允许不活动的用户通过自定义Django后端登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆