PasswordPolicyEventSubscriber.php in Password Policy 8.3
File
src/EventSubscriber/PasswordPolicyEventSubscriber.php
View source
<?php
namespace Drupal\password_policy\EventSubscriber;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
class PasswordPolicyEventSubscriber implements EventSubscriberInterface {
use StringTranslationTrait;
protected $currentUser;
protected $messenger;
protected $userStorage;
protected $request;
public function __construct(AccountProxyInterface $currentUser, EntityTypeManagerInterface $entityTypeManager, MessengerInterface $messenger, RequestStack $requestStack) {
$this->currentUser = $currentUser;
$this->messenger = $messenger;
$this->request = $requestStack
->getCurrentRequest();
$this->userStorage = $entityTypeManager
->getStorage('user');
}
public function checkForUserPasswordExpiration(GetResponseEvent $event) {
$route_name = $this->request->attributes
->get(RouteObjectInterface::ROUTE_NAME);
$ignore_route = in_array($route_name, [
'entity.user.edit_form',
'system.ajax',
'user.logout',
'admin_toolbar_tools.flush',
]);
if (strpos($route_name, 'jsonapi') !== FALSE) {
return;
}
if ($this->currentUser
->isAuthenticated()) {
$user = $this->userStorage
->load($this->currentUser
->id());
$is_ajax = $this->request->headers
->get('X_REQUESTED_WITH') === 'XMLHttpRequest';
$user_expired = FALSE;
if ($user && $user
->hasField('field_password_expiration') && $user
->get('field_password_expiration')
->get(0)) {
$user_expired = $user
->get('field_password_expiration')
->get(0)
->getValue();
$user_expired = $user_expired['value'];
}
if ($user_expired && !$ignore_route && !$is_ajax) {
$url = new Url('entity.user.edit_form', [
'user' => $user
->id(),
]);
$url = $url
->setAbsolute()
->toString();
$event
->setResponse(new RedirectResponse($url));
$this->messenger
->addError($this
->t('Your password has expired, please update it'));
}
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = [
'checkForUserPasswordExpiration',
];
return $events;
}
}