You are here

public function TokenManager::createNewTokenForUser in Persistent Login 8

Create a new token for the specified user.

Parameters

int $uid: The user id to associate the token to.

Return value

PersistentToken A new PersistentToken object.

File

src/TokenManager.php, line 126

Class

TokenManager
Class TokenManager.

Namespace

Drupal\persistent_login

Code

public function createNewTokenForUser($uid) {
  $config = $this->configFactory
    ->get('persistent_login.settings');
  $token = new PersistentToken($this->csrfToken
    ->get(Crypt::randomBytesBase64()), $this->csrfToken
    ->get(Crypt::randomBytesBase64()), $uid);
  if ($config
    ->get('lifetime') === 0) {
    $token
      ->setExpiry(new DateTime("@" . 2147483647));
  }
  else {
    $token
      ->setExpiry(new DateTime("now +" . $config
      ->get('lifetime') . " day"));
  }
  try {
    $this->connection
      ->insert('persistent_login')
      ->fields([
      'uid' => $uid,
      'series' => $token
        ->getSeries(),
      'instance' => $token
        ->getInstance(),
      'created' => $token
        ->getCreated()
        ->getTimestamp(),
      'refreshed' => $token
        ->getRefreshed()
        ->getTimestamp(),
      'expires' => $token
        ->getExpiry()
        ->getTimestamp(),
    ])
      ->execute();
  } catch (\Exception $e) {
    throw new TokenException("An error occurred storing the new token", 0, $e);
  }

  // Check for exceeding the maximum tokens per user.
  if ($config
    ->get('max_tokens') !== 0) {
    try {
      $oldTokensResult = $this->connection
        ->select('persistent_login', 'pl')
        ->fields('pl', [
        'created',
        'expires',
      ])
        ->orderBy('expires', 'DESC')
        ->orderBy('created', 'DESC')
        ->condition('uid', $uid)
        ->range($config
        ->get('max_tokens'), 1)
        ->execute();
      if ($oldestToken = $oldTokensResult
        ->fetchObject()) {
        $this->connection
          ->delete('persistent_login')
          ->condition('uid', $uid)
          ->condition('expires', $oldestToken->expires, '<=')
          ->condition('created', $oldestToken->created, '<=')
          ->execute();
      }
    } catch (\Exception $e) {
      $this->logger
        ->error('Unable to delete extra persistent tokens for user with uid @uid', [
        '@uid' => $uid,
      ]);
    }
  }
  return $token;
}