2

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.

6

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.

1
  • Make sure you are using the correct config name for your Craft version: enableGraphQlCaching before Craft CMS 3.7 and enableGraphqlCaching after Craft CMS 3.7 Aug 23 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.