4

Using version 0.6.0 of the jsonapi-resources gem in conjuction with Doorkeeper I am having a problem seeing the current user in the context object in my resource.

I am basically following the docs, however nothing I try will make the context I set in ApplicationController visible in the resource's fetchable_fields method. I did confirm that context is actually being set in my ApplicationController.

Here is what I have

ApplicationController

class ApplicationController < JSONAPI::ResourceController
  protect_from_forgery with: :null_session

  def context
    {current_user: current_user}
  end
end

Controller

class Api::ItemsController < ApplicationController
  prepend_before_action :doorkeeper_authorize!
end

Resource

class Api::ItemResource < JSONAPI::Resource
  # attributes

  def fetchable_fields
    # context is always nil here
    if (context[:current_user].guest)
      super - [:field_i_want_private]
    else
      super
    end
  end
end
Dhaulagiri
  • 3,281
  • 24
  • 26
  • Did you ever get an answer for this, I am running up against something similar? – withakay Jan 07 '16 at 22:01
  • I did not @withakay. I ultimately didn't need to do this but we should probably open an issue in github since it seems unlikely to get addressed here. – Dhaulagiri Jan 08 '16 at 16:59
  • I guess `:doorkeeper_authorize!` has a method called `current_user`? Are you sure it works properly? – Fei Oct 20 '17 at 13:01

3 Answers3

0

Well, using the jsonapi-utils gem – that is created on top of jsonapi-resources – you would write something like this:

ApplicationController:

class ApplicationController < JSONAPI::ResourceController
  include JSONAPI::Utils
  protect_from_forgery with: :null_session
end

ItemsController:

class API::ItemsController < ApplicationController
  prepend_before_action :doorkeeper_authorize!
  before_action :load_user

  def index
    jsonapi_render json: @user.items
  end

  private

  def load_user
    @user = User.find(params[:id])
  end
end

No need to define context :-)

I hope it helps you. Cheers!

Tiago G.
  • 119
  • 2
  • 3
0

Taking your example, here is my solution

Resource

class Api::ItemResource < JSONAPI::Resource
  # attributes

  def fetchable_fields
    # context is always nil here
    if (context[:current_user].guest)
      super - [:field_i_want_private]
    else
      super
    end
  end

  # upgrade
  def self.create(context)
    # You can use association here but not with association table
    # only works when `id` is inside the table of the resource
    ItemResource.new(Item.new, context)
  end

  before_save do
    # Context is now available with `self.context`
    self.context[:current_user]
  end
end
brcebn
  • 1,571
  • 1
  • 23
  • 46
-1

You do not need a context method in the ApplicationController. The context is actually available in the Resource class through the framework. In your resource, you can access:

@context[:current_user]
Ilya Kaplun
  • 51
  • 1
  • 5