1

My scheme is simple. Model is custom user from django.

class UserFilter(django_filters.FilterSet):
    class Meta:
        model = User
        fields = ['username', 'email', ]

class UserNode(DjangoObjectType):
    class Meta:
        model = User
        only_fields = (
            'username',
            'email',
            'is_staff',
            'is_active',
            'is_superuser',
            'last_login',
            'date_joined',
            'profile',
        )
        interfaces = (graphene.relay.Node, )

    @classmethod
    def get_node(cls, info, id):
        try:
            user = cls._meta.model.objects.get(id=id)
        except cls._meta.model.DoesNotExist:
            return None

        if user:
            return user
        return None

class Query(graphene.ObjectType):
   users = DjangoFilterConnectionField(
        UserNode,
        filterset_class=UserFilter,
    )
def resolve_users(self, info):
        user = info.context.user
        if user.is_anonymous:
            raise Exception('You aren't autorized')
        elif not user.is_superuser:
            return get_user_model().objects.defer("email")
        elif user.is_superuser:
            return get_user_model().objects.all().select_related('profile')
        else:
            raise Exception('Error')

When I make a request from a user who is not superuser, and in the schema I specify the field "email", the answer gives the value of this field.:

query{
    users{
        edges{
            node{
                id
                username
                email
                isSuperuser
            }
        }
    }
}

I get:

{
    "data": {
        "users": {
            "edges": [
{
                    "node": {
                        "id": "VXNlck5vZGU6NQ==",
                        "username": "Test4",
                        "email": "Test4@test.ru",
                        "isSuperuser": false
                    }
                }
            ]
        }
    }
}

Whether it is possible as that to differentiate access to fields in resolve_users? The exception in the filter does not work. Perhaps I do not correctly understand the design of the DjangoFilterConnectionField, and I should use the usual list for output to the GraphQL.

  • Have a look at https://stackoverflow.com/questions/49084322/how-to-limit-field-access-on-a-model-based-on-user-type-on-graphene-django/49283138#49283138 which may be what you need. – Mark Chackerian Jul 10 '18 at 14:18
  • This solution is not straightforward, and it suggests writing a code to work with permissions. I do not quite understand how to make the field read limit, so that any user sees his email, but the rest were not available to him. I suppose that one of the ways of solution lies through the use of the serializer. – Антон Игоревич Воробьев Jul 11 '18 at 04:06

0 Answers0