[英]Manual Update password Rails Devise
我有一個基於API的Rails應用程序,登錄后需要為客戶端添加一個更改密碼部分。 到目前為止,這是您的代碼:
# routes.rb
resources :passwords, only: %i[index]
post '/passwords/update_password', to: 'passwords#update_password'
passwords_controller.rb
class Api::PasswordsController < ApplicationController
respond_to :json
before_action :auth_check
def auth_check
if !user_signed_in?
render json: {:status => false, :msg => 'Access denied!'}
end
end
def update_password
user = User.find(current_user['_id'])
password = params["password"]
if password && !password.blank?
user.password = user.password_confirmation = password
end
if user.save
render json: {company: user}, status: 200
else
render json: {message: "Problem updating company"}, status: 500
end
end
end
這是來自客戶端的XHR請求
axios({
url: '/api/passwords/update_password',
method: 'POST',
body: {
password: password,
password_confirmation: password_confirmation
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
它不起作用!
您應該能夠使用current_user。 我編輯了代碼。 如果不起作用,您可以在這里寫下錯誤嗎? 確保發布請求轉到update_password操作。
class Api::PasswordsController < ApplicationController
respond_to :json
before_action :auth_check
def update_password
password = params.dig(:password)
password_confirmation = params.dig(:password_confirmation)
if password.present? && password == password_confirmation
if current_user.update(password: password, pasword_confirmation: password_confirmation)
render json: { company: user }, status: 200
else
render json: { message: 'Problem updating company' }, status: 500
end
end
end
private
def auth_check
render json: { status: false, msg: 'Access denied!' } unless user_signed_in?
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.