AuthenticationByUser.php in CMS Content Sync 2.0.x
File
src/Controller/AuthenticationByUser.php
View source
<?php
namespace Drupal\cms_content_sync\Controller;
use Drupal\Core\KeyValueStore\KeyValueDatabaseFactory;
use Drupal\encrypt\Entity\EncryptionProfile;
use Drupal\user\Entity\User;
use Drupal\user\UserDataInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AuthenticationByUser {
public const KEY_USERNAME = 'userName';
public const KEY_PASSWORD = 'userPass';
protected $keyValueDatabase;
protected $userData;
public function __construct(KeyValueDatabaseFactory $key_value_database, UserDataInterface $user_data) {
$this->keyValueDatabase = $key_value_database;
$this->userData = $user_data;
}
public static function getInstance() {
static $instance = null;
if ($instance) {
return $instance;
}
return $instance = self::createInstance(\Drupal::getContainer());
}
public static function createInstance(ContainerInterface $container) {
return new static($container
->get('keyvalue.database'), $container
->get('user.data'));
}
public function getLoginData() {
static $loginData = null;
if (!empty($loginData)) {
return $loginData;
}
$user = User::load(CMS_CONTENT_SYNC_USER_ID);
if (is_null(CMS_CONTENT_SYNC_USER_ID)) {
$user = User::load($this->keyValueDatabase
->get('cms_content_sync_user')
->get('uid'));
}
if (!$user) {
throw new \Exception("Content Sync User not found. Encrypted data can't be read or saved.");
}
$loginData = $this->userData
->get('cms_content_sync', $user
->id(), 'sync_data');
if (!$loginData) {
throw new \Exception('No credentials for sync user found.');
}
$encryption_profile = EncryptionProfile::load(CMS_CONTENT_SYNC_ENCRYPTION_PROFILE_NAME);
foreach ($loginData as $key => $value) {
$loginData[$key] = \Drupal::service('encryption')
->decrypt($value, $encryption_profile);
}
return $loginData;
}
public function getUsername() {
return $this
->getLoginData()[self::KEY_USERNAME];
}
public function getPassword() {
return $this
->getLoginData()[self::KEY_PASSWORD];
}
}