【问题标题】:Let user update their password without current password in devise让用户在没有当前密码的情况下更新他们的密码
【发布时间】:2015-05-07 15:12:33
【问题描述】:

我在 Rails 4.2.1 并设计 3.4.1。我基本上同时想要两件事:

Allow users to edit their password

Allow users to edit their account without providing a password

我设法让他们分开工作。但是第一个问题的解决方案 1 恐怕与第二个问题的唯一官方解决方案不兼容,因为对于后者,我需要覆盖 registration em>控制器。

因此我尝试在 registration 控制器而不是 application 控制器中执行 solution 1 工作:

class Users::RegistrationsController < Devise::RegistrationsController
  before_filter :configure_account_update_params, only: [:update]

  protected

  def configure_account_update_params
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :password, :password_confirmation, :current_password) }
  end

  def update_resource(resource, params)
    resource.update_without_password(params)
  end

end

这种方式只有像 name 这样添加的属性会在密码被完全过滤掉的情况下得到更新。 我不确定我是否应该像 解决方案 2 和 3 中那样为这样一个简单的目标开始大量定制。我错过了什么吗?

【问题讨论】:

    标签: ruby-on-rails devise


    【解决方案1】:

    将此添加到您的registrations_controller

    def update_resource(resource, params)
      resource.update_without_password(params)
    end
    

    并在您的用户模型或使用 Devise 的模型上覆盖 update_withour_password 方法:

    def update_without_password(params, *options)
      if params[:password].blank?
        params.delete(:password)
        params.delete(:password_confirmation) if params[:password_confirmation].blank?
      end
    
      result = update_attributes(params, *options)
      clean_up_passwords
      result
    end
    

    官方文档/代码 - database_authenticatable

    【讨论】:

      【解决方案2】:

      在挖掘设计代码后,我发现update_without_password 故意删除了:password:password_confirmation 参数。出于安全原因,默认情况下会这样做。

      所以(可能有风险的)解决方案是在我的资源模型中覆盖 update_without_password,但不删除 passwords* 参数

      【讨论】:

      • 这对我也有帮助。我不确定在覆盖 update_without_password 时不删除密码参数是否有任何危害,除非我实际上需要使用 update_without_password 来更新没有密码的任何其他帐户详细信息时最终会遇到问题。想过吗?
      【解决方案3】:

      最新的 rails 6 解决方案:

        def update_resource(resource, params)
          resource.update(params)
        end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-14
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 2013-03-29
        • 1970-01-01
        相关资源
        最近更新 更多