创建一个自定义的验证

问题描述 投票:3回答:1

我转移数据库到一个新的项目,更精确的用户。不要问我为什么,但在旧数据库中的密码是使用MD5加密,然后用SHA256。

我使用Django的休息-auth的管理登录。

url(r'^api/rest-auth/', include('rest_auth.urls')),

我添加了一个自定义的验证方法:

REST_FRAMEWORK = {
  'DEFAULT_AUTHENTICATION_CLASSES': (
     'users.auth.OldCustomAuthentication',
     'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
  )
}

这是我的身份验证文件:

class OldCustomAuthentication(BaseAuthentication):
    def authenticate(self, request):
        try:
            password = request.POST['password']
            email = request.POST['email']
        except MultiValueDictKeyError:
            return None

        if not password or not email:
            return None

        password = hashlib.md5(password.encode())
        password = hashlib.sha256(password.hexdigest().encode())

        try:
            user = User.objects.get(email=email, password=password.hexdigest())
        except User.DoesNotExist:
            return None

        # User is found every time
        print('FOUND USER', user)
        return user, None

但是,当我要求http://apiUrl/rest-auth/login/我还得到一个错误:

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

你有什么主意吗?或者,也许我在一个错误的方式这样做。

先感谢您。

杰里米。

python django python-3.x django-rest-framework django-rest-auth
1个回答
2
投票

@MrName我设法解决我的问题的建议。

所以我删除了我的设置DEFAULT_AUTHENTICATION_CLASSES并添加这样的:

 REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'users.auth.LoginSerializer'
 }

然后,我复制粘贴的original serializer和改良功能_validate_email:

def _validate_email(self, email, password):
    user = None

    if email and password:
        user = self.authenticate(email=email, password=password)

        # TODO: REMOVE ONCE ALL USERS HAVE BEEN TRANSFERED TO THE NEW SYSTEM
        if user is None:
            password_hashed = hashlib.md5(password.encode())
            password_hashed = hashlib.sha256(password_hashed.hexdigest().encode())
            try:
                user = User.objects.get(email=email, password=password_hashed.hexdigest())
            except ObjectDoesNotExist:
                user = None
    else:
        msg = _('Must include "email" and "password".')
        raise exceptions.ValidationError(msg)

    return user
© www.soinside.com 2019 - 2024. All rights reserved.