Search code examples
ruby-on-railsjsonactive-model-serializersdevise-token-auth

API JSON Response serialize to throw custom message


I am using devise token auth gem along with active model serializer to authenticate, which sends response like

{

  "status": "Success",

  "message": "User Created Successfully",

  "data": {

    "id": 9,

    "tokens": {

      "cUZCQrKCPQCijIjCWZI4mA": {

        "token": "$2a$10$9/ZKX7KmH4sLLdp19R331.E9BLInpnXCkJCX0xffJSHpTsu0/X.UK",

        "expiry": 1554720926

      }

    }

  }

}

But I am primarily looking to get something like :-

{

  "status": "Success",

  "message": "User Created Successfully",

  "data": {

    "id": 9,

    "token": "$2a$10$9/ZKX7KmH4sLLdp19R331.E9BLInpnXCkJCX0xffJSHpTsu0/X.UK"

  }

}

I tried using JSON Parse , tried fetching the last token but since the name is unknown as it is randomly generate, I am unable to do so. How can i go about to achieve this?

Edit :- User Serializer :-

class UserSerializer < ActiveModel::Serializer
  attributes :id, :tokens
end


Solution

  • Thank you for posting your code. Could you try this?

    class UserSerializer < ActiveModel::Serializer
      attributes :id, :token
    
      def token
        tokens = DeviseTokenAuth::TokensSerialization.load(object.tokens) # This gives you a hash
        tokens['YOURCLIENTID']['token']
      end
    end
    

    UPDATE

    You need the clientid, which is the key to the hash. Also, the gem generates the token using JSON.generate. So you can deserialize using load.

    I hope this helps!