From 93ec8eb09923ae9eabceae7071e11a5893cbf577 Mon Sep 17 00:00:00 2001 From: Jason Kraus Date: Sat, 23 Jan 2021 21:32:01 -0800 Subject: [PATCH 1/2] document auth pattern: return None with resolve method --- docs/authorization.rst | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/authorization.rst b/docs/authorization.rst index 387ad299f..62f582af3 100644 --- a/docs/authorization.rst +++ b/docs/authorization.rst @@ -48,6 +48,28 @@ conversely you can use ``exclude`` meta attribute. exclude = ('published', 'owner') interfaces = (relay.Node, ) + +Another pattern is to have a resolve method act as a gatekeeper, returning None +if the client isn't allowed to see the data. + +.. code:: python + + from graphene import relay + from graphene_django.types import DjangoObjectType + from .models import Post + + class PostNode(DjangoObjectType): + class Meta: + model = Post + fields = ('title', 'content', 'owner') + interfaces = (relay.Node, ) + + def resolve_owner(self, info): + if info.context.user.is_anonymous(): + return None + return self.owner + + Queryset Filtering On Lists --------------------------- From 712d99caa4296ed34ecfce58c77dbe51d038b90e Mon Sep 17 00:00:00 2001 From: Jason Kraus Date: Fri, 29 Jan 2021 16:38:49 -0800 Subject: [PATCH 2/2] (doc, auth): also show that one can raise an exception in a resolve method --- docs/authorization.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/authorization.rst b/docs/authorization.rst index 62f582af3..39305f6b1 100644 --- a/docs/authorization.rst +++ b/docs/authorization.rst @@ -50,7 +50,7 @@ conversely you can use ``exclude`` meta attribute. Another pattern is to have a resolve method act as a gatekeeper, returning None -if the client isn't allowed to see the data. +or raising an exception if the client isn't allowed to see the data. .. code:: python @@ -65,7 +65,10 @@ if the client isn't allowed to see the data. interfaces = (relay.Node, ) def resolve_owner(self, info): - if info.context.user.is_anonymous(): + user = info.context.user + if user.is_anonymous: + raise PermissionDenied("Please login") + if not user.is_staff: return None return self.owner