-
Hello, I would like to restrict access to some of the queries and mutations available in my schema. As mentioned in #506 it is not possible to add custom directives on queries. So I added my custom directive on the object I want to restrict access to: from functools import partial
from ariadne import QueryType, make_executable_schema
from ariadne.asgi import GraphQL
from ariadne.schema_visitor import SchemaDirectiveVisitor
from graphql import default_field_resolver
from graphql.type.definition import GraphQLObjectType
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
import uvicorn
type_def = """
directive @checkAccess(needs: [String]) on OBJECT
type MyObject @checkAccess(needs: ["admin"]) {
id: Int!
name: String!
}
type Query {
getObject: MyObject
}
"""
query = QueryType()
@query.field("getObject")
def resolve_getObject(obj, info):
return {"id": 1, "name": "object1"}
class MyObjectDirective(SchemaDirectiveVisitor):
def visit_object(self, obj: GraphQLObjectType):
self.check_myobject(obj)
def check_myobject(self, obj: GraphQLObjectType):
def _resolver(_, info, *, field=None, obj_=None):
return original_resolver(_, info)
for _, field in obj.fields.items():
original_resolver = field.resolve or default_field_resolver
field.resolve = partial(_resolver, field=field, obj_=obj)
schema = make_executable_schema(type_def, query,
directives={"checkAccess": MyObjectDirective})
graphqlapp = GraphQL(schema, debug=True)
app = Starlette(debug=True, middleware=[Middleware(CORSMiddleware,
allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])])
app.mount("/graphql", graphqlapp)
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=5000, log_level="info") The problem is that the query's resolver |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Your What you are after doesn't seem like something that can be achieved out of the box with |
Beta Was this translation helpful? Give feedback.
Your
MyObjectDirective.visit_object
is not run against the resolvers onQuery
type, but instead on resolvers onMyObject
fields.What you are after doesn't seem like something that can be achieved out of the box with
SchemaDirectiveVisitor
. You will have to write custom logic that would walk theschema
object and wrap resolvers returningMyObject
with custom resolver checking permissions.