繁体   English   中英

Devise 和 jwt - 可恢复的 reset_password_by_token

[英]Devise with jwt - recoverable reset_password_by_token

我正在使用 Rails API,它将通过 jwt 进行身份验证,并希望用户帐户可以恢复。 据推测,在 email 收到他们的重置令牌后,用户将提供他们的新密码和带有 PUT 的令牌到https://example.com/users/password ,由/app/controllers/users/passwords_controller#update处理。 目前我在passwords_controller.rb中得到了这个(主要是默认的 Devise 代码):

  # PUT /resource/password
  def update
    # {"user": {"password": "secret", "password_confirmation": "secret", "reset_password_token": "token_goes_here"}}
    self.resource = resource_class.reset_password_by_token(resource_params) # problem here (line 33)...
    yield resource if block_given?

    if resource.errors.empty?
      resource.unlock_access! if unlockable?(resource)
      if Devise.sign_in_after_reset_password
        resource.after_database_authentication
        auth_options = {user: {login: resource.username, password: params['user']['password']}}
        warden.authenticate!(auth_options)
        render json: {success: true, jwt: current_token, response: "Authentication successful" }
      else
        render json: {success: false, response: "Authentication failed" }
      end
    else
      set_minimum_password_length
      respond_with resource
    end
  end

问题是reset_password_by_token正在请求授权:

 app/controllers/users/passwords_controller.rb:33:in `update'
Completed 401 Unauthorized in 220ms (ActiveRecord: 60.8ms | Allocations: 6810)

这对我来说似乎很奇怪,因为我希望用户能够使用令牌(除非已过期)登录一次以更改密码。 那时我想返回 jwt(因此使用warden.authenticate ),以便前端应用程序可以立即使用它来让用户登录。

谁能在这里指出我正确的方向?

从概念上讲,将Rails用作API提供程序时,重置密码功能的流程如下:

  • 用户单击前端上的重置密码链接。 前端对POST / auth / password进行API调用,该API向用户发送电子邮件。
  • 链接(来自用户邮箱)将用户带到服务器( GET / auth / password / edit ),在该服务器上验证令牌,然后服务器会将用户重定向到查询参数中带有令牌的前端网址。
  • 前端使用该令牌使用参数passwordpassword_confirmationPUT / auth / password进行API调用,以设置新密码。

由于评论中要求最终结果,这里是:

  # PUT /resource/password
  def update
    resource = resource_class.reset_password_by_token(resource_params)

    if resource.errors.empty?
      resource.unlock_access! if unlockable?(resource)
      if Devise.sign_in_after_reset_password
        resource.after_database_authentication
        resource.skip_confirmation!  # Added in case user account shows as unconfirmed...
        sign_in(resource_name, resource)
        render json: {success: true, message: "Password reset successful." }
      else
        respond_with resource
      end
    else
      set_minimum_password_length
      respond_with resource
    end

  end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM