2👍
This is what I have come up with, which allows to determine the access on a per-field basis.
import strawberry
import strawberry.django
from django.http.request import HttpRequest
from django.core.exceptions import PermissionDenied
from strawberry_django.fields.field import StrawberryDjangoField
class AuthStrawberryDjangoField(StrawberryDjangoField):
def resolver(self, info, source, **kwargs):
request: HttpRequest = info.context.request
if not request.user.is_authenticated:
raise PermissionDenied()
return super().resolver(info, source, **kwargs)
@strawberry.type
class Query:
foo: List[Foo] = AuthStrawberryDjangoField()
For a mutation you can use
async def graphql_check_authenticated(info: Info):
auth = await sync_to_async(lambda: info.context.request.user.is_authenticated)()
if auth is False:
raise PermissionDenied()
@strawberry.type
class Mutation:
@strawberry.mutation
async def add_foo(self, info: Info, new_foo: FooInput) -> None:
await graphql_check_authenticated(info)
# ...
See https://stackoverflow.com/a/72796313/3475778 why this is not a decorator.
I think this is not pure Graphql as this will return an error instead of a typed error message, maybe I will update it in the future on how to properly implement it.
Source:stackexchange.com