问题
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
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 ?
EDIT
User model
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
回答1:
You don't need the attribute accessor for password
. You get that for free when you use has_secure_password
.
To seed users, I would recommend using Hartl's approach from his tutorial.
User model
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
Seed file
User.create!(name: 'foo',
email: 'foo@bar.com',
password_digest: #{User.digest('foobar')} )
回答2:
In your model:
class User < ApplicationRecord
has_secure_password
end
In the seeds.rb file:
User.create(username: "username",
...
password_digest: BCrypt::Password.create('Your_Password'))
回答3:
You can create a hash of password something like following:
require 'digest/sha1'
encrypted_password= Digest::SHA1.hexdigest(password)
You can use this code in your seeds.rb file to encrypt the password. But it seems that you have already written a method encrypt_password
. Now, you can call this method in before_save
callback. So each time, a user is about to be saved in database, encrypt_password
will be called.
来源:https://stackoverflow.com/questions/31026248/encrypt-users-password-in-seed-file