You are here

public function KeyAuth::generateKey in Key auth 8

Generate a new unique key.

Return value

string An API key.

Overrides KeyAuthInterface::generateKey

File

src/KeyAuth.php, line 118

Class

KeyAuth
Class KeyAuth.

Namespace

Drupal\key_auth

Code

public function generateKey() {

  // Determine the key length.
  $length = $this->config
    ->get('key_length');

  // Load user storage.
  $storage = $this->entityTypeManager
    ->getStorage('user');
  do {

    // Generate a key.
    $key = substr(bin2hex(random_bytes($length)), 0, $length);

    // Query to see if this key is in use.
    $in_use = $storage
      ->getQuery()
      ->condition('api_key', $key)
      ->execute();
  } while ($in_use);
  return $key;
}