You are here

public function MoxtraConnector::getToken in Opigno Moxtra 3.x

Same name and namespace in other branches
  1. 8 src/MoxtraConnector.php \Drupal\opigno_moxtra\MoxtraConnector::getToken()

Build Moxtra access token.

Return value

string

File

src/MoxtraConnector.php, line 159

Class

MoxtraConnector

Namespace

Drupal\opigno_moxtra

Code

public function getToken($uid = NULL, $force = FALSE) {
  $account = empty($uid) ? \Drupal::currentUser() : User::load($uid);
  $token = \Drupal::cache()
    ->get('moxtra_access_token_' . $account
    ->id());
  if (!empty($token->data) && !$force) {
    return $token->data;
  }
  $data = $this->settings;

  // For users on Moxtra not possible to change user Role or Remove user.
  // So for user with different roles we will create different Moxtra users.
  $prefix = $this
    ->prefix($account);

  // For admin user we will use admin on Moxtra.
  if ($uid != 1) {
    unset($data['email']);
    $data['unique_id'] = $prefix . $account
      ->id();
  }
  $url = $this->url . '/v1/core/oauth/token';
  $responce = $this
    ->request($url, $data);
  if (empty($responce['error']) && !empty($responce['access_token'])) {

    // Save Moxtra token for the next hour.
    \Drupal::cache()
      ->set('moxtra_access_token_' . $account
      ->id(), $responce['access_token'], time() + 3600);
    if ($force) {
      \Drupal::logger('Moxtra')
        ->notice($this
        ->t('New token has force generated @token', [
        '@token' => $responce['access_token'],
      ]));
    }
    return $responce['access_token'];
  }
  else {
    \Drupal::cache()
      ->set('moxtra_access_token', NULL, 0);
    return '';
  }
}