您可以像这样定义授权或/和身份验证装饰器:
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