gpt4 book ai didi

python - 如何在 graphene-django 中仅向用户配置文件所有者显示特定字段?

转载 作者:行者123 更新时间:2023-12-01 00:29:09 24 4
gpt4 key购买 nike

我的 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
}
}

如何才能使只有登录用户才能看到自己个人资料的电子邮件字段,而其他人则看不到其他人的电子邮件?

最佳答案

这是我根据评论采取的方法。这里的主要问题是能够获取解析器中查询请求的字段列表。为此,我使用改编自 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

其余部分应该非常简单:

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

关于python - 如何在 graphene-django 中仅向用户配置文件所有者显示特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58322640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com