Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

After loading the Rails console, how should I sign in a user?

Devise provides a test helper which can be used in tests and I've tried to use in console:

>> include Devise::TestHelpers >> helper.sign_in(User.first) 

But I get:

NoMethodError: undefined method `env' for nil:NilClass 

Anyway, I would like to use the real devise helper and not this test helper. Is there any way to achieve this?

like image 378
Christian Avatar asked Feb 08 '11 02:02

Christian


People also ask

What does devise do in Rails?

Devise creates all the code and routes required to create accounts, log in, log out, etc. Make sure your rails server is running, open http://localhost:3000/users/sign_up and create your user account.


2 Answers

Here's one way I was able to do it:

>> ApplicationController.allow_forgery_protection = false >> app.post('/sign_in', {"user"=>{"login"=>"login", "password"=>"password"}}) 

Then you can do:

 >> app.get '/some_other_path_that_only_works_if_logged_in'  >> pp app.response.body 
like image 141
Brian Deterling Avatar answered Oct 25 '22 07:10

Brian Deterling


Here is another example which uses the csrf token, authenticates the user, and makes a POST/GET request.

# get csrf token app.get  '/users/sign_in' csrf_token = app.session[:_csrf_token]  # log in app.post('/users/sign_in', {"authenticity_token"=>csrf_token, "user"=>{"email"=>"foo", "password"=>"bar"}})  # get new csrf token, as auth user app.get '' csrf_token = app.session[:_csrf_token]  # make a POST request app.post '/some_request.json', {"some_value"=>"wee", "authenticity_token"=>csrf_token}  # make a GET request app.get '/some_other_request.json' 
like image 30
Eric London Avatar answered Oct 25 '22 07:10

Eric London