我想保护内容类型的某些特定字段,只允许管理员用户修改值,但允许用户访问它。
例如,想象一下User
带有is_admin
字段的类型。只有管理员应该能够更新它,但每个人都应该能够阅读它。
type User {
id: ID!
name: String!
email: String!
is_admin: Boolean!
}
can指令似乎不适用于突变中的字段。起初我尝试@can(ability: "setAdmin")
使用自定义策略添加,但没有任何效果。用于突变的相同罐头/策略“有效”,但这还不够细化。
似乎使用自定义指令的自定义字段限制应该有所帮助,但这似乎也不适用于突变输入类型的字段级别。
type mutation {
updateUser(
input: UpdateUserInput! @spread
): User @update @middleware(checks: ["auth:api"])
}
input UpdateUserInput {
id: ID!
name: String!
email: String!
is_admin: Boolean! @adminOnly
}
有了这个自定义指令app/GraphQL/Directives/AdminOnlyDirective.php
<?php
namespace App\GraphQL\Directives;
use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Exceptions\DefinitionException;
use Nuwave\Lighthouse\Schema\Directives\BaseDirective;
use Nuwave\Lighthouse\Schema\Values\FieldValue;
use Nuwave\Lighthouse\Support\Contracts\DefinedDirective;
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class AdminOnlyDirective extends BaseDirective implements FieldMiddleware, DefinedDirective
{
/**
* Name of the directive as used in the schema.
*
* @return string
*/
public function name(): string
{
return 'adminOnly';
}
public static function definition(): string
{
return /** @lang GraphQL */ <<<GRAPHQL
"""
Limit field update to only admin.
"""
directive @adminOnly() on FIELD_DEFINITION
GRAPHQL;
}
public function handleField(FieldValue $fieldValue, Closure $next): FieldValue
{
$originalResolver = $fieldValue->getResolver();
return $next(
$fieldValue->setResolver(
function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($originalResolver) {
$user = $context->user();
if (
// Unauthenticated users don't get to see anything
! $user
// The user's role has to match have the required role
|| !$user->is_admin
) {
return null;
}
return $originalResolver($root, $args, $context, $resolveInfo);
}
)
);
}
}
那么,有没有办法防止使用 laravel lighthouse 对特定字段进行“更新”?