使用 devise 更新密码后完成 401 Unauthorized

Completed 401 Unauthorized after updating password with devise

当我尝试更新我的用户密码时:

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

更新正常进行,但随后我注销了。我想在这次更新后保持日志。

我使用 devise 中的 update with password 方法。

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

查看代码:

  = 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') }

将您的 update 操作更改为类似这样的内容

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

编辑:

Devise 会在更新密码时自动注销,因此我们无法避免这种情况,相反我们会再次登录用户并绕过 warder 回调。