简体   繁体   中英

Manual Update password Rails Devise

I have an API based Rails app and I need to add a changing password section for clients after login. this is y codes so far:

# 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

And this is XHR request from client-side

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);
          });

Its not working!

You should be able to use current_user. I edited the code. If it doesn't work, can you write the error here? Make sure the post request goes to update_password action.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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