agonist_
agonist_

Reputation: 5032

Devise don't want to return JSON after sign_in

I try to configure my rails app to be able to do sign_in by JSON request (that part look to work), and after that I don't want to be redirected, I just want the sign_in return me a JSON with the user email and some other stuff.

Can someone tell me how to do that ? I use the last version of rails with this gem token authentication and devise.

For the moment I've created a custom session controller but I don't know what to put inside. I'm new to rails so maybe it's easy but I can't find up to date answer to that.

Thank's

UPDATE : For information my main goal is to get back the auth token associated to the user after a sign_in success

Upvotes: 3

Views: 4131

Answers (2)

Emily
Emily

Reputation: 151

You can also use the yield block to create additional code and return before hitting the redirect command

def create
  super do
    render json: { user: current_user, 
                   token: form_authenticity_token }.to_json and return
  end
end

and return will stop the controller from continuing on after the yield block.

form_authenticity_token - I've had to reset the csrf-token in header after sign-in. This is one way to get the new csrf-token.

Upvotes: 6

Allerin
Allerin

Reputation: 1108

Override session create method of Devise::SessionsController

add a controller file in app/controllers/users/sessions_controller.rb and inherit Devise::SessionsController as below.

class Users::SessionsController < Devise::SessionsController

  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_flashing_format?
    sign_in(resource_name, resource)
    yield resource if block_given?
    respond_with resource, :location => after_sign_in_path_for(resource) do |format|
      format.json {render :json => resource } # this code will get executed for json request
    end
  end

end

Add following in routes to consider the inherited User::SessionsController

devise_for :users, :controllers => { :sessions => 'users/sessions'}

Upvotes: 4

Related Questions