简体   繁体   English

如何在devise_token_auth gem中成功登录后返回自定义JSON?

[英]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 . 我正在使用devise_token_auth gem创建rails API。 I want not just the token in header that this gem returns after successful sign_in but also some table associated with user. 我想要的不仅仅是这个gem在成功的sign_in之后返回的标头中的标记,还有一些与用户关联的表。

How can I send custom JSON after successful sign_in from devise_token auth gem overriding the default JSON response? 从devise_token auth gem成功登录后,如何在重写默认JSON响应后发送自定义JSON?

In User model create a method " token_validation_response ". 在用户模型中,创建方法“ 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

I solved it my-self. 我解决了我自己。

First in config/routes.rb I added the custom sessions controller: 首先在config/routes.rb我添加了自定义会话控制器:

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: 然后创建了一个名为app/controllers/sessions_controller.rb的文件,并添加了以下内容:

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: 然后我创建了一个名为app/views/users/success.json.jbuilder并添加了如下的json数据:

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. 因此,我可以在成功登录后提供自定义JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM