在 Ruby on Rails 中使用 Devise 为用户播种

问题描述 投票:0回答:15

在我的开发和测试环境中,我想用一群用户为数据库播种。我正在使用 Ruby on Rails v3.2.8 和最新的 Devise。所以我在 db/seeds.rb 文件中添加了这一行:

User.create(email: '[email protected]', encrypted_password: '#$taawktljasktlw4aaglj')

但是,当我运行

rake db:setup
时,出现以下错误:

耙子中止!无法批量分配受保护的属性: 加密密码

种子用户的正确方法是什么?

ruby-on-rails ruby-on-rails-3 devise ruby-on-rails-3.2 seed
15个回答
51
投票

你必须这样做:

user = User.new
user.email = '[email protected]'
user.encrypted_password = '#$taawktljasktlw4aaglj'
user.save!

阅读本指南以了解什么是批量分配:http://guides.rubyonrails.org/security.html

我想知道为什么一定要直接设置加密密码。你可以这样做:

user.password = 'valid_password'
user.password_confirmation = 'valid_password'

30
投票

阿伦是对的。在你的 seeds 中执行此操作会更容易。rb

user = User.create! :name => 'John Doe', :email => '[email protected]', :password => 'topsecret', :password_confirmation => 'topsecret'

16
投票

仅当您的用户模型中有

skip_confirmation
模块时,
confirmable
方法才有效,否则将其删除。

  user = User.new(
      :email                 => "[email protected]",
      :password              => "123456",
      :password_confirmation => "123456"
  )
  user.skip_confirmation!
  user.save!

8
投票

这是一个老问题,但这是一个管理员用户的示例(来自 cancancan):

User.create!([
  {email: "[email protected]", password: "testadminuser", password_confirmation: "testadminuser", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2015-02-06 14:02:10", last_sign_in_at: "2015-02-06 14:02:10", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", admin: true},
  {email: "[email protected]", password: "testuseraccount", password_confirmation: "testuseraccount", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2015-02-06 14:03:01", last_sign_in_at: "2015-02-06 14:03:01", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", admin: false},
  {email: "[email protected]", password: "testcustomeruser", password_confirmation: "testcustomeruser", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2015-02-06 14:03:44", last_sign_in_at: "2015-02-06 14:03:44", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", admin: false}
])

8
投票

如果您使用的是 devise

confirmable
模块,您需要执行以下操作:

user = User.new(
  email: '[email protected]', 
  password: '123456789', 
  password_confirmation: '123456789'
)
user.skip_confirmation!
user.save!

skip_confirmation!
电话只是告诉你不需要确认此帐户。
其他选项只是在保存之前将
confirmed_at
用户属性设置为
Time.now.utc


4
投票

为用户表播种:

User.create(
        email: "[email protected]",
        password: "12345678"
    )

安装devise后,

:password
将自动散列并保存到
:encrypted_password


4
投票

我不知道这是否有帮助,但实际上我这样做是为了在我的Rails 5应用程序中创建一个默认管理员用户,但不会在我的GitHub存储库中以纯文本形式共享密码。

基本上这个逻辑是:

  • 播种时为默认用户生成安全的随机密码。
  • 转至 “.../admins/sign_in” 并单击 “忘记密码?” 链接以重置密码。
  • 在默认电子邮件帐户中获取重置密码链接
  • 设置新密码。

所以在

db/seeds.rb
中添加以下内容:

randomPassword = Devise.friendly_token.first(8)
mainAdminUser = Admin.create!(email: "[email protected]", password: randomPassword, name: "Username")

如果您使用的是 devise

confirmable
功能,只需执行以下操作即可跳过可确认的选项:

mainAdminUser = Admin.new(
    email: "[email protected]",
    password: randomPassword,
    password_confirmation: randomPassword,
    name: "Username"
)
mainAdminUser.skip_confirmation!
mainAdminUser.save!

祝你一切顺利!

现在您有一个默认用户,但您不共享默认密码! 我希望它对某人有用。


2
投票

不要尝试创建加密密码,系统会为您处理该密码。这可行,只需确保密码长度至少为 6 个字符即可。

User.create(
        email: "[email protected]",
        password: "123456"
    )

更好的是,在你的终端中:

$bundle add faker

然后:

User.create(
            email: [email protected],
            password: "123456"
        )
10.times do
  User.create(
              email: Faker::Internet.email,
              password: "123456"
           )
end

只需确保您在种子中设置了至少一封您能记住的电子邮件即可。因此保留“测试”电子邮件。


1
投票

使用您的 db/seeds.rb 文件来启动您的第一个用户:

User.create!(email: '[email protected]', 
             password: '123456789', 
             password_confirmation: '123456789')

1
投票

对于 seeds.rb 文件中的设计用户,对我有用的是在保存新用户时使用通用密码。然后更新加密密码并再次保存模型。这是一种很狡猾的方式。

user = User.new(
    :email                 => "[email protected]",
    :password              => "fat12345",
    :password_confirmation => "fat12345"
)
user.save!
user.encrypted_password="ENCRYPT.MY.ASS!!!KJASOPJ090923ULXCIULSH.IXJ!S920"
user.save

更新其他人已经发布的内容,这是更好的方法:

user = User.new(
    email: "[email protected]", 
    password: "foob1234", 
    password_confirmation: "foob1234"
)
user.skip_confirmation! #only if using confirmable in devise settings in user model.
user.save!

0
投票

我在我的一项要求中做了同样的事情,所以只需粘贴我的代码片段

def triggerSeedUsers
      p "Starting Seeding Users..."
      p   "Deleting all users"..
      User.destroy_all
      normal_users = [{:email => '[email protected]', :login => "abc_demo", :name => 'abc Demo'}]
      admin_users = [{:email => '[email protected]', :login => 'abc_admin', :name => 'abc Admin'}]

      [normal_users,admin_users].each do |user_type|
        user_type.each do |user|
          User.create!(:name => user[:name],
            :login => user[:login],
            :email => user[:email],
            :first_login => false,
            :password => 'P@ssw0rd',
            :password_confirmation => 'P@ssw0rd'
            )
        end
      end
      User.where('name LIKE ?', '%demo%').update_all(:is_admin => 0)
      User.where('name LIKE ?', '%admin%').update_all(:is_admin => 1)
     end

0
投票

在 db:seed 中通过电子邮件确认:

User.create!( name: 'John', email:'[email protected]', password: '123456', password_confirmation: '123456',confirmed_at: '2018-08-04 04:51:43', current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1")

0
投票

只需添加:password属性rest,devise就会为你做password_encrypt

user = User.new({ email: '[email protected]', password: 'EnterYourPassword'})
user.save!
flash[:notice] = 'User Created'

#or for extra logic

        #if user.save
          #ExtraCredentialsOrLogic

        #elsif user.errors.any?
          #user.errors.full_messages.each do |msg|
            #puts msg
          #end
        #else
          #puts "****NOT VALID****"
    #end

现在运行“rake db:seed”


0
投票

这允许您多次运行种子而不会出现错误:

User.where(email: "[email protected]").first_or_create.update_attributes(nome: "Your Name",
    email: "[email protected]",
    password:              "password#123",
    password_confirmation: "password#123")

0
投票

在我的 Rails 3 用户模型中,还有几个必填字段。结合此处和其他地方的其他建议,我构建了一个导出 rake 任务,该任务创建一个 seeds.rb,该任务与 Rails 5 中接收端的 devise 配合使用。它首先让 Devise 加密伪造的密码,然后保存用户的原始加密密码。请注意 .serialized_hash 的方法参数,如果没有该参数,这些字段将不会被序列化。

namespace :export do
  desc "Export users"
  task :seeds => :environment do
    # Dependent models loaded first
    User.all.each do |user|
      excluded_keys = ['invitation_sent_at', 'invitation_accepted_at', 'invitation_created_at']
      serialized = user
                    .serializable_hash(methods: [:encrypted_password, :sign_in_count])
                     .delete_if{|key,value| excluded_keys.include?(key)}
      serialized['password'] = '123456789ABCDefg%'
      serialized['password_confirmation'] = '123456789ABCDefg%'
      puts "user = User.new(#{serialized})"
      puts "user.save!"
      puts "user.encrypted_password = '#{user.encrypted_password}'"
      puts "user.save!"
    end
  end
end

我用

rake export:seeds
运行了它。我还必须更改 user.rb 以绕过 Devise 对日期执行的一些序列化。我没有费心对邀请日期执行此操作,因为它们可以为空并且旁路不起作用。生成 seeds.rb 后,我将“序列化”行撤回,因为我不确定可能会产生什么后果。相关线路在这里:

class User < ActiveRecord::Base 
  devise :timeoutable, :timeout_in => 6.hours
  devise :invitable, :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  serialize :created_at, DateTime
  serialize :updated_at, DateTime
© www.soinside.com 2019 - 2024. All rights reserved.