SamlauthUserSyncSubscriber.php in Acquia Cloud Site Factory Connector 8.2
File
acsf_sso/src/EventSubscriber/SamlauthUserSyncSubscriber.php
View source
<?php
namespace Drupal\acsf_sso\EventSubscriber;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\samlauth\Event\SamlauthEvents;
use Drupal\samlauth\Event\SamlauthUserSyncEvent;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SamlauthUserSyncSubscriber implements EventSubscriberInterface {
const ATTRIBUTE_NAME_ROLES = 'roles';
const ATTRIBUTE_NAME_IS_OWNER = 'is_owner';
protected $entityTypeManager;
protected $messenger;
protected $logger;
public function __construct(EntityTypeManagerInterface $entity_type_manager, MessengerInterface $messenger, LoggerInterface $logger) {
$this->entityTypeManager = $entity_type_manager;
$this->messenger = $messenger;
$this->logger = $logger;
}
public static function getSubscribedEvents() {
return [
SamlauthEvents::USER_SYNC => 'onUserSync',
];
}
public function onUserSync(SamlauthUserSyncEvent $event) {
$attributes = $event
->getAttributes();
$add_role_machine_names = [];
if (!empty($attributes[static::ATTRIBUTE_NAME_ROLES])) {
foreach ($attributes[static::ATTRIBUTE_NAME_ROLES] as $role_name) {
$add_role_machine_names[] = str_replace(' ', '_', strtolower($role_name));
}
}
if (!empty($attributes[static::ATTRIBUTE_NAME_IS_OWNER])) {
$admin_roles = $this->entityTypeManager
->getStorage('user_role')
->getQuery()
->condition('is_admin', TRUE)
->execute();
$add_role_machine_names[] = reset($admin_roles);
}
$account = $event
->getAccount();
foreach (array_unique($add_role_machine_names) as $role_machine_name) {
if (!$account
->hasRole($role_machine_name) && !in_array($role_machine_name, [
RoleInterface::AUTHENTICATED_ID,
RoleInterface::ANONYMOUS_ID,
])) {
if ($role = Role::load($role_machine_name)) {
$account
->addRole($role_machine_name);
$event
->markAccountChanged();
$this->messenger
->addStatus(t('Site Factory assigned the "@role_name" role to the account.', [
'@role_name' => $role
->label(),
]));
$this->logger
->notice('Site Factory assigned the "@role" role to the account.', [
'@role' => $role_machine_name,
]);
}
elseif (!$role) {
$this->messenger
->addWarning(t('Automatic role assignment failed because the website does not have a "@role_name" role.', [
'@role_name' => $role_machine_name,
]));
}
}
}
}
}