src/EventSubscriber/SecurityEventSubscriber.php line 76

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\EventSubscriber;
  3. use DateTime;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use MedBrief\MSR\Entity\AuditRecord\User as UserAuditRecord;
  6. use MedBrief\MSR\Entity\Firm;
  7. use MedBrief\MSR\Entity\User;
  8. use MedBrief\MSR\Entity\UserLogin;
  9. use MedBrief\MSR\Event\AuditRecordEvent;
  10. use MedBrief\MSR\Factory\AuditRecordEventFactory;
  11. use MedBrief\MSR\Factory\AuditRecordFactory;
  12. use MedBrief\MSR\Security\Exception\GenericOAuthException;
  13. use MedBrief\MSR\Service\EntityHelper\UserHelper;
  14. use MedBrief\MSR\Service\Notification\Generators\UserLoginNotification;
  15. use MedBrief\MSR\Service\TrustedDevice\DeviceContextCollector;
  16. use Override;
  17. use Ramsey\Uuid\Uuid;
  18. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  19. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  20. use Symfony\Component\HttpFoundation\Cookie;
  21. use Symfony\Component\HttpFoundation\RequestStack;
  22. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  23. use Symfony\Component\HttpKernel\KernelEvents;
  24. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  25. use Symfony\Component\Security\Core\AuthenticationEvents;
  26. use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
  27. use Symfony\Component\Security\Core\User\UserInterface;
  28. use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
  29. use Symfony\Component\Security\Http\Event\SwitchUserEvent;
  30. use Symfony\Component\Security\Http\SecurityEvents;
  31. class SecurityEventSubscriber implements EventSubscriberInterface
  32. {
  33. public const LOGIN_NEW_IP = 'ip';
  34. public const LOGIN_NEW_DEVICE = 'device';
  35. /** Wire sign-in audit persistence and the request-scoped device context. */
  36. public function __construct(
  37. protected EntityManagerInterface $entityManager,
  38. private readonly DeviceContextCollector $deviceContext,
  39. protected UserLoginNotification $loginNotificationGenerator,
  40. protected UserHelper $userHelper,
  41. protected RequestStack $request,
  42. protected EventDispatcherInterface $eventDispatcher,
  43. ) {
  44. }
  45. /**
  46. * @inheritDoc
  47. */
  48. #[Override]
  49. public static function getSubscribedEvents(): array
  50. {
  51. return [
  52. LoginSuccessEvent::class => [
  53. ['logUserLogin', 0],
  54. ],
  55. SecurityEvents::SWITCH_USER => [
  56. ['logUserSimulation', 0],
  57. ],
  58. AuthenticationEvents::AUTHENTICATION_FAILURE => [
  59. ['logFailedUserLogin', 0],
  60. ],
  61. KernelEvents::RESPONSE => [
  62. ['setDeviceId', 50],
  63. ],
  64. ];
  65. }
  66. /** Record a failed form login against the submitted account. */
  67. public function logFailedUserLogin(AuthenticationFailureEvent $event): void
  68. {
  69. // Because OAuth exceptions cannot be traced to a specific user, skip them
  70. if (!$event->getAuthenticationException() instanceof GenericOAuthException) {
  71. // Grab the user account that the failure was logged for
  72. $request = $this->request->getMainRequest();
  73. if ($request === null) {
  74. return;
  75. }
  76. $email = $request->request->all()['username'] ?? null;
  77. if (!is_string($email) || $email === '') {
  78. return;
  79. }
  80. $user = $this->entityManager->getRepository(User::class)
  81. ->findOneBy(['email' => $email])
  82. ;
  83. // If we actually have a user
  84. if ($user instanceof UserInterface) {
  85. $context = $this->deviceContext->collect($request);
  86. // Create a UserLogin object
  87. $login = new UserLogin(
  88. $user,
  89. $context->ipAddress ?? '',
  90. $context->historicalClient,
  91. $context->historicalOs,
  92. $context->historicalLocation,
  93. false,
  94. );
  95. $this->entityManager->persist($login);
  96. $this->entityManager->flush();
  97. }
  98. }
  99. }
  100. /**
  101. * Logs a user's login (login success event) and persists the details to the database to ensure an auditable track
  102. * of IP addresses they accessed from as well as what platform and browser, including emailing users when a new
  103. * login is detected.
  104. *
  105. *
  106. *
  107. * @todo: Correctly log DocSorter logins rather than bypassing them
  108. *
  109. * @param LoginSuccessEvent $loginEvent
  110. *
  111. * @throws \Exception
  112. */
  113. public function logUserLogin(LoginSuccessEvent $loginEvent): void
  114. {
  115. // Grab the path and make sure we are not doing this check on anything but login events
  116. $path = $loginEvent->getRequest()->getRequestUri();
  117. // Putting this logic back for now, until we have time to prevent the interactive login happening on every DocSorter request.
  118. if (preg_match("/^\/api\/sort\/(?!login).*$/", $path)) {
  119. return;
  120. }
  121. // Grab the User
  122. /** @var User $user */
  123. $user = $loginEvent->getUser();
  124. if ($user instanceof Firm) {
  125. // Firms do not get logged here (at the moment)
  126. return;
  127. }
  128. // Grab the device identifier cookie, if it exists
  129. $request = $loginEvent->getRequest();
  130. $rawDeviceId = $request->cookies->all()['msr_dev_id'] ?? null;
  131. $deviceId = is_string($rawDeviceId) && Uuid::isValid($rawDeviceId) ? Uuid::fromString($rawDeviceId) : null;
  132. $context = $this->deviceContext->collect($request);
  133. $login = new UserLogin(
  134. $user,
  135. $context->ipAddress ?? '',
  136. $context->historicalClient,
  137. $context->historicalOs,
  138. $context->historicalLocation,
  139. true,
  140. $deviceId,
  141. );
  142. // Set the device ID in the attributes to persist it to cookies
  143. $request->attributes->set('msr_dev_id', $login->getDevice()->toString());
  144. // First time user has logged in. Set firstLoginDate
  145. if ($user->getFirstLoginDate() === null) {
  146. $user->setFirstLoginDate(new DateTime('NOW'));
  147. }
  148. // Set the last login date for the user as well
  149. $user->setLastLogin(new DateTime('NOW'));
  150. // This user has never logged in before or we can't match so...
  151. // Register this login
  152. $this->entityManager->persist($user);
  153. $this->entityManager->persist($login);
  154. $this->entityManager->flush();
  155. // ... and email the user
  156. // @TODO: This caused issues with clients who were spammed.
  157. // $this->sendAlertNotification($login, self::LOGIN_NEW_DEVICE);
  158. }
  159. /**
  160. * Logs the simulation of users
  161. *
  162. * @param SwitchUserEvent $event
  163. */
  164. public function logUserSimulation(SwitchUserEvent $event): void
  165. {
  166. $token = $event->getToken();
  167. if ($token instanceof SwitchUserToken) {
  168. $user = $event->getToken()->getOriginalToken()->getUser();
  169. $targetUser = $event->getTargetUser();
  170. $verb = UserAuditRecord::VERB_SIMULATE;
  171. } else {
  172. $user = $event->getToken()->getUser();
  173. $targetUser = null;
  174. $verb = UserAuditRecord::VERB_SIMULATE_EXIT;
  175. }
  176. $auditRecord = AuditRecordFactory::create(
  177. UserAuditRecord::class,
  178. $user,
  179. $targetUser,
  180. $verb
  181. );
  182. $this->eventDispatcher->dispatch(
  183. AuditRecordEventFactory::create($auditRecord),
  184. AuditRecordEvent::AUDIT
  185. );
  186. }
  187. /**
  188. * Sets a device ID cookie during the kernel.response
  189. *
  190. * @param ResponseEvent $event
  191. */
  192. public function setDeviceId(ResponseEvent $event): void
  193. {
  194. $attr = $event->getRequest()->attributes->get('msr_dev_id');
  195. if ($attr !== null) {
  196. $event->getResponse()->headers->setCookie(Cookie::create('msr_dev_id', $attr, new DateTime('+2 year')));
  197. }
  198. }
  199. /**
  200. * Sends a login alert notification to the user
  201. *
  202. * @param $type
  203. * @param UserLogin $login
  204. */
  205. protected function sendAlertNotification(UserLogin $login, $type)
  206. {
  207. // Disable notification temporarily, until there is a way to unsubscribe
  208. // $this->loginNotificationGenerator->generate($login, $type);
  209. }
  210. }