0

ユーザーが古いパスワードを知っている場合にのみパスワードを更新できるようにしたいと考えています。現在、ユーザーが古いパスを確認せずにパスワードを更新できるようにしています。正しい方向に私を向けることができますか。

現在のユーザーの更新方法:

def update
  if params[:user][:password] 
    if current_user
      @user = User.find(params[:id])
      if @user.update_attributes(params[:user])
        redirect_to root_url, :notice => "Password has been changed!"
      else
        render "edit" 
      end
    else
      # Something else
    end
  end 
end

(HAML) 現在の形式:

= form_for @user do |f|  
  - if @user.errors.any?
    - for message in @user.errors.full_messages
      = message
  .form
    = f.password_field :password
    = f.password_field :password_confirmation
    %input{name: "commit", type: "submit", value: "SAVE CHANGES"}
4

2 に答える 2

1

Devise gemから着想を得たテクニックを使用しています。

アプリ/コントローラー/users_controller.rb:

def update
  @user.update_with_password(user_params)
  ...
end

アプリ/モデル/user.rb:

class User < ActiveRecord::Base
  cattr_reader :current_password

  def update_with_password(user_params)
    current_password = user_params.delete(:current_password)

    if self.authenticate(current_password)
      self.update(user_params)
      true
    else
      self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
      false
    end
  end
end

これにより、現在のパスワードが欠落しているか正しくない場合に検証エラーが設定されます。

注:認証方法に has_secure_password を使用していますが、好きなように変更できます。

于 2013-11-04T13:13:27.197 に答える