Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to authenticate a user directly in the console under Devise. How can I do it?

I need to do something like this from Rails console to do some testing and experiments:

User.authenticate(username, password)

I'm using Devise, but I have no idea how to do this.

I saw this other answer here

How to sign in a user using Devise from a Rails console?

But I need something cleaner and more direct. If necessary, I just need the algorithm to hash an attempted password with the salt and compare it to the encryped_password.

Is it this?

User.find(1).valid_password?('password123') 
like image 723
dan Avatar asked Jul 17 '11 14:07

dan


People also ask

How do I add devise to an existing model?

Add Devise for existing model First, add a column called "email" if you don't already have one. Second, make sure that every existing row has a unique value for email. Finally, go into the migration file called "add_devise_to_users" and comment out the line that adds an email column. and restart your server.


1 Answers

General info:

Check out the Devise README found here.

As an example, here is a helper method that you can use to do this test:

class User
    def self.authenticate(username, password)
        user = User.find_for_authentication(:username => username)
        user.valid_password?(password) ? user : nil
    end
end

Testing it, I get:

1.9.3p194 :001 > user = User.find(1)
    User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
    User id: 1, {...USER DETAILS SHOWN HERE...}
1.9.3p194 :002 > user.valid_password?('is this it?')=> false

Also working: User.find(1).valid_password?('1') in Rails console:

1.9.3p194 :011 > User.find(1).valid_password?('1')
    User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
    => false

For reference, here's my Devise setup for the User model:

class User < ActiveRecord::Base`

  devise :database_authenticatable, :registerable, :timeoutable, :recoverable, :rememberable, :trackable, :validatable

  {...}

end

Like you said in the comments, there is no sessions_controller since Devise. Look into the Devise config file in /config/initializers/devise.rb. Depending on your application configuration, you may also want to look at the token.rb and session_store.rb initializer configs.

EDIT: Can you check your user model to see if devise is properly configured for it? Compare it against my devise line. The :validatable property could be missing.

EDIT 2: Added the helper method to do this test if you want to do it outside of the console. Check up top.

Side-note: The rails_admin gem is pretty useful and may be worth checking out!

Hope that helps.

like image 85
sbolel Avatar answered Oct 05 '22 22:10

sbolel