How can we filter what entries are returned by a GraphQL query so that users cannot see entries authored by other people?
For example, Editors can access everything but Writers can only access their own entries.
You can do this using a custom module that adds an authorId
condition to element queries, for graphql/api
requests.
use Craft;
use craft\elements\db\EntryQuery;
use yii\base\Event;
use yii\web\ForbiddenHttpException;
// ...
// Is this a GraphQL request?
if (Craft::$app->request->getActionSegments() == ['graphql', 'api']) {
Event::on(EntryQuery::class, EntryQuery::EVENT_BEFORE_PREPARE, function(Event $event) {
// Get the current user
$user = Craft::$app->user->identity;
// If no one is logged in, return a 403 error
if (!$user) {
throw new ForbiddenHttpException();
}
// Only Editors are allowed to see everything
if (!$user->isInGroup('editors')) {
/** @var EntryQuery $query */
$query = $event->sender;
$query->subQuery->andWhere(['authorId' => $user->id]);
}
});
}
Note: Since the results will start changing for the same element query depending on who is logged in, you’ll also need to disable the enableGraphQlCaching config setting.
enableGraphQlCaching
before Craft CMS 3.7 and enableGraphqlCaching
after Craft CMS 3.7
Commented
Aug 23, 2021 at 17:48