繁体   English   中英

如何仅向 graphene-django 中的用户个人资料所有者显示特定字段?

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

我的graphene-django应用程序中有以下模式:

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")


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:
            # If the query didn't access email field -> query is ok
            # If the query tried to access email field -> raise an error
        else:
            # Logged in as the user we're querying -> let the query access all the fields

我希望能够通过以下方式查询架构:

# Logged in as user 1 => no errors, because we're allowed to see all fields
query {
  user (userId: 1) {
    id
    username
    email
  }
}

# Not logged in as user 1 => no errors, because not trying to see email
query {
  user (userId: 1) {
    id
    username
  }
}

# Not logged in as user 1 => return error because accessing email
query {
  user (userId: 1) {
    id
    username
    email
  }
}

我怎样才能做到只有登录用户才能看到自己个人资料的email字段,而其他人不能看到其他人的电子邮件?

这是我根据评论采取的方法。 这里的主要问题是能够获得解析器中查询请求的字段列表。 为此,我使用了改编自此处的代码:

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

rest 应该非常简单:

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

我最终只是这样做了,其中查询自己的信息时返回email的实际值,而其他人则返回None

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)

当前的答案太复杂了。 只需创建两个 ObjectType,例如:

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

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

花了 4 个多小时尝试其他解决方案才意识到原来如此简单

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM