brno32
brno32

Reputation: 424

check_password() returning False

I have made a model with its own password field. This is wholly separate from the User object. I'm using the django.contrib.auth.hashers library for this.

In the create method for this model (overwriting a generic CreateListAPI view)

def create(self, request, *args, **kwargs):
        data = request.data
        data['password'] = make_password(data['password'])
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

This stores a hashed password in my database as expected, but when I try to authenticate with the password

def get_object(self):
    queryset = self.filter_queryset(self.get_queryset())

    try:
        # Grabs the 'name' parameter from the URL
        obj = queryset.get(name=self.kwargs['name'])
    except Group.DoesNotExist:
        raise Http404

    print(self.request.data['password'])  # raw password string
    print(obj.password)  # encoded password from database
    if check_password(self.request.data['password']), obj.password):
        raise Http404

    obj.user_set.add(self.request.user)

    self.check_object_permissions(self.request, obj)
    return obj

check_password returns False. However, passing in the encoded password as the raw string password works. So hashing the password works, but not comparing the raw password to it after the fact.

Upvotes: 0

Views: 1157

Answers (1)

Exprator
Exprator

Reputation: 27503

if not check_password(self.request.data['password'], obj.password):
        raise Http404

change the line to the above code

Upvotes: 1

Related Questions