src/EventSubscriber/SecurityEventSubscriber.php line 82

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