Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize Devise user JSON response on creation of a user account

How do I customize the JSON output on creation of a devise User?

### User.rb ###
class User < ActiveRecord::Base
  devise :database_authenticatable,
         :registerable, ...
  ...
end

### Routes.rb ###
...
devise_for :users, :controllers => {:registrations => "registrations"}
...

I've got some extra fields in my User table that are secret, but they get returned in the JSON response when I do a User creation via JSON like this:

$ curl -H "Content-Type: application/json" -d '{"user" : {"username":"someone","email":"[email protected]","password":"awesomepass"}}' -X POST http://localhost:3000/users.json

which returns:

{"user":{"secret_field_1":"some value","secret_field_2":"some value","created_at":"2013-07-25T21:24:50-05:00","email":"[email protected]","first_name":null,"id":3226,"last_name":null,"updated_at":"2013-07-25T21:24:50-05:00","username":"someone"}}

I'd like to hide those secret fields, but don't know how to customize the JSON response.

I've tried a standard ActiveRecord serializer:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :created_at, :updated_at, :email, :first_name, :last_name, :username
end

to no avail, I'm guessing because of Devise.

like image 983
joseph.hainline Avatar asked Jul 26 '13 02:07

joseph.hainline


2 Answers

I just ran into the same issue. I haven't pinpointed exactly why but it looks like respond_with in Devise's SessionsController (tested on Devise 3.0 and active_model_serializers 0.8.1) doesn't trigger the ActiveModel::Serializer.

So I overrode respond_with in my controller:

class SessionsController < Devise::SessionsController

  def respond_with(resource, opts = {})
    render json: resource # Triggers the appropriate serializer
  end

end

It is, however, working in my RegistrationsController with respond_with. There I needed to do the following:

class RegistrationsController < Devise::RegistrationsController

  respond_to :json
end
like image 78
mattwindwer Avatar answered Oct 03 '22 07:10

mattwindwer


I recently ran into this and overriding respond_with didn't fix the issue. I ended up overriding to_json in user.rb like so:

def to_json(arg)
  UserSerializer.new(self).to_json
end

Not sure what the extra arg is, but that seems to be required by one of the devise mixins.

I'm using the following:

  • Rails 4.2.0
  • Devise 3.4.1
like image 36
Gowiem Avatar answered Oct 03 '22 08:10

Gowiem