使用BCrypt更新密码 [英] Updating password with BCrypt

查看:185
本文介绍了使用BCrypt更新密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过BCrypt用用户名和密码登录时,没有问题时,一切都很好.

When I login with a username and password by BCrypt checks no problem, everything is fine.

但是,当我经历恢复密码的过程并尝试使用新密码登录时,BCrypt永远不会返回true.

But when I go through the process of recovering password and try to login with the new password the BCrypt never returns true.

我的代码如下:

before_save :encrypt_password
before_update :encrypt_password

def authenticate
   player = Player.find_by(mail: self.mail)
   unless player.nil?
   current_password = BCrypt::Password.new(player.password)
   if current_password == self.password
    player
   else
     nil
   end
 end
end

private
def encrypt_password
    unless self.password.nil?
    self.password = BCrypt::Password.create(self.password)
end

我正在使用Rails 4

I'm using rails 4

推荐答案

您不需要before_update回调.

You don't need the before_update callback.

在创建新记录(在这种情况下为用户)时,仅触发before_save.这样您就可以得到正确的行为.

When creating a new record (user in this case), only before_save is triggered. So you get the right behavior.

但是在更新记录时,会同时触发before_updatebefore_save,这意味着您的password列被加密了两次.这就是为什么您会发生意外的行为.

But when updating a record, both before_update and before_save are triggered, which means your password column is encrypted twice. That's why you get unexpected behavior.

检查此页面以获取有关回调的更多信息.

Check this page for more information about callbacks.

此外,我认为将password设置为数据库中的真实列是一个坏主意.您只需要在数据库中创建一个名为encrypted_password的列并将password设置为虚拟属性即可.

What's more, I think it's a bad idea to make password a real column in database. All you need is a column called encrypted_password in database and making password a virtual attribute.

所以您可以这样编写encrypt_password方法:

So you can write encrypt_password method like this:

def encrypt_password
    unless self.password.nil?
    self.encrypt_password = BCrypt::Password.create(self.password)
end

哪一个都没有机会像你刚才那样犯错.

Which gave you no chance to make a mistake like you just made.

这篇关于使用BCrypt更新密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆