Orsay Orsay - 1 month ago 13
Ruby Question

Completed 401 Unauthorized after updating password with devise

When I try to update the user password I have :



Completed 401 Unauthorized in 3ms (ActiveRecord: 0.6ms)



The update happen properly but then I'm logged out. I would like to stay log after this update.

I use the
update with password
method from devise.

Registrations_controller

def update_password
@user = current_user
authorize @user, :update?
if @user.update_with_password(user_params)
flash[:success] = t 'edit.success'
else
flash[:error] = t 'flash.error_occured'
end
redirect_to edit_user_registration_path + "##{t('users.account.title')}"
end

private

def user_params
params.require(:user).permit(
:current_password, :password, :email, :username )
end


view code:

= form_for @user, url: update_password_path, html: { method: :put, role: 'form'} do |f|
= devise_error_messages!

= f.label t ('password.current')
= f.password_field :current_password, autocomplete: :off

= f.label t('password.new')
= f.password_field :password, autocomplete: :off

= f.submit t('button.change'), data: { disable_with: t('ajaxdoing') }

Answer

change your update action to something like this

def update_password
  @user = current_user
  authorize @user, :update?
  if @user.update_with_password(user_params)
    sign_in(@user, :bypass => true)
    flash[:success] = t 'edit.success'
  else
    flash[:error] = t 'flash.error_occured'
  end
  redirect_to edit_user_registration_path + "##{t('users.account.title')}"
end

EDIT:

Devise logs out automatically when password is updated so we can not escape that, instead we are logging in the user again and bypassing warder callbacks.

Comments