在种子文件中加密用户密码
我需要使用加密密码为用户播种,我不使用Devise。 所以我尝试了这个:
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_confirmation
user = UserManager::User.new({ :name => 'a', :surname => 'a', :email => 'a', :active => true, :password => 'password', :password_confirmation => 'password'}) user.save
但是这两个字段是未知的,因为它们不在数据库中,所以如何使用种子加密密码呢?
编辑
用户模型
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
时可以免费获得。
为了播种用户,我建议在他的教程中使用Hartl的方法。
用户模型
添加手动生成密码摘要的方法:
# 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')} )
在你的模型中:
class User < ApplicationRecord has_secure_password end
在seeds.rb文件中:
User.create(username: "username", ... password_digest: BCrypt::Password.create('Your_Password'))
您可以创建密码哈希,如下所示:
require 'digest/sha1' encrypted_password= Digest::SHA1.hexdigest(password)
您可以在seeds.rb文件中使用此代码来加密密码。 但似乎你已经编写了一个方法encrypt_password
。 现在,您可以在before_save
回调中调用此方法。 因此,每次用户即将保存在数据库中时,将调用encrypt_password
。