1

I have a question that is probably solved easily, but intense googling didn't quite help me. Problem is the following: I have a Rails application with an authentication system. The system works in such a way that there is an Admin user that can create other users. Problem is, I just reset my operation system and now everything needs to be hooked up again, including this Admin user. Before, you could just do it via the application, but this was not longer wanted any more. So now, you need to create the Admin user manually using sqlite3. So I need to do something like:

sqlite3 db/development.sqlite3 "INSERT INTO users VALUES(1,'admin-name','admin-email','admin-password','admin-password',1,1,1,1)"

But this obviously does not work, since "admin-password" is not encrypted. Trying to log on to the application then gives me

BCrypt::Errors::InvalidHash in SessionsController#create

as expected.

How can I insert an encrypted password so I can log on to the application as Admin?

I appreciate your help :-) Thank you and best regards!

user2902965
  • 87
  • 1
  • 1
  • 7

2 Answers2

2

I would do one of two things:

  1. Create a rake task that creates the admin user using the User model
  2. Have a database seed file that creates the admin user, again using your User class to handle the password encryption.

Which one you choose depends on how you plan to use it. If it's a common occurrence to need to create the admin user (I hope not), the rake task makes more sense. If you just need to wipe out the database and recreate it with a usable admin, the db seed is the path to go.

The reason I would avoid a raw SQL method is that it's way too easy to screw up, plus you might have sensitive data in the database that you don't want accessible to whoever is making the change. Automating processes like this can save a ton of effort in the future.

Eric Andres
  • 3,417
  • 2
  • 24
  • 40
0

Here's an example of how it works

#small script that automatically creates an admin user
puts 'creating admin user...'
namespace :db do
  namespace :admin_setup do
    task :admin => :environment do
      admin = User.create(
        :name => "admin", 
        :email => "admin", 
        :password => "admin", 
        :password_confirmation => "admin"
      )
    end
  end
end

Put this into a file called something.rake into folder path/to/application/lib/tasks and run it via

rake db:admin_setup:admin
user2902965
  • 87
  • 1
  • 1
  • 7