2013-11-04 87 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