Completed
Pull Request — 8.x-3.x (#525)
by Philipp
02:12
created

QueryAccessCheck   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 55
rs 10
wmc 7
lcom 1
cbo 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B access() 0 25 6
1
<?php
2
3
namespace Drupal\graphql\Access;
4
5
use Drupal\Core\Access\AccessResult;
6
use Drupal\Core\Routing\Access\AccessInterface;
7
use Drupal\Core\Session\AccountInterface;
8
use Symfony\Component\HttpFoundation\RequestStack;
9
10
class QueryAccessCheck implements AccessInterface {
11
12
  /**
13
   * The request stack.
14
   *
15
   * @var \Symfony\Component\HttpFoundation\RequestStack
16
   */
17
  protected $requestStack;
18
19
  /**
20
   * QueryAccessCheck constructor.
21
   *
22
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
23
   *   The request stack.
24
   */
25
  public function __construct(RequestStack $requestStack) {
26
    $this->requestStack = $requestStack;
27
  }
28
29
  /**
30
   * Checks access.
31
   *
32
   * @param \Drupal\Core\Session\AccountInterface $account
33
   *   The currently logged in account.
34
   *
35
   * @return \Drupal\Core\Access\AccessResultInterface
36
   *   The access result.
37
   */
38
  public function access(AccountInterface $account) {
39
    // If the user has the global permission to execute any query, let them.
40
    if ($account->hasPermission('execute graphql requests')) {
41
      return AccessResult::allowed();
42
    }
43
44
    $request = $this->requestStack->getCurrentRequest();
45
    /** @var \GraphQL\Server\OperationParams[] $operations */
46
    if (!$operations = $request->attributes->get('operations', [])) {
47
      return AccessResult::forbidden();
48
    }
49
50
    $operations = is_array($operations) ? $operations : [$operations];
51
    foreach ($operations as $operation) {
52
      // If a query was provided by the user, this is an arbitrary query (it's
53
      // not a persisted query). Hence, we only grant access if the user has the
54
      // permission to execute any query.
55
      if ($operation->getOriginalInput('query')) {
56
        return AccessResult::allowedIfHasPermission($account, 'execute graphql requests');
57
      }
58
    }
59
60
    // If we reach this point, this is a persisted query.
61
    return AccessResult::allowedIfHasPermission($account, 'execute persisted graphql requests');
62
  }
63
64
}
65