Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return custom JSON after successful sign_in in devise_token_auth gem?

I am creating a rails API using devise_token_auth gem. I want not just the token in header that this gem returns after successful sign_in but also some table associated with user.

How can I send custom JSON after successful sign_in from devise_token auth gem overriding the default JSON response?

like image 220
SulmanWeb Avatar asked Mar 09 '16 07:03

SulmanWeb


2 Answers

I solved it my-self.

First in config/routes.rb I added the custom sessions controller:

mount_devise_token_auth_for 'User', at: 'auth', skip: [:omniauth_callbacks], controllers: { registrations: "registrations", sessions: "sessions" }

Then created a file called app/controllers/sessions_controller.rb and added following content:

class SessionsController < DeviseTokenAuth::SessionsController
  def render_create_success
    render "users/success"
  end
end

Then I created a file named app/views/users/success.json.jbuilder and added the json data like this:

json.data @resource
json.groups @resource.groups do |group|
  json.id group.id
  json.name group.name
end

So by that I can give the custom JSON after successful login.

like image 80
SulmanWeb Avatar answered Oct 18 '22 20:10

SulmanWeb


In User model create a method "token_validation_response". Example:

def token_validation_response
  {test: 'this is custom data'}
end

Or if you want to add a custom field, you can do it like this:

  def as_json(options={})
    super(options).merge({test: 'this is custom field'})
  end
like image 38
Swagga Avatar answered Oct 18 '22 20:10

Swagga