【问题标题】:Django authentication backend returning multiple status valuesDjango 身份验证后端返回多个状态值
【发布时间】:2012-11-07 19:54:39
【问题描述】:

我正在编写自定义身份验证后端(和自定义用户模型)来检查用户帐户是否被锁定或过期。我看到,在所有身份验证后端返回值的示例中,要么是用户对象,要么是无。生成的唯一异常是 User.DoesNotExist。

我的问题是我应该如何返回不同的结果(例如帐户被锁定或过期或已达到最大登录尝试次数)?

我应该引发自定义异常还是有其他方法可以做到这一点?

我正在使用 Django 1.5alpha。

编辑: 我需要获取多个状态以向用户显示适当的消息并重定向到适当的视图。

【问题讨论】:

    标签: django authentication login custom-backend


    【解决方案1】:

    如文档中所述:

    无论哪种方式,authenticate 都应该检查它获得的凭据,如果凭据有效,它应该返回一个与这些凭据匹配的用户对象。如果它们无效,它应该返回 None。

    被锁定、过期或已达到其最大登录尝试次数的帐户将被视为“无效”,因此应针对这些情况返回 None

    基本上,只要登录被拒绝访问(无论出于何种原因),都应该返回None

    【讨论】:

    • 谢谢。知道这很有帮助。但是我仍然需要 Authenticate 方法的多个状态来显示适当的消息和视图。我用这些信息编辑了我的问题。
    【解决方案2】:

    如果有人有同样的问题,我最终会这样做。

    class UserNotActivatedError(Exception):
        pass
    
    class UserLockedError(Exception):
        def __init__(self, remaining_mins):
            self.remaining_mins = remaining_mins
    
    # backend
    def authenticate(self, email=None, password=None):
        if email is None or password is None:
            return None
        try:
            user = ExtUser.objects.get(email=email)
            user.last_login_attempt_at = timezone.now()
            if not use.is_active:
                raise UserNotActivatedError
            if user.is_locked:
                # Check when it was locked and found the duration
                sec_to_go = user.get_remaining_locktime()
                if sec_to_go:
                    raise UserLockedError(sec_to_go)
            if user.check_password(password):
                user.last_login_at = timezone.now() 
                return user
            else:
                return None
        except User.DoesNotExist:
            return None
    

    然后在登录表单中,您可以捕获这些错误并将适当的验证错误传递给视图。

    【讨论】:

      猜你喜欢
      • 2013-04-13
      • 2018-03-28
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      • 2013-06-08
      • 2018-12-31
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多