我不能 100% 理解您的问题。有两种情况:
- 您想要保护根查询/变异字段。为此,您可以使用 laravel 策略和
@can 指令。像这样:
type Query {
protectedPost(postId: ID! @eq): Post @find @can(ability: "view", find: "id")
}
在你的PostPolicy:
class PostPolicy
{
//...
public function view(User $user, Post $post)
{
// check if use has access to data
if ($post->author_id === $user->id || $user->role === UserRole::Admin) {
return true;
}
return false;
}
}
别忘了将你的策略注册到模型中。
- 您想保护您的类型的部分字段。例如。你有一个
Post 类型,比如
type Post {
id: ID!
secretAdminComment: String
}
你想保护secretAdminComment。这似乎有点棘手,但通常您可以使用@can 指令代码并以您需要的方式对其进行扩展。主要逻辑是 - 如果用户能够访问 - 使用常规字段解析器,如果不能 - 返回 null。我会给你一个例子,说明我是如何为我的应用程序实现它的。在我的应用中,用户可能有多个角色。也可以从当前/嵌套字段(或 laravel 中的模型)传递用户 ID 以检查授权用户。
namespace App\GraphQL\Directives;
use App\Enums\UserRole;
use App\User;
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 CanAccessDirective extends BaseDirective implements FieldMiddleware, DefinedDirective
{
public static function definition(): string
{
return /** @lang GraphQL */ <<<'SDL'
"""
Checks if user has at least one of the role, or user ID is match the value of path defined in allowForUserIdIn. If there are no matches, returns null instead of regular value
"""
directive @canAccess(
"""
The user roles to check
"""
roles: [String!]
"""
Custom null value
"""
nullValue: Mixed
"""
Define if user assigment should be checked. Currently authanticated user ID will be compared to defined path relative to root.
"""
allowForUserIdIn: String
) on FIELD_DEFINITION
SDL;
}
/**
* @inheritDoc
*/
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) {
$nullValue = $this->directiveArgValue('nullValue', null);
/** @var User $user */
$user = $context->user();
if (!$user) {
return $nullValue;
}
// check role
$allowedRoles = [];
$roles = $this->directiveArgValue('roles', []);
foreach ($roles as $role) {
try {
$allowedRoles[] = UserRole::getValue($role);
} catch (\Exception $e) {
throw new DefinitionException("Defined role '$role' could not be found in UserRole enum! Consider using only defined roles.");
}
}
$allowedViaRole = count(array_intersect($allowedRoles, $user->roles)) > 0;
// check user assignment
$allowForLinkedUser = false;
$allowForUserIdIn = $this->directiveArgValue('allowForUserIdIn');
if ($allowForUserIdIn !== null) {
$compareToUserId = array_reduce(
explode('.', $allowForUserIdIn),
function ($object, $property) {
if ($object === null || !is_object($object) || !(isset($object->$property))) {
return null;
}
return $object->$property;
},
$root
);
$allowForLinkedUser = $user->id === $compareToUserId;
}
if ($allowedViaRole || $allowForLinkedUser) {
return $originalResolver($root, $args, $context, $resolveInfo);
}
return $nullValue;
}
)
);
}
}
以下是该指令的用法,该指令为某些角色提供访问权限:
type Post {
id: ID!
secretAdminComment: String @canAccess(roles: ["Admin", "Moderator"])
}
或授予链接到该字段的用户访问权限。因此,只有 ID 等于 $post->author_id 的用户才能获取该值:
type Post {
id: ID!
author_id: ID!
secretAdminComment: String @canAccess(allowForUserIdIn: "author_id")
}
您还可以组合这两个参数,因此如果用户具有其中一个角色或具有$post->author_id 中定义的 ID,则用户可以访问。
type Post {
id: ID!
author_id: ID!
secretAdminComment: String @canAccess(roles: ["Admin", "Moderator"], allowForUserIdIn: "author_id")
}
您还可以通过nullValue 参数定义自定义空值。
希望能帮到你=)