src/EventSubscriber/Enforce2FASubscriber.php line 52

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\EventSubscriber;
  3. use Override;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use MedBrief\MSR\Entity\User;
  6. use MedBrief\MSR\Entity\UserPolicy;
  7. use MedBrief\MSR\Security\MedBriefLoginAuthenticator;
  8. use MedBrief\MSR\Service\TrustedDevice\Enforcement;
  9. use Scheb\TwoFactorBundle\Security\TwoFactor\Event\TwoFactorAuthenticationEvent;
  10. use Scheb\TwoFactorBundle\Security\TwoFactor\Event\TwoFactorAuthenticationEvents;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpKernel\Event\RequestEvent;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  16. use Symfony\Component\Routing\RouterInterface;
  17. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  18. class Enforce2FASubscriber implements EventSubscriberInterface
  19. {
  20. /** Wire the legacy MFA and policy continuation handlers. */
  21. public function __construct(private readonly RouterInterface $router, private readonly TokenStorageInterface $tokenStorage, private readonly EntityManagerInterface $entityManager, private readonly ?Enforcement $trustedDeviceEnforcement = null)
  22. {
  23. }
  24. #[Override]
  25. /** List the events used by legacy MFA and policy enforcement. */
  26. public static function getSubscribedEvents(): array
  27. {
  28. return [
  29. KernelEvents::REQUEST => [
  30. ['enforce2FA', 0],
  31. ],
  32. TwoFactorAuthenticationEvents::COMPLETE => [
  33. ['onTwoFactorAuthenticationComplete', 0],
  34. ],
  35. ];
  36. }
  37. /** Apply the legacy mandatory enrolment and policy redirects outside the Trusted Device rollout. */
  38. public function enforce2FA(RequestEvent $event): void
  39. {
  40. $request = $event->getRequest();
  41. $currentUser = $this->tokenStorage->getToken()?->getUser();
  42. if ($currentUser instanceof User && $this->trustedDeviceEnforcement?->appliesToAccount($currentUser)) {
  43. return;
  44. }
  45. // Check if we need to redirect for policy acceptance
  46. if ($request->getSession()->has('policy_redirect_needed')
  47. && $request->getSession()->get('policy_redirect_needed') === true) {
  48. $redirectUrl = $request->getSession()->get('policy_redirect_url');
  49. $request->getSession()->remove('policy_redirect_needed');
  50. $request->getSession()->remove('policy_redirect_url');
  51. $event->setResponse(new RedirectResponse($redirectUrl));
  52. return; // Exit early
  53. }
  54. $token = $this->tokenStorage->getToken();
  55. $user = null;
  56. if ($token) {
  57. /** @var User $user */
  58. $user = $token->getUser();
  59. }
  60. $enforce2FADetail = $request->getSession()->get(MedBriefLoginAuthenticator::ENFORCE_2FA_DETAIL_SESSION_KEY);
  61. // Check if 2FA is required from the session variable.
  62. // If the user is set, and the user has enabled 2FA...
  63. if (is_array($enforce2FADetail) && $enforce2FADetail['2faRequired'] === true && $user) {
  64. if ($user->hasEnabledMfa()) {
  65. // Redirect to the target path or the dashboard, and remove the session indicator for 2FA required.
  66. $targetPath = $enforce2FADetail['targetPath'];
  67. if ($targetPath !== null) {
  68. $event->setResponse(new RedirectResponse($targetPath));
  69. } else {
  70. $event->setResponse(new RedirectResponse($this->router->generate('infology_medbrief_dashboard')));
  71. }
  72. $request->getSession()->remove(MedBriefLoginAuthenticator::ENFORCE_2FA_DETAIL_SESSION_KEY);
  73. } else {
  74. // Allowed routes that do not require 2FA
  75. $allowedRoutes = [
  76. 'mfa_enable',
  77. 'mfa_enable_force',
  78. 'mfa_generate_codes',
  79. 'mfa_generate_initial_codes',
  80. 'auth_app_enable',
  81. 'auth_app_disable',
  82. 'email_mfa_enable',
  83. 'email_mfa_disable',
  84. 'user_policy_accept_decline',
  85. 'user_policy_accept_policies',
  86. 'user_policy_decline_policies',
  87. 'logout',
  88. ];
  89. // Redirect to the 2FA setup page if the current route is not allowed
  90. if (!in_array($request->attributes->get('_route'), $allowedRoutes, true)) {
  91. // Create the redirect URL
  92. $redirectUrl = $this->router->generate('mfa_enable_force');
  93. // Only proceed with policy checks for users WITHOUT 2FA
  94. $relevantPolicies = $this->entityManager->getRepository(UserPolicy::class)
  95. ->findUnacceptedActivePoliciesForUser($user->getId())
  96. ;
  97. // If the user has any pending policies, store them in the session along with the targetPath
  98. if ($relevantPolicies != null && $relevantPolicies != []) {
  99. $request->getSession()->set('pending-policies', $relevantPolicies);
  100. $request->getSession()->set('pending-policies-detail', [
  101. 'targetPath' => $redirectUrl,
  102. ]);
  103. }
  104. // Set the response with the combined URL
  105. $event->setResponse(new RedirectResponse($redirectUrl));
  106. }
  107. }
  108. }
  109. }
  110. /** Continue the legacy browser flow after MFA completes outside the rollout. */
  111. public function onTwoFactorAuthenticationComplete(TwoFactorAuthenticationEvent $event): void
  112. {
  113. $currentUser = $event->getToken()->getUser();
  114. if ($currentUser instanceof User && $this->trustedDeviceEnforcement?->appliesToAccount($currentUser)) {
  115. return;
  116. }
  117. $request = $event->getRequest();
  118. $token = $this->tokenStorage->getToken();
  119. $user = null;
  120. if ($token) {
  121. /** @var User $user */
  122. $user = $token->getUser();
  123. }
  124. $targetPath = $request->getSession()->get('_security.main.target_path');
  125. $relevantPolicies = $this->entityManager->getRepository(UserPolicy::class)
  126. ->findUnacceptedActivePoliciesForUser($user->getId())
  127. ;
  128. // If the user has any pending policies, store them in the session along with the targetPath
  129. if ($relevantPolicies != null && $relevantPolicies != []) {
  130. $request->getSession()->set('pending-policies', $relevantPolicies);
  131. $request->getSession()->set('pending-policies-detail', [
  132. 'targetPath' => $targetPath,
  133. ]);
  134. // Store the redirect URL in the session
  135. $request->getSession()->set('policy_redirect_needed', true);
  136. $request->getSession()->set(
  137. 'policy_redirect_url',
  138. $targetPath
  139. );
  140. }
  141. }
  142. }