How to sign in a user using Devise from a Rails console? How to sign in a user using Devise from a Rails console? ruby-on-rails ruby-on-rails

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


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


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

# get csrf tokenapp.get  '/users/sign_in'csrf_token = app.session[:_csrf_token]# log inapp.post('/users/sign_in', {"authenticity_token"=>csrf_token, "user"=>{"email"=>"foo", "password"=>"bar"}})# get new csrf token, as auth userapp.get ''csrf_token = app.session[:_csrf_token]# make a POST requestapp.post '/some_request.json', {"some_value"=>"wee", "authenticity_token"=>csrf_token}# make a GET requestapp.get '/some_other_request.json'


You can add an action inside one of your controller, and use the technique explained 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])  endend