Rails 3.2 Omniauth Devise - 添加密码 - 跳过当前密码

时间:2012-01-26 17:06:38

标签: ruby-on-rails authentication devise omniauth

我正在使用Omniauth允许用户通过Facebook,Twitter和Google登录(并创建帐户)。

但是,如果用户决定不再使用这些服务,但继续使用他们的帐户,他们会想要添加密码。


如何在不输入current password的情况下让用户为其帐户添加密码?*


当我让用户转到edit_user_registration_path(@user)时,他们会看到以下表单:

= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put, name: 'validation'}) do |f|
  = devise_error_messages!

  = f.label :email, class: 'block'
  = f.email_field :email, class: 'large'
  %span.infobar Keep this here unless you'd like to change your email

  = f.label :password, class: 'block'
  = f.password_field :password, class: 'large'
  %span.infobar Leave blank if you don't want to change it

  = f.label :password_confirmation, class: 'block'
  = f.password_field :password_confirmation, class: 'large'

  - if @user.password_required?
    = f.label :current_password, class: 'block'
    = f.password_field :current_password, class: 'large'
    %span.infobar We need your current password to confirm changes

  = f.submit "Update"

user.rb

def password_required?
  (authentications.empty? || !password.blank?) && super
end

正如您所看到的,我拥有它,以便@user.password_required?,然后显示当前的密码字段。即使尝试为帐户创建新密码时未显示此字段,表单也无法正确验证,因为需要当前密码。

1 个答案:

答案 0 :(得分:3)

我刚刚覆盖了RegistrationsController#update方法:

class RegistrationsController < Devise::RegistrationsController
  def update
    # Override Devise to use update_attributes instead of update_with_password.
    # This is the only change we make.
    if resource.update_attributes(params[resource_name])
      set_flash_message :notice, :updated
      # Line below required if using Devise >= 1.2.0
      sign_in resource_name, resource, :bypass => true
      redirect_to after_update_path_for(resource)
    else
      clean_up_passwords(resource)
      render_with_scope :edit
    end
  end
end

来源:How To: Allow users to edit their account without providing a password