You are here

public function BynderApi::hasAccessToken in Bynder 4.0.x

Same name and namespace in other branches
  1. 8.3 src/BynderApi.php \Drupal\bynder\BynderApi::hasAccessToken()
  2. 8 src/BynderApi.php \Drupal\bynder\BynderApi::hasAccessToken()
  3. 8.2 src/BynderApi.php \Drupal\bynder\BynderApi::hasAccessToken()

Gets if the current user has a valid oAuth access token.

Return value

bool TRUE if the current user has a valid oAuth access token. FALSE otherwise.

Overrides BynderApiInterface::hasAccessToken

1 method overrides BynderApi::hasAccessToken()
BynderApiTest::hasAccessToken in tests/modules/bynder_test_module/src/BynderApiTest.php
Returns value set in state.

File

src/BynderApi.php, line 198

Class

BynderApi
Bynder API service.

Namespace

Drupal\bynder

Code

public function hasAccessToken() {
  $session_data = $this->session
    ->get('bynder', []);

  // Required tokens need to be stored in the session.
  if (empty($session_data['access_token']) || !$session_data['access_token'] instanceof AccessToken) {
    return FALSE;
  }

  // In case of the global config change all user sessions need to expire.
  if (empty($session_data['config_hash']) || $session_data['config_hash'] != $this->state
    ->get('bynder_config_hash')) {
    return FALSE;
  }

  // Check if the token has expired, attempt to refresh it.
  if ($session_data['access_token']
    ->getExpires() < $this->time
    ->getCurrentTime()) {
    try {

      // Trigger an API request.
      $this
        ->hasUploadPermissions();
      if ($this->bynderConfiguration instanceof \Bynder\Api\Impl\OAuth2\Configuration) {

        // The updated access token might not have a refresh token, use the
        // existing one.
        $options = $this->bynderConfiguration
          ->getToken()
          ->jsonSerialize();
        if (empty($data['refresh_token'])) {
          $options['refresh_token'] = $session_data['access_token']
            ->getRefreshToken();
        }
        $session_data['access_token'] = new AccessToken($options);
        $this->session
          ->set('bynder', $session_data);
        return TRUE;
      }
      else {

        // Failed to refresh, user needs to log in again.
        $this->session
          ->set('bynder', []);
      }
    } catch (\Exception $e) {

      // Failed to refresh, user needs to log in again.
      $this->session
        ->set('bynder', []);
    }
    return FALSE;
  }
  return TRUE;
}