Encrypt User's password in seed file

女生的网名这么多〃 提交于 2019-12-24 16:26:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!