0
我正在实施验证方案,并使用bcrypt-ruby gem。困惑如何使用bcrypt-ruby
需要 'bcrypt'
class User < ActiveRecord::Base
include BCrypt
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
validates :password, :presence => true, :on => :create,
:confirmation => true,
:length => {:within => 6..12}
before_save :encrypt_password
def has_password?(submitted_password)
self.encrypted_password == submitted_password # this calls a method in bcrypt
# File lib/bcrypt.rb, line 171
# def ==(secret)
# super(BCrypt::Engine.hash_secret(secret, @salt))
# end
end
private
def encrypt_password
self.encrypted_password = Password.create(password, :cost => 5)
end
end
在控制台
现在我创建一个新用户
>> user = User.create!(:name => "test", :email => "[email protected]", :password => "foobar", :password_confirmation => "foobar")
=> #<User id: 1, name: "test", email: "[email protected]", created_at: "2011-06-23 05:00:00", updated_at: "2011-06-23 05:00:00", encrypted_password: "$2a$10$I7Wy8NDMeVcNgOsE3J/ZyubiNAESyxA7Z49H4p1x5xxH...">
如果我检查密码是否有效我做了以下内容:
>> user.has_password?("foobar")
=> true
但如果我从数据库中获得用户,它会失败:
user = User.find(1)
user.has_password?("foobar")
=> false
为什么会发生这种情况,我该如何实现bcrypt才能完成这项工作?
预先感谢您。
将dbrypt :: Password存储在db而不是encypted_password是否更好?我怎样才能做到这一点? – chell