Graphql-ruby构建突变/查询无需用户身份验证

f45qwnt8  于 2022-11-04  发布在  Ruby
关注(0)|答案(1)|浏览(110)

嘿,我有一个graphql变种,需要在用户登录之前实现。到目前为止,我一直在使用graphql端点,只有在用户完全通过身份验证后。由于graphql控制器继承了应用程序控制器,它实现了before_action :authenticate_user!回调,我总是需要一个有效的用户才能使用graphql端点。有没有办法配置某些graphql端点没有有效的用户。
我该怎么做呢?

yrdbyhpb

yrdbyhpb1#

您可以在GraphQlController的execute方法中添加检查异常的逻辑。
例如,我们希望跳过对“createSession”查询的授权,该查询应该为有效的用户名/密码组合生成JWT标记。技巧是创建“Query”对象,在该对象中您可以轻松地访问正在调用的查询,并确定它是否在跳过列表中。请原谅代码,这是第一次通过,只是作为概念证明。


# 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

相关问题