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

在控制器中

@user = User.find(params[:id])
if @user.authenticate(params[:user][:current_password]) &&
    @user.update_attributes(params[:user])
  ...

在用户模型中

def authenticate(password)
  # whatever you have to do to check if the password matches the current password
end
于 2013-11-04T13:03:13.240 回答
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 回答