You are here

public function RefreshInstagramTokenAction::access in Instagram Feeds 8

Checks object access.

Parameters

mixed $object: The object to execute the action on.

\Drupal\Core\Session\AccountInterface $account: (optional) The user for which to check access, or NULL to check access for the current user. Defaults to NULL.

bool $return_as_object: (optional) Defaults to FALSE.

Return value

bool|\Drupal\Core\Access\AccessResultInterface The access result. Returns a boolean if $return_as_object is FALSE (this is the default) and otherwise an AccessResultInterface object. When a boolean is returned, the result of AccessInterface::isAllowed() is returned, i.e. TRUE means access is explicitly allowed, FALSE means access is either explicitly forbidden or "no opinion".

Overrides ActionInterface::access

File

src/Plugin/Action/RefreshInstagramTokenAction.php, line 90

Class

RefreshInstagramTokenAction
Provides an action that can refresh Instagram Token for an entity.

Namespace

Drupal\instagram_feeds\Plugin\Action

Code

public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {

  /** @var \Drupal\instagram_feeds\Entity\InstagramAccountInterface $object */
  if (!$account) {
    $account = \Drupal::currentUser();
  }

  // Token is invalid or entity is unpublished.
  if (!$object
    ->isPublished() || !$object
    ->tokenIsValid()) {
    $result = AccessResult::forbidden('Unpublished or Instagram token is invalid.')
      ->addCacheableDependency($object);
    return $return_as_object ? $result : $result
      ->isAllowed();
  }
  $primary_access = $account
    ->hasPermission('administer instagram_feeds');
  $role_access = $primary_access || $account
    ->hasPermission('update instagram_account');
  $user_access = $role_access || $account
    ->id() == $object
    ->getOwnerId() && $account
    ->hasPermission('update own instagram_account');

  // User doesn't have access.
  if (!$user_access) {
    $result = AccessResult::forbidden()
      ->cachePerPermissions();
    return $return_as_object ? $result : $result
      ->isAllowed();
  }

  // Token can be refreshed only after 24h. It lives 60 days. Expired token
  // cannot be refreshed anymore. 60 days - 1 day = 59 days = 5097600 sec.
  $age = $object
    ->getTokenExpirationTime() - $this->time
    ->getRequestTime();
  if ($age <= 5097600) {
    $result = AccessResult::allowed()
      ->setCacheMaxAge($age)
      ->cachePerPermissions()
      ->addCacheableDependency($object);
    return $return_as_object ? $result : $result
      ->isAllowed();
  }
  $age -= 5097600;
  $result = AccessResult::forbidden('You should wait at least 24 hours prior previous token refesh')
    ->setCacheMaxAge($age)
    ->cachePerPermissions();
  return $return_as_object ? $result : $result
    ->isAllowed();
}