[Django]-How to show specific field only to the user profile owner in graphene-django?

1πŸ‘

βœ…

I ended up just doing it like this, where the actual value of email is returned when querying one’s own info, and None is returned for others:

import graphene
from django.contrib.auth import get_user_model
from graphene_django import DjangoObjectType


class UserType(DjangoObjectType):
    class Meta:
        model = get_user_model()
        fields = ("id", "username", "email")

    def resolve_email(self, info):
        if info.context.user.is_authenticated and self.pk == info.context.user.pk:
            return self.email
        else:
            return None


class Query(graphene.ObjectType):
    user = graphene.Field(UserType, user_id=graphene.Int())

    def resolve_user(self, info, user_id):
        return get_user_model().objects.get(pk=user_id)
πŸ‘€ruohola

2πŸ‘

Here’s the approach I would take based on the comments. The main issue here is to be able to get a list of fields requested by a query in the resolver. For that, I use a code adapted from here:

def get_requested_fields(info):
    """Get list of fields requested in a query."""
    fragments = info.fragments

    def iterate_field_names(prefix, field):
        name = field.name.value
        if isinstance(field, FragmentSpread):
            results = []
            new_prefix = prefix
            sub_selection = fragments[name].selection_set.selections
        else:
            results = [prefix + name]
            new_prefix = prefix + name + '.'
            sub_selection = \
                field.selection_set.selections if field.selection_set else []
        for sub_field in sub_selection:
            results += iterate_field_names(new_prefix, sub_field)
        return results

    results = iterate_field_names('', info.field_asts[0])
    return results

The rest should be quite straightforward:

import graphene
from django.contrib.auth import get_user_model
from graphene_django import DjangoObjectType


class AuthorizationError(Exception):
    """Authorization failed."""


class UserType(DjangoObjectType):
    class Meta:
        model = get_user_model()
        fields = ("id", "username", "email")


class Query(object):
    user = graphene.Field(UserType, user_id=graphene.Int())

    def resolve_user(self, info, user_id):
        user = get_user_model().objects.get(pk=user_id)
        if info.context.user.id != user_id:
            fields = get_requested_fields(info)
            if 'user.email' in fields:
                raise AuthorizationError('Not authorized to access user email')
        return user

0πŸ‘

The current answer is wayyy overcomplicated. Just create two ObjectTypes e.g.:

class PublicUserType(DjangoObjectType):
    class Meta:
        model = get_user_model()
        fields  = ('id', 'username')

class PrivateUserType(DjangoObjectType):
    class Meta:
        model = get_user_model()

Spent over 4 hours trying other solutions before realized it was this simple

πŸ‘€aaon

Leave a comment