Rails 3.2 current_password身份验证失败

时间:2012-02-12 11:07:36

标签: ruby-on-rails authentication bcrypt change-password

使用Ruby 1.9.3和bcrypt-ruby 3.0.1

我正在使用Agile Web Development书中的Depot应用程序,我在验证用户当前密码时遇到问题,以便他们更改密码。

我的用户型号:

class User < ActiveRecord::Base
  validates :name, presence: true, uniqueness: true
  attr_accessible :name, :password, :current_password, :password_confirmation
  has_secure_password

  after_destroy :ensure_an_admin_remains

  private
    def ensure_an_admin_remains
      if User.count.zero?
        raise "Can't delete last user"
      end
    end
end

用户控制器中的我的更新方法如下所示:

  def update
    @user = User.find(params[:id])
    if @user.authenticate(params[:current_password])
      params[:user].delete :current_password
      respond_to do |format|
        if @user.update_attributes(params[:user])
          format.html { redirect_to users_url, notice: "User #{@user.name} was successfully updated." }
          format.json { head :no_content }
        else
          format.html { render action: "edit" }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      end
    else
      redirect_to edit_user_path(@user), notice: "Current password is incorrect."
    end
  end

我的用户表单如下所示:

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
      <ul>
      <% @user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

    <fieldset>
        <legend>Enter User Details</legend>
        <div>
        <%= f.label :name %><br />
        <%= f.text_field :name, size: 40 %>
      </div>
        <% if params[:action] == :edit %>
            <div>
                <label for="old_password">Old Password:</label>
                <%= password_field_tag :current_password, params[:current_password]%>
            </div>
        <% end %>
        <div>
        <%= f.label :password, 'Password' %><br />
        <%= f.password_field :password, size: 40 %>
      </div>
        <div>
            <%= f.label :password_confirmation, 'Confirm' %>
            <%= f.password_field :password_confirmation, size: 40%>
        </div>
      <div>
        <%= f.submit %>
      </div>
    </fieldset>
<% end %>

问题似乎与@user.authenticate(params[:current_password])行有关。 我很困惑,因为我认为身份验证在param的范围内,并且因为控制台上的这个方法确实通过了。

1 个答案:

答案 0 :(得分:1)

我认为它应该是if @user.authenticate(params[:user][:current_password])