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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With