Instead of a Drupal 7 hook you can use the new AccountEvents::SET_USER event:
/src/EventSubscriber/SetAccountSubscriber.php
<?php
namespace Drupal\mymodule\EventSubscriber;
use Drupal\Core\Session\AccountEvents;
use Drupal\Core\Session\AccountSetEvent;
use Drupal\Core\Session\UserSession;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* mymodule event subscriber.
*/
class SetAccountSubscriber implements EventSubscriberInterface {
/**
* Account set event handler.
*
* @param Drupal\Core\Session\AccountSetEvent $event
* Account set event.
*/
public function onAccountSet(AccountSetEvent $event) {
$account = $event->getAccount();
if ($account->isAuthenticated()) {
$roles = $account->getRoles();
if (in_array('administrator', $roles)) {
$roles = array_values(array_diff($roles, ['administrator']));
$account = new UserSession([
'uid' => $account->id(),
'access' => $account->getLastAccessedTime(),
'roles' => $roles,
'name' => $account->getAccountName(),
'preferred_langcode' => $account->getPreferredLangcode(),
'preferred_admin_langcode' => $account->getPreferredAdminLangcode(),
'mail' => $account->getEmail(),
'timezone' => $account->getTimeZone(),
]);
\Drupal::currentUser()->setAccount($account);
}
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
AccountEvents::SET_USER => ['onAccountSet'],
];
}
}
mymodule.services.yml
services:
mymodule.set_account_subscriber:
class: Drupal\mymodule\EventSubscriber\SetAccountSubscriber
tags:
- { name: event_subscriber }
Be careful to avoid an infinite loop. The last line dispatches the event again and you need a condition preventing the line to be executed a second time, in this case through the removed role.