Update Password Endpoint using Devise in Rails 5.1 API App

Implement the update action in passwords controller.

def update
  user = User.with_reset_password_token(params[:reset_password_token])

  if user&.update(password_params)      
    render json: user, status: :ok
  else
    render json: {error: ['Password update failed']}, status: :internal_server_error
  end
end

private

def password_params
  params.permit(:password)
end

The with_reset_password_token class method is provided by Devise. The reset_password_token is stored in encrypted form so:

User.find_by(reset_password_token: params[:reset_password_token])

will fail to retrieve the record from the database.

Endpoint

HTTP Verb : PUT
URL: users/password
Input: password, resetpasswordtoken

We can send a PUT request using cURL, we need to copy the reset_password_token from the reset password email link from the development log.

curl -X PUT --data "password=secret&reset_password_token=9nXHzCb" http://localhost:3000/users/password

The response for success:

{  
   "data":{  
      "id":"1",
      "type":"users",
      "attributes":{  
         "email":"bugs@rubyplus.com",
         "first-name":"",
         "last-name":"",
         "authentication-token":"mHJJTpcGQpeTaMnZfUNR"
      }
   }
}

I am using the JSON API specification. For failure case:

{  
   "error":[  
      "Password update failed"
   ]
}

In this article, we saw how to update password by customizing Devise in a Rails 5.1 API app.


Related Articles