简体   繁体   中英

Ruby On Rails - override rendering methods in devise_token_auth

I am currently using devise_token_auth to implement secure token based authentication for a my Rails API. This gem generates a User model with some attributes. After adding some custom attributes to my User model, the user management(log in, log out...) routes, provided by devise_token_auth , keep on rendering the same old attributes.

I've tried adding a UserSerializer but it didn't solve the issue.

Does anyone know how to render custom data for User model, using devise_token_auth ?

--- EDIT ---

I was reading the gem documentation and found out it was possible to override rendering methods , but I truly don't know how.

What the doc means, is that it is possible tu use your own Controller, to replace the basics Registrations/Sessions/Passwords/Token Validations Controllers.

For the sake of exemple, let say you want to override the RegistrationsController provided by DeviseTokenAuth.

First, you need to create your own controller, inheriting from the basic one :

# app/controllers/custom/registration_controller.rb
class Custom::RegistrationsController < DeviseTokenAuth::RegistrationsController

    def render_create_success
        # here, the @resource is accessible, in your case, a User instance.
        render json: {status: 'success', data: @resource.as_json}
    end

end

Then you need to tell the routing to route to your new controller :

# config/routes.rb
mount_devise_token_auth_for 'User', at: 'auth', controllers: {
    registrations: 'custom/registrations'
}

dvxam 's answer and thelastinuit helped me figure out how to implement the solution.

First, I created a method in my User model:

def token_validation_response                                                                                                                                         
  UserSerializer.root = false
  UserSerializer.new(self).as_json
end

Then, in app/controllers/custom/registration_controller.rb , overriding render_create_success the following way :

def render_create_success
  render json: @resource.token_validation_response ##@resource is a user instance
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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