x-graphql/field-guard

管理对象字段的访问控制

0.2.0 2024-04-17 02:48 UTC

This package is auto-updated.

Last update: 2024-09-17 03:37:36 UTC


README

中间件,用于向GraphQL模式添加安全层

unit tests codecov

入门指南

通过Composer安装此包

composer require x-graphql/field-guard

用法

创建权限数组,映射对象类型名称及其字段与规则,规则可以是布尔值或XGraphQL\FieldGuard\RuleInterface的实例

use GraphQL\Type\Definition\ResolveInfo;
use XGraphQL\FieldGuard\RuleInterface;

$isAdminRule = new class implements RuleInterface {
    public function allows(mixed $value, array $args, mixed $context, ResolveInfo $info) : bool{
        return $context->isAdmin();
    }
    
    public function shouldRemember(mixed $value,array $args,mixed $context,ResolveInfo $info) : bool{
        return true;
    }
};

$permissions = [
    'Query' => [
        'getUser' => true, /// all user can get user.
        'getBook' => false, /// deny all user to get book.
    ],
    'Mutation' => [
        'createUser' => $isAdminRule, /// only admin user can create user.
    ]   
];

然后使用上面的$permissions创建中间件并将其应用于模式

use XGraphQL\FieldMiddleware\FieldMiddleware;
use XGraphQL\FieldGuard\FieldGuardMiddleware;

$schema = ...
$guardMiddleware = new FieldGuardMiddleware($permissions);

FieldMiddleware::apply($schema, [$guardMiddleware]);

致谢

Minh Vuong创建