1

Hey I have a graphql mutation which needs to be implemented before user logs in. Till now I have been using graphql endpoints only after User is fully authenticated. Since graphql controller inherits application controller which implements a before_action :authenticate_user! callback I always need a valid user inorder to use the graphql endpoints. Is there a way to configure certain graphql endpoint to not have a valid user.

How should I go about it?

JIGME
  • 23
  • 4
  • you can always add a condition in your `authenticate_user!` method to skip authentication when a call with certain param/flag is made – Abhinay Jan 12 '22 at 16:49
  • Also, please consider adding more details to your question and things you've tried so far. – Abhinay Jan 12 '22 at 16:50

1 Answers1

0

You can add logic in execute method of GraphQlController that checks for exceptions.

For example, we want to skip authorization on "createSession" query that is supposed to generate JWT token for valid username/password combination. Trick is to create "Query" object where you can easily get to the query being invoked and determine if it's in skip list. Pardon the code it is first pass, just as proof of concept.

#class GraphqlController < Application Controller

 @skips_authorization = ["createSession"]

  def execute
    variables = prepare_variables(params[:variables])
    query = params[:query]
    operation_name = params[:operationName]
    current_user = AuthorizeApiRequest.call(request.headers).result

    context = {
      current_user: current_user,
    }
    query_parse = GraphQL::Query.new(ApiSchema, query_string = params[:query])
    result = ApiSchema.execute(query, variables: variables, context: context, operation_name: operation_name)

    if current_user.present? || @skips_authorization.include?(query_parse.selected_operation.selections[0].name)
      render json: result
    else
      render json: {}, status: 401
    end
  rescue StandardError => e
    raise e unless Rails.env.development?
    handle_error_in_development(e)
  end

drKreso
  • 1,030
  • 10
  • 16