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

2024-04-29 09:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望使用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
}

这很好,但是我更喜欢使用响应的状态码作为检查,所以我决定用一个定制的decorator包装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或石墨烯会提供这样的东西。你知道吗

请让我知道如果我需要提供更多的信息。谢谢你的帮助!你知道吗


Tags: 中间件ofpathnameinfoauthviewreturn