graphql_controller.rb 1.66 KB
Newer Older
1 2
# frozen_string_literal: true

Nick Thomas's avatar
Nick Thomas committed
3 4 5
class GraphqlController < ApplicationController
  # Unauthenticated users have access to the API for public data
  skip_before_action :authenticate_user!
6 7 8 9 10 11 12

  # Allow missing CSRF tokens, this would mean that if a CSRF is invalid or missing,
  # the user won't be authenticated but can proceed as an anonymous user.
  #
  # If a CSRF is valid, the user is authenticated. This makes it easier to play
  # around in GraphiQL.
  protect_from_forgery with: :null_session, only: :execute
Nick Thomas's avatar
Nick Thomas committed
13 14

  before_action :check_graphql_feature_flag!
15
  before_action(only: [:execute]) { authenticate_sessionless_user!(:api) }
Nick Thomas's avatar
Nick Thomas committed
16 17

  def execute
18
    variables = Gitlab::Graphql::Variables.new(params[:variables]).to_h
Nick Thomas's avatar
Nick Thomas committed
19 20 21 22 23 24 25 26 27
    query = params[:query]
    operation_name = params[:operationName]
    context = {
      current_user: current_user
    }
    result = GitlabSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
    render json: result
  end

28 29 30 31 32 33 34 35 36 37
  rescue_from StandardError do |exception|
    log_exception(exception)

    render_error("Internal server error")
  end

  rescue_from Gitlab::Graphql::Variables::Invalid do |exception|
    render_error(exception.message, status: :unprocessable_entity)
  end

Nick Thomas's avatar
Nick Thomas committed
38 39 40 41 42
  private

  # Overridden from the ApplicationController to make the response look like
  # a GraphQL response. That is nicely picked up in Graphiql.
  def render_404
43 44 45 46 47
    render_error("Not found!", status: :not_found)
  end

  def render_error(message, status: 500)
    error = { errors: [message: message] }
Nick Thomas's avatar
Nick Thomas committed
48

49
    render json: error, status: status
Nick Thomas's avatar
Nick Thomas committed
50 51 52
  end

  def check_graphql_feature_flag!
Phil Hughes's avatar
Phil Hughes committed
53
    render_404 unless Gitlab::Graphql.enabled?
Nick Thomas's avatar
Nick Thomas committed
54 55
  end
end