加密种子文件中的用户密码 [英] Encrypt User's password in seed file
问题描述
我需要使用加密密码为用户播种,但我没有使用 Devise.所以我尝试了这个:
I need to seed an user with encrypted password and I'm not using Devise. So I tried this :
user = UserManager::User.new({ :name => 'a', :surname => 'a', :email => 'a', :active => true, :password_hash => 'password', :password_salt => 'password'})
user.save
但是这样放置password_hash和password_salt是不对的,我发现我必须改用password和password_confirmation
But this is not right to put password_hash and password_salt like this and I found that I have to put password and password_confirmation instead
user = UserManager::User.new({ :name => 'a', :surname => 'a', :email => 'a', :active => true, :password => 'password', :password_confirmation => 'password'})
user.save
但是这两个字段是未知的,因为它们不在数据库中,所以我该如何用种子加密密码?
But these 2 fields are unknow because they are not in the database, so how can I do to encrypt the password with seed ?
编辑
用户模型
attr_accessor :password
has_secure_password
before_save :encrypt_password
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
推荐答案
password
不需要属性访问器.使用 has_secure_password
即可免费获得.
You don't need the attribute accessor for password
. You get that for free when you use has_secure_password
.
对于种子用户,我建议使用 Hartl 教程中的方法.
To seed users, I would recommend using Hartl's approach from his tutorial.
用户模型
添加手动生成密码摘要的方法:
Add a method for generating the password digest manually:
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
种子文件
User.create!(name: 'foo',
email: 'foo@bar.com',
password_digest: #{User.digest('foobar')} )
这篇关于加密种子文件中的用户密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!