我正在遵循此解决方案:Rails 4 - Allow password change only if current password is correct
但无论我输入的密码是否正确,我的密码都会更新。这是我的代码:
员工模式:
class Employee < ActiveRecord::Base
attr_accessor :password, :current_password
def self.authenticate(user, password)
employee = find_by_code(user)
if employee && employee.password_hash == BCrypt::Engine.hash_secret(password, employee.password_salt)
employee
end
end
validates_presence_of :current_password, if: :validate_password?, on: :update
validate :current_password_is_correct, if: :validate_password?, on: :update
def current_password_is_correct
if Employee.authenticate(code, current_password) == false
errors.add(:current_password, "Wrong password.")
end
end
def validate_password?
!password.blank?
end
end
如果我将current_password_is_correct更改为此,则会正确显示错误:
def current_password_is_correct
if Employee.authenticate(code, current_password) == false || true
errors.add(:current_password, "Wrong password.")
end
end
这让我觉得在执行此验证之前可能会更新密码。我如何确定这一点,如果是这样,我怎样才能以正确的顺序执行它?
由于
答案 0 :(得分:1)
此方法
def self.authenticate(user, password)
employee = find_by_code(user)
if employee && employee.password_hash == BCrypt::Engine.hash_secret(password, employee.password_salt)
employee
end
end
如果与员工不匹配,则返回nil
。当你测试它的结果时,在这里:
def current_password_is_correct
if Employee.authenticate(code, current_password) == false
errors.add(:current_password, "Wrong password.")
end
end
你专门测试结果== false
。 nil
不等于false
,雇员也不对,因此此测试将始终返回false,并且永远不会添加错误。我会将此方法更改为:
def current_password_is_correct
unless Employee.authenticate(code, current_password)
errors.add(:current_password, "Wrong password.")
end
end
&#34;除非&#34;案件将由任何事情触发&#34; falsy&#34;其中包括false
或nil
。
答案 1 :(得分:1)
像这样改变你的方法,并检查相同的
def self.authenticate(user, password)
employee = find_by_code(user)
employee && employee.password_hash == BCrypt::Engine.hash_secret(password, employee.password_salt)
end
答案 2 :(得分:0)
在Devise gem中,您可以使用update_with_password方法使用st
来询问当前密码它在轨道4和5上工作。
def update_password
@user = User.find(current_user.id)
if @user.update_with_password(password_params)
end
end
private
def password_params
params.require(:user).permit(:password, :password_confirmation, :current_password)
end