How do I set a current_user in Rack middleware for GraphQL

326 Views Asked by At

I'm using GraphQLPlayground configured in my config.ru

  map "/graphql-playground" do
    use GraphqlPlaygroundAuthentication
    use GraphQLPlayground, endpoint: "/graphql"
  end
end

And I want to authorize my requests via GraphqlPlaygroundAuthentication since Rack does not send cookies with the request.

In my graphql_controller.rb I have this:

def execute
    variables = prepare_variables(params[:variables])
    query = params[:query]
    operation_name = params[:operationName]
    context = {
      current_actor: current_user
    }
    # more code here

How do I set current_user inside of GraphqlPlaygroundAuthentication.rb? I have tried to set cookies with Rack::Utils.set_cookie_header! but even though I see the cookies inside Application tab in my browser, my current_user inside request is nil.

I have no idea how to set the current_user to be available inside the controller and then my playground requests are unauthorized.

Reason why Playground is mounted inside config.ru and not routes.rb: CSP configuration of my project. I cannot change that.

1

There are 1 best solutions below

0
Daniel N. On

You need to define current_user method in your controllers/application_controller.rb.

class ApplicationController < ActionController::API
  def current_user
    # If test situation when user is logged in
    User.first

    # If test situation when user is not logged in
    # nil
  end
end