有没有一种方法可以使用Graphene / GraphQL从GraphQLString解析AST

时间:2019-03-25 13:49:42

标签: python django graphql graphene-python pyjwt

我正在使用PyJWT为GraphQL端点编写自定义中间件。问题是我不想保护我的登录突变。因此,我正在尝试编写中间件以排除登录突变。

通过编写GraphQL中间件很容易做到这一点,因为传递给中间件的参数使我能够检查查询的名称。

class JWTMiddleware(object):
    def resolve(self, next, root, info, **args):
        if info.field_name == 'login':
            return next(root, info, **args
        # rest of auth logic

但是因为GraphQL总是返回200,所以我不能在客户端上使用状态代码作为我的身份验证失败检查。并且必须检查errors数组以查看消息是Unauthorized还是其他东西。

示例错误响应:

{
    errors: [
        {
            message: 'Unauthorized: JWT invalid',
            ...,
        },
        ...
    ],
    data: null
}

这很好,但是我希望使用响应的状态代码作为检查,因此我决定使用自定义装饰器包装GraphQL视图。

def jwt_required(fn):
    def wrapper(request):
        # no access to query name, just the GraphQLString
        # need function to parse the AST of a GraphQLString
        graphql_string = request.body.decode('utf-8')
        query_name = ast[0].name  # or something like this
        if query_name == 'login':
             return fn(request)
        # rest of auth logic
        return fn(request)
    return wrapper


def protected_graphql_view():
    return jwt_required(GraphQLView.as_view())


urlpatterns = [
    path('admin/', admin.site.urls),
    path('graphiql', GraphQLView.as_view(graphiql=True)),
    path('graphql', protected_graphql_view()),
    path('token/refresh', refresh_token_view),
]

通过这样做,我现在可以返回带有不同状态代码的响应。但是同样的问题是,除非我可以正确解析GraphQLString,否则我无法轻易检查请求是否用于登录并跳过auth逻辑。

如果可能,我宁愿不定制产品。我认为GraphQL或Graphene会提供类似的信息。

请让我知道是否需要提供更多信息。谢谢您的帮助!

0 个答案:

没有答案
相关问题