2013-11-04 89 views
0

我想讓用戶只有在知道他們的舊密碼後才能更新他們的密碼。目前,我允許用戶在不檢查舊通行證的情況下更新其密碼。你能爲我指出正確的方向嗎。Rails:更新密碼

當前用戶更新方法:

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"} 
+1

你有什麼試過?另外,忘記舊密碼的用戶會發生什麼情況? –

+0

^還有另一種選擇,但我在此將它從更新控制器中刪除。我現在試圖找出獨奏。 –

回答

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 
1

我使用靈感來自Devise寶石的技術。

應用程序/控制器/ 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進行身份驗證方法,但您可以將其更改爲任何您喜歡的方式。

+0

如果'self.update(user_params)'失敗,該方法仍然返回「true」。因此,不應該返回'true',而應該返回'self.update(user_params)'的響應。 – Timo