UsersJwtKeyRepository.php in JSON Web Token Authentication (JWT) 8
File
modules/users_jwt/src/UsersJwtKeyRepository.php
View source
<?php
namespace Drupal\users_jwt;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\user\UserDataInterface;
class UsersJwtKeyRepository implements UsersJwtKeyRepositoryInterface {
use StringTranslationTrait;
protected $userData;
protected $keyCache;
protected $cacheTagsInvalidator;
protected $options = [];
public function __construct(UserDataInterface $user_data, CacheBackendInterface $key_memory_cache, CacheTagsInvalidatorInterface $cache_tags_invalidator) {
$this->userData = $user_data;
$this->keyCache = $key_memory_cache;
$this->cacheTagsInvalidator = $cache_tags_invalidator;
}
public function getKey($id) : ?UsersKey {
$cached = $this->keyCache
->get($id);
if ($cached) {
$key = $cached->data;
}
else {
$keys = $this->userData
->get('users_jwt', NULL, $id);
if (empty($keys) || count($keys) > 1) {
$key = NULL;
}
else {
$key = end($keys);
}
$this->keyCache
->set($id, $key);
}
return $key;
}
public function saveKey($uid, $id, $alg, $pubkey) : UsersKey {
if (empty($id)) {
throw new \InvalidArgumentException("Key ID '{$id}' is empty");
}
$keys = $this->userData
->get('users_jwt', NULL, $id);
foreach ($keys as $key_uid => $key_data) {
if ($key_uid !== $uid) {
throw new \InvalidArgumentException("Key ID '{$id}' is already in use by user with uid {$key_uid}");
}
}
$key = new UsersKey($uid, $id, $alg, $pubkey);
$this->userData
->set('users_jwt', $uid, $id, $key);
$this->keyCache
->delete($id);
$this->cacheTagsInvalidator
->invalidateTags([
'users_jwt:' . $uid,
]);
return $key;
}
public function deleteKey($id) {
$keys = $this->userData
->get('users_jwt', NULL, $id);
if ($keys) {
$this->userData
->delete('users_jwt', NULL, $id);
$cache_tags = [];
foreach ($keys as $key_uid => $key_data) {
$cache_tags[] = 'users_jwt:' . $key_uid;
}
$this->cacheTagsInvalidator
->invalidateTags($cache_tags);
}
}
public function deleteUsersKeys($uid) {
$this->userData
->delete('users_jwt', $uid);
$this->cacheTagsInvalidator
->invalidateTags([
'users_jwt:' . $uid,
]);
}
public function getUsersKeys($uid) : array {
return $this->userData
->get('users_jwt', $uid);
}
public function algorithmOptions() : array {
if (empty($this->options)) {
$this->options['RS256'] = $this
->t('RSA (2048 bits or more)');
}
return $this->options;
}
public function offsetExists($offset) {
return (bool) $this
->getKey($offset);
}
public function offsetGet($offset) {
$key = $this
->getKey($offset);
return $key ? $key->pubkey : NULL;
}
public function offsetSet($offset, $value) {
}
public function offsetUnset($offset) {
}
}