Search code examples
ruby-on-railsjsondevisedoorkeeper

How to return Doorkeeper access token as json


I am trying to create a log in system for an iOS app with a rails back end powered by devise and door keeper.

I want to limit the number of network requests so don't want to have to get the token from credentials then get the user details as a separate request.

Here is my current attempt:

token = Doorkeeper::AccessToken.create!(application_id: @application_id,
    resource_owner_id: current_user.id, :expires_in => 168.hours)
puts token.token
render :json => {:user => current_user, :token => token.as_json(:include=> token)}, 
    status: :ok, location: :users

However what is being returned is:

{"user":{"id":2,"email":"user3@test.com","created_at":"2014-06-12T17:25:12.000Z",
"updated_at":"2014-06-13T12:20:18.536Z",
"firstName":"user","lastName":"test","subscription":null},
"token":{"resource_owner_id":2,"scopes":[],"expires_in_seconds":604800,
"application":{"uid":"[Filtered]"}}}

So the actual access_token key isn't being passed back to allow me to make future calls. I can see that the token itself isn't returned in DoorKeeper::AccessToken.as_json, but token.as_json(:include=> token) still doesn't return it.

Does anyone know how to return the AccessToken, including the access token itself, as json?


Solution

  • The way I managed to solve this was to create my own AccessToken class that overloads the as_json method to include the fields I wanted.

    e.g

    class AccessToken < Doorkeeper::AccessToken
       def as_json(options={})
          {
            :token => self.token,
            #:resource_owner_id => self.resource_owner_id,
            #:scopes => self.scopes,
            :created_at => self.created_at,
            :expires_in_seconds => self.expires_in_seconds,
            #:application => { :uid => self.application.uid }
          }
       end
    end
    

    If anyone has a better solution I'm all ears