0

如何要求对下面的tier节点字段和allTiers连接字段查询进行身份验证/授权?

# schema.py
class TierNode(DjangoObjectType):
    class Meta:
        model = Tier
        filter_fields = []
        interfaces = (graphene.relay.Node,)


class Query(graphene.ObjectType):
    tier = relay.Node.Field(TierNode)
    all_tiers = DjangoFilterConnectionField(TierNode)
4

2 回答 2

0

您可以像这样定义授权或/和身份验证装饰器:

from functools import wraps

def authorize_required(role):
    def decorator(func):
        @wraps(func)
        def wrapper(instance, info, *args, **kwargs):
            current_user = info.context.user
            if not current_user.is_authenticated:
                raise Exception("Authentication credentials were not provided")
            if not authorize(instance, current_user, role):
                raise Exception(
                    f"{current_user} has no access to {instance} with required {role=}"
                )
            return func(instance, info, *args, **kwargs)
        return wrapper
    return decorator

def authorize(instance, user, role) -> bool:
   # check if user can have access to instance
   # if there is requirement to have certain role

并在模式定义中使用它:

class TierNode(DjangoObjectType):
    class Meta:
        model = Tier
        filter_fields = []
        interfaces = (graphene.relay.Node,)


class Query(graphene.ObjectType):
    tier = relay.Node.Field(TierNode)
    all_tiers = DjangoFilterConnectionField(TierNode)
  
    @authorize_required('user')
    def resolve_tier(self, info, **args):
        # some resolve code

    @authorize_required('admin')
    def resolve_all_tiers(self, info, **args):
        # some resolve code
于 2021-12-06T21:55:10.607 回答
0

您可以使用 auth 装饰器为这些字段定义解析器,如下所示:

from graphql_jwt.decorators import login_required

class Query(graphene.ObjectType):
    tier = relay.Node.Field(TierNode)
    all_tiers = DjangoFilterConnectionField(TierNode)


    @login_required
    def resolve_tier(root, info, **kwargs):
        # code for resolving here

这只是使用login_decorator附带的,graphql_jwt但如果您定义它们,它也适用于您的自定义装饰器。

此外,这也适用于您解析以下字段时TierNode

class TierNode(DjangoObjectType):
    class Meta:
        model = Tier
        filter_fields = []
        interfaces = (graphene.relay.Node,)

    some_property = graphene.Field("types.SomePropertyType")

    @login_required
    def resolve_some_property(root, info, **kwargs):
        # code for resolving here

于 2021-09-16T07:57:38.250 回答