rest_framework.authtoken刷新更改密码

时间:2019-01-06 20:39:03

标签: django django-rest-framework django-authentication http-token-authentication

我已成功(希望)成功实施了change_password操作。

但是,更改密码后,客户端会自动注销。 (令牌可能不再有效)

我希望在重置密码以使用新令牌发出其他请求之后,API客户端仍保持登录状态。

是否有与 update_session_auth_hash(请求,self.object)等效的对象?

序列化器:

class PasswordSerializer(serializers.Serializer):
    """
    Serializer for password change endpoint.
    """
    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True)

API视图

    @action(methods=['put'], detail=True)
    def change_password(self, request, pk):
        serializer = PasswordSerializer(data=request.data)
        if serializer.is_valid():
            user = get_object_or_404(User, pk=pk)
            if user != request.user:
                return Response({'error': "Cannot change other user's password"},
                                status=status.HTTP_403_FORBIDDEN)
            else:
                if not user.check_password(serializer.data.get('old_password')):
                    return Response({'old_password': ['Wrong password.']},
                                    status=status.HTTP_400_BAD_REQUEST)
                user.set_password(request.POST.get('new_password'))
                user.save()
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
        return Response({'details': 'Success'}, status=status.HTTP_200_OK)

1 个答案:

答案 0 :(得分:0)

成功更改密码后,您可以用新令牌代替。

token, created =  Token.objects.get_or_create(user=serializer.object['user'])

token.delete()
token.created = Token.objects.create(user=serializer.object['user'])
token.save()