Django auth自定义业务逻辑 - 如何引发自定义错误消息?

时间:2015-11-13 13:46:24

标签: python django authentication

所以我使用的是django.contrib.auth模块。 我的业务逻辑是:用户具有状态字段,即PENDING,ACTIVE或DISABLED( is_active 字段不足以满足我的需求)

我像这样覆盖了auth后端:

from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from app import constants

class ModelBackend(object):
  """
  Authenticates against settings.AUTH_USER_MODEL.
  """

  def authenticate(self, username=None, password=None, **kwargs):
    UserModel = get_user_model()
    if username is None:
      username = kwargs.get(UserModel.USERNAME_FIELD)
    try:
      user = UserModel._default_manager.get_by_natural_key(username)

      if not user.status == constants.ACCOUNT_STATUS['ACTIVE']:
        return None # This is where I prevent pending users to log in.

      if user.check_password(password):
        return user
    except UserModel.DoesNotExist:
      # Run the default password hasher once to reduce the timing
      # difference between an existing and a non-existing user (#20760).
      UserModel().set_password(password)

目前,我可以阻止待定用户登录,但我无法找到显示自定义错误消息的方法。目前的错误是:

  

无法使用提供的凭据登录。

此外,这可能与我的问题无关,但可能有用:我正在使用Django Rest Framework和JWT。所以我没有使用Django表单,所有都是通过ajax调用执行的,并且对登录请求的响应以下列格式呈现为json:

{
    "non_field_errors": [
        "Unable to login with provided credentials."
    ]
}

所以我想"注射"我的自定义错误消息进入" non_field_errors"。类似于:"请在登录前激活您的帐户"。

有什么想法吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

如果你深入了解django-rest-framework-jwt,你会发现在JSONWebTokenSerializer(https://github.com/GetBlimp/django-rest-framework-jwt/blob/f07772769c0f72f971daefe1d9426a90ea099a63/rest_framework_jwt/serializers.py#L66)中设置了“无法登录...”。由于此消息是硬编码的,因此您无法简单地注入自己的消息。

要覆盖它,您需要:

  1. 基于JSONWebTokenSerializer创建自己的序列化程序 覆盖它的验证方法记录您的需求(改变 例如错误消息)
  2. 根据默认的ObtainJSONWebToken视图(https://github.com/GetBlimp/django-rest-framework-jwt/blob/f07772769c0f72f971daefe1d9426a90ea099a63/rest_framework_jwt/views.py#L69)创建自定义api视图,并将serializer_class属性更改为您的自定义webtoken序列化程序。
  3. 在urls.py中使用自定义API视图,而不是默认值。