【发布时间】:2020-02-07 21:11:12
【问题描述】:
我的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字段,而其他人不能看到其他人的电子邮件?
【问题讨论】:
-
看一下石墨烯中间件的authorization example。
-
@TomasLinhart 我已经经历过很多次了,但我不知道该怎么做。
-
你说得对,在这种情况下使用授权中间件可能有点多余。但是,解决方案取决于您是要返回没有
email字段的用户对象(由第一个代码块建议)还是引发错误(由第二个代码块建议)。如果是前者,只需在if info.context.user.id != user_id:分支中执行user['email'] = None或del user['email']。如果是后者,请在此处引发异常。 -
@TomášLinhart 我稍微编辑了我的 graphql 和 python cmets。如果查询正在访问电子邮件并且未登录到用户,我只想引发错误。您介意将您的评论扩展到答案吗?
标签: python django graphql graphene-django