atropa belladona
atropa belladona

Reputation: 524

Unable to set_password using POST request

I'm trying to make a function which can reset user password of OTP matached to the stored value in user model.

I'm able to make a successful post request and JSON response I'm getting

{
    "detail": "Password have been changed"
}

But problem is password in actual dosent change but remains the older one. Can anybody identify what is the problem in my function. My API view is :

@api_view(['POST'])
def reset_password(request):
    data = request.data
    email = data['email']
    otp_to_verify = data['otp']
    new_password = data['password']

    user = User.objects.get(email=email)
    if User.objects.filter(email=email).exists():
        otp_to_verify == user.otp #user model has a field name otp
        if new_password != '':
            # user.set_password(make_password(data['password']))
            user.set_password((data['password'])) #changed to this but dosnt work 
            user.save()
            message = {
                'detail': 'Password have been changed'}
            return Response(message, status=status.HTTP_200_OK)
        else:
            message = {
                'detail': 'Something wrong'}
            return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:
        message = {
            'detail': 'Something went wrong'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)

So I'm not sure what might be the problem as it's passing silently without giving any errors but in the end password does not change.

EDIT: using this method user password hash in database gets changed but unable to login with new password and older password also gets invalid this error comes then .

 Unauthorized: /api/v1/accounts/login/
    [11/Feb/2022 17:44:54] "POST /api/v1/accounts/login/ HTTP/1.1" 401 63
    Not Found: /jwt/refresh-token
    [11/Feb/2022 17:44:54] "POST /jwt/refresh-token HTTP/1.1" 404 2761

Upvotes: 0

Views: 88

Answers (1)

mon io
mon io

Reputation: 752

I think that user.set_password method dont need to use make_password function.

  1. set_password hash plain text password by default

    user.set_password(data['password'])

  2. Using make_password

    user.password = make_password(data['password'])

Upvotes: 2

Related Questions