src/EventSubscriber/PasswordExpirySubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\Routing\RouterInterface;
  7. use Symfony\Component\Security\Core\Security;
  8. use App\Entity\User;
  9. class PasswordExpirySubscriber implements EventSubscriberInterface
  10. {
  11. private RouterInterface $router;
  12. private Security $security;
  13. public function __construct(Security $security, RouterInterface $router)
  14. {
  15. $this->security = $security;
  16. $this->router = $router;
  17. }
  18. public static function getSubscribedEvents(): array
  19. {
  20. return [
  21. RequestEvent::class => 'onKernelRequest',
  22. ];
  23. }
  24. public function onKernelRequest(RequestEvent $event)
  25. {
  26. if (!$event->isMainRequest()) {
  27. return;
  28. }
  29. $request = $event->getRequest();
  30. $allowedRoutes = [
  31. 'app_change_password',
  32. 'app_logout',
  33. 'app_login',
  34. ];
  35. $route = $request->attributes->get('_route');
  36. $path = $request->getPathInfo();
  37. if (!$route) {
  38. return;
  39. }
  40. $allowedRoutes = [
  41. 'app_change_password',
  42. 'app_logout',
  43. 'app_login',
  44. ];
  45. if (in_array($route, $allowedRoutes) || str_contains($path, '/change-password')) {
  46. return;
  47. }
  48. $user = $this->security->getUser();
  49. if (!$user instanceof User) {
  50. return;
  51. }
  52. $passwordChangedAt = $user->getPasswordChangedAt();
  53. $now = new \DateTime();
  54. if (!$passwordChangedAt) {
  55. $event->setResponse(
  56. new RedirectResponse($this->router->generate('app_change_password'))
  57. );
  58. return;
  59. }
  60. $expireDate = (clone $passwordChangedAt)->modify('+90 days');
  61. if ($now >= $expireDate) {
  62. $event->setResponse(
  63. new RedirectResponse($this->router->generate('app_change_password'))
  64. );
  65. }
  66. }
  67. }