仅在更改密码设置注册时需要密码

时间:2017-04-04 20:06:31

标签: ruby-on-rails ruby devise

我有一个注册/编辑表单,通过我的应用程序中的Devise::RegistrationsController呈现。它的工作方式现在,您必须在对表单进行任何更新时提供当前密码。他们希望它工作的方式是current_password仅在您更新password字段时才需要...或者您必须重复" new_password"作为确认的手段。我在Devise Wiki上做了一些阅读,主要是以下链接,他们似乎没有为此列出解决方案。如果有人对如何实现这一点有一些了解,我将不胜感激。

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-password

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password

3 个答案:

答案 0 :(得分:4)

所以我一直在努力解决这个问题,我找到了解决办法。

在我的模型(user.rb)中,我将:validatable添加到以下代码段中:

  devise :omniauthable, :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable,
     :confirmable, :trackable, reset_password_keys:[:email, :company_id],
     request_keys: [:host, :params], omniauth_providers: [:auth0]

然后在我的注册控制器中,我添加了以下内容:

def update_resource(resource, params)
  if !params[:password].blank?
    resource.password = params[:password]
    resource.password_confirmation = params[:password_confirmation]
  end

  resource.update_without_password(params)
end

最后在我的应用程序控制器中,我将:password_confirmation添加到以下代码段:

devise_parameter_sanitizer.permit(:account_update) do |u|
  u.permit(:first_name, :last_name, :email, :password, :password_confirmation, :phone_number, :receive_emails,
           location_attributes: [:id, :street, :city, :state, :zip, :country])
end

使用此组合,一旦表单提交,它将落入我已覆盖的update_resource块中。它会检查以确保resource.passwordpassword_confirmation相同。最重要的是,current_password不在等式中,您不必每次都输入密码来保存更改。

答案 1 :(得分:2)

您可以做的是在用户对其帐户进行更新时通过参数params[:user][:password]params[:user][:password_confirmation]进行验证:

这种方式如果没有password也不password_confirmation,那么使用传递update_without_password的{​​{1}}方法,另一种方法就是使用user_params方法

update_attributes

答案 2 :(得分:0)

在app / controllers / registrations_controller.rb中创建注册控制器

class RegistrationsController < Devise::RegistrationsController

  protected

  def update_resource(resource, params)
    # Require current password if user is trying to change password.
    return super if params["password"]&.present?

    # Allows user to update registration information without password.
    resource.update_without_password(params.except("current_password"))
  end
end

相关问题