我想让用户有机会更新一些用户信息。现在只有名称和电子邮件。用户需要键入当前密码才能授权更新。我尝试了几种方法,它归结为以下问题:
在更新用户属性之前,我调用了“validate_password”方法。
users_controller.rb:
def update
@user = User.find(params[:id])
respond_to do |format|
if validate_password(params[:password]) && @user.update_attributes(params[:user])
format.html { redirect_to @user, notice: 'Account 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
端
application_controller.rb:
def validate_password(pswd)
if current_user.password_hash == BCrypt::Engine.hash_secret(pswd, current_user.password_salt)
true
else
false
end
端
即使使用正确的密码“pswd”,它也会返回false。 我错过了什么吗?如果你知道正确的盐,你可以重新创建密码哈希吗?
答案 0 :(得分:1)
假设current_user.password_hash
包含使用BCrypt::Password#create
创建的哈希,而不是
current_user.password_hash == BCrypt::Engine.hash_secret(...)
试
BCrypt::Password.new(current_user.password_hash) == passwd
不要自己做盐腌。这是多余的,因为BCrypt已经进行了腌制。
良好方向的另一个步骤是放弃手写身份验证并使用现有的经过实战检验的解决方案,例如: Devise
答案 1 :(得分:1)
您也可以使用:
validates_presence_of :password, :on => :create
这样,您将在更新时避免密码验证。