You are here

public function DrupalOAuth2Client::getAccessToken in OAuth Connector 7

File

modules/oauth2/lib/DrupalOAuth2Client.inc, line 5

Class

DrupalOAuth2Client

Code

public function getAccessToken($endpoint = NULL, $options = array()) {
  if ($this->accessToken) {
    return clone $this->accessToken;
  }
  $options += array(
    'params' => array(),
    'realm' => NULL,
    'get' => FALSE,
  );
  if (empty($endpoint)) {
    if (!empty($this->consumer->configuration['access_endpoint'])) {
      $endpoint = $this->consumer->configuration['access_endpoint'];
    }
    else {
      $endpoint = '/oauth/access_token';
    }
  }
  $response = $this
    ->get($endpoint, array(
    'token' => TRUE,
    'params' => $options['params'],
    'realm' => $options['realm'],
    'get' => $options['get'],
  ));
  $params = array();
  parse_str($response, $params);
  if (empty($params['access_token'])) {
    $params = drupal_json_decode($response);
  }

  // FB doet het weer anders... pff
  if (isset($params['expires'])) {
    $params['expires_in'] = $params['expires'];
  }
  if (empty($params['access_token'])) {
    throw new Exception('No valid access token was returned');
  }

  // Check if we've has recieved this token previously and if so use the old one

  //TODO: Is this safe!? What if eg. multiple users are getting the same access token from the provider?
  $this->accessToken = DrupalOAuthToken::loadByKey($params['access_token'], $this->consumer);
  if (!$this->accessToken) {
    $expires = 0;
    if (isset($params['expires_in']) && $params['expires_in']) {
      $expires = REQUEST_TIME + $params['expires_in'];
    }
    $this->accessToken = new DrupalOAuthToken($params['access_token'], '', $this->consumer, array(
      'type' => OAUTH_COMMON_TOKEN_TYPE_ACCESS,
      'expires' => $expires,
    ));

    // TODO: doe iets met refresh token. $params['refresh_token']
  }
  return clone $this->accessToken;
}