0

I'm trying to assign a value to current_user in GraphqlController but it's not working.
this is my code in graphql_controller.rb

class GraphqlController < ApplicationController
  # If accessing from outside this domain, nullify the session
  # This allows for outside API access while preventing CSRF attacks,
  # but you'll have to authenticate your user separately
  # protect_from_forgery with: :null_session

  def execute
    variables = ensure_hash(params[:variables])
    query = params[:query]
    operation_name = params[:operationName]
    context = {
      # Query context goes here, for example:
      session: session,
      current_user: current_user
    }
    result = GraphqlSimpleLoginAppSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
    render json: result
  rescue => e
    raise e unless Rails.env.development?
    handle_error_in_development e
  end

  private

  def current_user
    return  unless session[:token]
    AuthToken.verify(session[:token])
  end

  # Handle form data, JSON body, or a blank value
  def ensure_hash(ambiguous_param)
    case ambiguous_param
    when String
      if ambiguous_param.present?
        ensure_hash(JSON.parse(ambiguous_param))
      else
        {}
      end
    when Hash, ActionController::Parameters
      ambiguous_param
    when nil
      {}
    else
      raise ArgumentError, "Unexpected parameter: #{ambiguous_param}"
    end
  end

  def handle_error_in_development(e)
    logger.error e.message
    logger.error e.backtrace.join("\n")

    render json: { errors: [{ message: e.message, backtrace: e.backtrace }], data: {} }, status: 500
  end
end

but current_user remains null. I don't know why. Please can you help me ?

  • whats the output of session[:token] and AuthToken.verify(session[:token]) in current_user method? – Simon Franzen May 23 '20 at 20:33
  • `session[:token]` returns a token that I generated with jwt, and the method `AuthToken.verify(session[token])` makes it possible to check by decoding the token and to make a request of selection to have a `user` according to his `id` – Aristide Ehouman May 25 '20 at 07:42

0 Answers0