How to log in using a utility using the Rails console?

After loading the Rails console, how do I log in to my account?

Devise provides a test helper that can be used in tests, and I tried to use it in the console:

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

But I get:

 NoMethodError: undefined method `env' for nil:NilClass 

In any case, I would like to use a real assistant assistant, not this test assistant. Is there any way to achieve this?

+42
ruby-on-rails console devise
Feb 08 2018-11-11T00:
source share
3 answers

Here is one way I was able to do this:

 >> 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 
+73
Feb 08
source share
β€” -

Here is another example that 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' 
+9
May 20 '15 at 1:30 pm
source share

You can add an action inside one of your controllers and use the technique described here .

 class MyController < ApplicationController # POST /my_controller/become {'email': 'test@example.com'} def become raise 'not in development environment' unless Rails.env == 'development' sign_in User.find_by_email(params[:email]) end end 
-2
Jun 17 '15 at 13:54
source share



All Articles