View source
<?php
namespace Drupal\key_auth;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\user\UserInterface;
class KeyAuth implements KeyAuthInterface {
const DETECTION_METHOD_HEADER = 'header';
const DETECTION_METHOD_QUERY = 'query';
protected $config;
protected $entityTypeManager;
public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager) {
$this->config = $config_factory
->get('key_auth.settings');
$this->entityTypeManager = $entity_type_manager;
}
public function getKey(Request $request) {
$methods = $this->config
->get('detection_methods');
$param_name = $this->config
->get('param_name');
if (in_array(self::DETECTION_METHOD_HEADER, $methods)) {
if ($key = $request->headers
->get($param_name)) {
return $key;
}
}
if (in_array(self::DETECTION_METHOD_QUERY, $methods)) {
if ($key = $request->query
->get($param_name)) {
return $key;
}
}
return FALSE;
}
public function getUserByKey($key) {
$storage = $this->entityTypeManager
->getStorage('user');
$user = $storage
->getQuery()
->condition('api_key', $key)
->execute();
if ($user) {
return $storage
->load(reset($user));
}
return NULL;
}
public function access(UserInterface $user) {
return $user
->hasPermission('use key authentication');
}
public function generateKey() {
$length = $this->config
->get('key_length');
$storage = $this->entityTypeManager
->getStorage('user');
do {
$key = substr(bin2hex(random_bytes($length)), 0, $length);
$in_use = $storage
->getQuery()
->condition('api_key', $key)
->execute();
} while ($in_use);
return $key;
}
}