2012-02-12 77 views
0

使用Ruby 1.9.3和bcrypt-紅寶石3.0.1的Rails 3.2 current_password認證失敗

我正在從敏捷Web開發的書倉庫應用程序,我在驗證用戶的當前密碼問題以便他們更改密碼。

我的用戶模型:

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

我覺得應該是if @user.authenticate(params[:user][:current_password])

+0

這與修改表單一起,並獲得成功。而不是上面的current_password字段,我使用rails生成的表單標籤和密碼字段:current_password。 – Ian 2012-02-12 12:17:26