忘记密码Devise gem API

时间:2013-02-12 06:59:02

标签: ruby-on-rails devise

我在我的应用程序中一直使用Devise gem。我能够 配置devise sessions_controller以响应来自web和的请求 来自移动API调用。

但是现在我想看看我如何使用Devise gem的Forgot Password选项 用于移动API调用。我可以使用API​​登录,如下所示

curl -X POST 'http://localhost:3002/users/sign_in.json' -d 'user[email]=balan@test.com&user[password]=123456'

我可以用忘记密码做同样的事吗?

3 个答案:

答案 0 :(得分:20)

得到了答案。

1)创建一个自定义操作,接收email作为输入

2)添加以下代码

@user = User.find_by_email("email@email.com")
if @user.present?
 @user.send_reset_password_instructions
 render :text => "updated"
else
     render :text => "no such email"
end

答案 1 :(得分:2)

我这样做了:

config/routes.rb

namespace :api do
  namespace :v1 do 
     resources :reset_passwords, only: [:index, :create]
  end
end

app/controllers/api/v1/reset_passwords_controller.rb

class Api::V1::ResetPasswordsController < Api::V1::BaseController
   def index
    user = User.find_by_email(user_params)
    if user.present?
     user.send_reset_password_instructions
     render(
          json: "{ \"result\": \"Email already exists\"}",
          status: 201
        )
    else
      render(
          json: "{ \"error\": \"Not found\"}",
          status: 404
        )
    end
  end

  private

  def user_params
    params.require(:email)
  end

end

答案 2 :(得分:1)

devise现在支持它。检查下面的链接 https://github.com/plataformatec/devise/wiki/API-Mode-Compatibility-Guide

密码重置请求(发布)

curl -X POST \
'http://{{protocol}}{{host}}:{{port}}/{{resource_plural}}/password' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-H 'Postman-Token: 406d7e49-7da5-460d-8cc2-1009da8fcb73' \
-H 'cache-control: no-cache' \
-d '{
  "user": {
      "email": "user@example.com"
  }
}'

密码重置确认(补丁)

  curl -X PATCH \
'http://{{protocol}}{{host}}:{{port}}/{{resource_plural}}/password' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-H 'Postman-Token: f68be2db-1b90-4443-be93-3f012ca4c7dc' \
-H 'cache-control: no-cache' \
-d '{
  "user": {
      "reset_password_token": "-96mB4zMSjL4t5N6ozGC",
      "password": "newpassword",
      "password_confirmation": "newpassword"
  }
}'