A
A
Abdulla Mursalov2016-04-25 17:29:55
Django
Abdulla Mursalov, 2016-04-25 17:29:55

Django User.check_password() - what is causing the strange behavior?

Hello!
Custom Method REST API

class UserViewSet(viewsets.ModelViewSet):
    ...
    ...
    @detail_route(methods=['POST'], permission_classes=[IsAuthenticated])
    def set_password(self, request, pk=None):
        user = self.get_object()
        serializer = user_serializers.SetPasswordSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            user.set_password(serializer.data['new_password'])
            user.save()
            if user.check_password(serializer.data['new_password']):
                return Response({'status': 'success'}, status=status.HTTP_200_OK)
            else:
                return Response({'status': 'error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Testing this:
class SetPasswordAPITest(APITestCase):
    def setUp(self):
        self.superuser = create_superuser()

    def test_set_password(self):
        user = create_user_test1()
        data = {
            'current_password': 'test1',
            'new_password': 'updatedPassword',
            're_new_password': 'updatedPassword'
        }
        self.client.login(username='test1', password='test1')
        response = self.client.post(reverse('user-set-password', args=[user.id]), data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(user.check_password('updatedPassword'))

The response from the server is 200, that is, check_password in the view returns True, but in the test the method returns False.
I’ll make a reservation right away that the user model is custom, if necessary I’ll lay it out

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rostislav Grigoriev, 2016-04-25
@amaprograma

The check is carried out with an old instance, it needs to be updated

updated_user = User.objects.get(pk=user.pk)
self.assertTrue(updated_user.check_password('updatedPassword'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question