src/Controller/DefaultController.php line 54

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\Controller;
  3. use DateTime;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Exception;
  6. use MedBrief\MSR\Controller\BaseController as Controller;
  7. use MedBrief\MSR\Entity\Analytics\AnalyticsReport;
  8. use MedBrief\MSR\Entity\Invitation;
  9. use MedBrief\MSR\Entity\Project;
  10. use MedBrief\MSR\Entity\RoleInvitation;
  11. use MedBrief\MSR\Entity\User;
  12. use MedBrief\MSR\Form\ChangePasswordFormType;
  13. use MedBrief\MSR\Form\Filter\MatterFilterType;
  14. use MedBrief\MSR\Form\Order\MatterOrderType;
  15. use MedBrief\MSR\Repository\ProjectRepository;
  16. use MedBrief\MSR\Repository\RoleInvitationRepository;
  17. use MedBrief\MSR\Repository\SystemNotificationRepository;
  18. use MedBrief\MSR\Service\Analytics\AnalyticsService;
  19. use MedBrief\MSR\Service\Analytics\Model\AnalyticsEmbeddedReport;
  20. use MedBrief\MSR\Service\DeviceDetectorService;
  21. use MedBrief\MSR\Service\EntityHelper\ProjectHelper;
  22. use MedBrief\MSR\Service\EntityHelper\UserHelper;
  23. use MedBrief\MSR\Service\LicenceRenewal\RenewalHelperService;
  24. use MedBrief\MSR\Service\ProjectMatch\MatchExpertDashboardAlert;
  25. use MedBrief\MSR\Service\ProjectMatch\MatchExpertUser;
  26. use MedBrief\MSR\Service\Role\RoleParserService;
  27. use MedBrief\MSR\Service\Security\GeneralSecurityService;
  28. use MedBrief\MSR\Traits\PaginatorAwareTrait;
  29. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  30. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  31. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  32. use Symfony\Component\HttpFoundation\Cookie;
  33. use Symfony\Component\HttpFoundation\JsonResponse;
  34. use Symfony\Component\HttpFoundation\RedirectResponse;
  35. use Symfony\Component\HttpFoundation\Request;
  36. use Symfony\Component\HttpFoundation\Response;
  37. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  38. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  39. use Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken;
  40. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  41. class DefaultController extends Controller
  42. {
  43. use PaginatorAwareTrait;
  44. /**
  45. * When the user navigates to the MedBrief home page, if they are logged in, then we
  46. * log them out. We then redirect to login. This is per Steve England's
  47. * request that for security purposes, when the landing page is hit, we log
  48. * users out.
  49. */
  50. public function indexAction(): JsonResponse|RedirectResponse
  51. {
  52. // if the user is currently logged in
  53. if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  54. // Forward to the dashboard. We used to log the user out but this caused more problems than it solved.
  55. return $this->redirectWithAjaxSupport($this->generateUrl('infology_medbrief_dashboard'));
  56. }
  57. // if we have a redirect page specified in the parameters
  58. $redirectUrl = $this->getParameter('root_page_redirect_url');
  59. if ($redirectUrl) {
  60. // redirect the user to it
  61. return $this->redirectWithAjaxSupport($redirectUrl);
  62. }
  63. // otherwise just sent them to login
  64. return $this->redirectWithAjaxSupport($this->generateUrl('login'));
  65. }
  66. /**
  67. * @param EntityManagerInterface $entityManager
  68. * @param AnalyticsService $analyticsService
  69. * @param UserHelper $userHelper
  70. * @param ProjectRepository $projectRepository
  71. * @param RoleInvitationRepository $roleInvitationRepository
  72. * @param SystemNotificationRepository $systemNotificationRepository
  73. * @param RoleParserService $roleParser
  74. * @param RenewalHelperService $renewalHelperService
  75. * @param Request $request
  76. * @param ProjectHelper $projectHelper
  77. * @param MatchExpertUser $matchExpertUserService
  78. * @param GeneralSecurityService $generalSecurityService
  79. * @param MatchExpertDashboardAlert $matchExpertDashboardAlert
  80. *
  81. * @throws Exception
  82. *
  83. */
  84. public function dashboardAction(
  85. AnalyticsService $analyticsService,
  86. UserHelper $userHelper,
  87. ProjectRepository $projectRepository,
  88. RoleInvitationRepository $roleInvitationRepository,
  89. SystemNotificationRepository $systemNotificationRepository,
  90. RoleParserService $roleParser,
  91. RenewalHelperService $renewalHelperService,
  92. ProjectHelper $projectHelper,
  93. MatchExpertUser $matchExpertUserService,
  94. Request $request,
  95. GeneralSecurityService $generalSecurityService,
  96. MatchExpertDashboardAlert $matchExpertDashboardAlert
  97. ): JsonResponse|RedirectResponse|Response {
  98. // Get the response message from url if we have one from the (match expert) complete profile confirm button.
  99. $responseMessage = $request->query->get('message', null);
  100. $referrer = $request->headers->get('referer');
  101. if ($responseMessage && $generalSecurityService->isRequestFromMedBrief($referrer)) {
  102. $this->addFlash('success', $responseMessage);
  103. }
  104. // Redirect to pending invitations page if User has pending role invitations.
  105. if ($this->userHasPendingInvitations()) {
  106. return $this->redirectWithAjaxSupport($this->pendingInvitationsUrlWithoutFlash());
  107. }
  108. /** @var User $user */
  109. $user = $this->getUser();
  110. $userHelper->setUser($user);
  111. // If the user has 2FA enabled and is rate limited, redirect them to the login page.
  112. if ($user->hasMultiMfaEnabled() && $request->getSession()->has('rateLimited')) {
  113. $this->addFlash('danger', 'You have entered the incorrect authentication code too many times. Please try again in fifteen minutes.');
  114. return $this->redirectToRoute('logout');
  115. }
  116. // If the user has 2FA enabled and their IP Address has been blacklisted, redirect them to the login page.
  117. if ($user->hasMultiMfaEnabled() && $request->getSession()->has('ipBlacklisted')) {
  118. $this->addFlash('danger', 'You have entered the incorrect authentication code too many times from this IP Address. Please try again in fifteen minutes.');
  119. return $this->redirectToRoute('logout');
  120. }
  121. $analyticsEmbeddedReport = $analyticsService->generateAnalyticsEmbeddedReport($user, AnalyticsReport::REPORT_TYPE_DASHBOARD);
  122. // We use this to determine if we should display the 'Explore Analytics' button.
  123. $analyticsEmbeddedReportMain = $analyticsService->generateAnalyticsEmbeddedReport($user, AnalyticsReport::REPORT_TYPE_MAIN);
  124. $recentlyViewedProjects = $this->getRecentlyViewedProjects($projectRepository, $userHelper, $projectHelper, $matchExpertUserService, false)['projects'];
  125. $favouriteProjects = $this->getFavouriteProjects($projectHelper, $matchExpertUserService, false)['projects'];
  126. $recentlyAcceptedProjects = $this->getRecentlyAcceptedProjects($roleInvitationRepository, $roleParser, $projectHelper, $matchExpertUserService, false)['projects'];
  127. $recentlyViewedProjectCount = count($recentlyViewedProjects);
  128. $favouritesCount = count($favouriteProjects);
  129. $recentlyAcceptedCount = count($recentlyAcceptedProjects);
  130. // Fetch renewal projects and filter by active licence renewal terms to get accurate count
  131. $renewalProjectsForCount = $projectRepository->findRenewalsDueWithin30DaysForUser($userHelper);
  132. $eligibleRenewalProjects = $this->getEligibleRenewalProjects($renewalProjectsForCount, $renewalHelperService);
  133. $renewalsCount = count($eligibleRenewalProjects);
  134. // Create a combined array of all unique Projects fetched in this controller action.
  135. $uniqueProjects = array_unique(array_merge(
  136. $recentlyViewedProjects,
  137. $favouriteProjects,
  138. $recentlyAcceptedProjects,
  139. ));
  140. $grossTotalProjectsCount = count($uniqueProjects);
  141. // All Projects that have a renewal date
  142. $eligibleProjects = $this->getEligibleRenewalProjects($uniqueProjects, $renewalHelperService);
  143. // Get the latest active system notification
  144. $systemNotification = $systemNotificationRepository->findLatestSystemNotification();
  145. /**
  146. * Create a form we will use to allow the user to Filter this list
  147. */
  148. $filterForm = $this->createForm(MatterFilterType::class, null, [
  149. 'userHelper' => $userHelper,
  150. 'em' => $this->getDoctrine()->getManager(),
  151. ]);
  152. // Create and user a form to order this list
  153. $orderForm = $this->createForm(MatterOrderType::class);
  154. $isExpert = $user->isExpertOnly() || $user->isExpertViewerOnly();
  155. // Order A applies to all user roles, excluding the two expert user roles
  156. // Order B applies to the two expert user roles only
  157. $tabOrder = $isExpert ? 'order-b' : 'order-a';
  158. return $this->renderTurbo('Default/dashboard.html.twig', [
  159. 'eligibleProjectsToDisplayRenewalDate' => $eligibleProjects,
  160. 'filterForm' => $filterForm->createView(),
  161. 'orderForm' => $orderForm->createView(),
  162. 'systemNotification' => $systemNotification,
  163. 'analyticsEmbeddedReport' => $analyticsEmbeddedReport,
  164. 'analyticsEmbeddedReportMain' => $analyticsEmbeddedReportMain,
  165. 'recentlyViewedCount' => $recentlyViewedProjectCount,
  166. 'recentlyAcceptedCount' => $recentlyAcceptedCount,
  167. 'favouritesCount' => $favouritesCount,
  168. 'renewalsCount' => $renewalsCount,
  169. 'grossTotalProjectsCount' => $grossTotalProjectsCount,
  170. 'tabOrder' => $tabOrder,
  171. 'isExpert' => $isExpert,
  172. 'matchActionAlert' => $matchExpertDashboardAlert->resolveForUser($user),
  173. ]);
  174. }
  175. /**
  176. * List Matters most recently viewed
  177. *
  178. * @Template("Default/Partials/viewedTab.html.twig")
  179. *
  180. * @param RoleInvitationRepository $roleInvitationRepository
  181. * @param RoleParserService $roleParser
  182. * @param UserHelper $userHelper
  183. * @param ProjectRepository $projectRepository
  184. * @param RenewalHelperService $renewalHelperService
  185. * @param ProjectHelper $projectHelper
  186. * @param MatchExpertUser $matchExpertUserService
  187. *
  188. * @throws Exception
  189. *
  190. */
  191. public function dashboardViewedAjaxAction(
  192. UserHelper $userHelper,
  193. ProjectRepository $projectRepository,
  194. RenewalHelperService $renewalHelperService,
  195. MatchExpertUser $matchExpertUserService,
  196. ProjectHelper $projectHelper,
  197. ): JsonResponse|RedirectResponse|array {
  198. // Redirect to pending invitations page if User has pending role invitations.
  199. if ($this->userHasPendingInvitations()) {
  200. return $this->redirectWithAjaxSupport($this->pendingInvitationsUrlWithFlash());
  201. }
  202. $userHelper->setUser($this->getUser());
  203. $recentlyViewed = $this->getRecentlyViewedProjects($projectRepository, $userHelper, $projectHelper, $matchExpertUserService);
  204. $recentlyViewedProjects = $recentlyViewed['projects'];
  205. $userType = $recentlyViewed['userType'];
  206. // Return if no qualifying Projects
  207. if ($recentlyViewedProjects === []) {
  208. return [
  209. 'blurb' => 'You do not have any recently viewed matters.',
  210. ];
  211. }
  212. // All Projects that have a renewal date
  213. $eligibleProjects = $this->getEligibleRenewalProjects($recentlyViewedProjects, $renewalHelperService);
  214. return [
  215. 'projects' => $recentlyViewedProjects,
  216. 'eligibleProjectsToDisplayRenewalDate' => $eligibleProjects,
  217. 'blurb' => 'Most recently viewed matters (up to 20).',
  218. 'userType' => $userType,
  219. ];
  220. }
  221. /**
  222. * List the User's favourite Matters
  223. *
  224. * @Template("Default/Partials/favouritesTab.html.twig")
  225. *
  226. * @param Request $request
  227. * @param RenewalHelperService $renewalHelperService
  228. * @param ProjectHelper $projectHelper
  229. * @param MatchExpertUser $matchExpertUserService
  230. *
  231. * @throws Exception
  232. */
  233. public function dashboardFavouritesAjaxAction(Request $request, RenewalHelperService $renewalHelperService, ProjectHelper $projectHelper, MatchExpertUser $matchExpertUserService): JsonResponse|RedirectResponse|array
  234. {
  235. // Redirect to pending invitations page if User has pending role invitations.
  236. if ($this->userHasPendingInvitations()) {
  237. return $this->redirectWithAjaxSupport($this->pendingInvitationsUrlWithFlash());
  238. }
  239. $favouriteProjectsArray = $this->getFavouriteProjects($projectHelper, $matchExpertUserService);
  240. $favouriteProjects = $favouriteProjectsArray['projects'];
  241. $userType = $favouriteProjectsArray['userType'];
  242. // Return if no qualifying Projects
  243. if ($favouriteProjects === []) {
  244. return [
  245. 'blurb' => 'You do not have any matters added as a favourite.',
  246. ];
  247. }
  248. // All favourite Projects that have a renewal date
  249. $eligibleProjects = $this->getEligibleRenewalProjects($favouriteProjects, $renewalHelperService);
  250. $projectCount = count($favouriteProjects);
  251. $blurbText = $projectCount === 1 ? '1 Matter added as a favourite.' : sprintf('%d %s', $projectCount, 'Matters added as a favourite.');
  252. // Paginate with a specific page and limit
  253. $pagination = $this->paginator->paginate(
  254. $favouriteProjects, // the array to paginate
  255. $request->query->getInt('page', 1), // current page number, default is 1
  256. 10 // items per page
  257. );
  258. return [
  259. 'pagination' => $pagination,
  260. 'totalProjectCount' => $projectCount,
  261. 'eligibleProjectsToDisplayRenewalDate' => $eligibleProjects,
  262. 'blurb' => $blurbText,
  263. 'userType' => $userType,
  264. ];
  265. }
  266. /**
  267. * List Matters accepted in the past 30 days
  268. *
  269. * @Template("Default/Partials/invitationsTab.html.twig")
  270. *
  271. * @param Request $request
  272. * @param RoleInvitationRepository $roleInvitationRepository
  273. * @param RoleParserService $roleParser
  274. * @param RenewalHelperService $renewalHelperService
  275. * @param ProjectHelper $projectHelper
  276. * @param MatchExpertUser $matchExpertUserService
  277. *
  278. * @throws Exception
  279. */
  280. public function dashboardInvitationsAjaxAction(
  281. Request $request,
  282. RoleInvitationRepository $roleInvitationRepository,
  283. RoleParserService $roleParser,
  284. RenewalHelperService $renewalHelperService,
  285. MatchExpertUser $matchExpertUserService,
  286. ProjectHelper $projectHelper
  287. ): JsonResponse|RedirectResponse|array {
  288. // Redirect to pending invitations page if User has pending role invitations.
  289. if ($this->userHasPendingInvitations()) {
  290. return $this->redirectWithAjaxSupport($this->pendingInvitationsUrlWithFlash());
  291. }
  292. $recentlyAcceptedArray = $this->getRecentlyAcceptedProjects($roleInvitationRepository, $roleParser, $projectHelper, $matchExpertUserService);
  293. $recentlyAccepted = $recentlyAcceptedArray['projects'];
  294. $userType = $recentlyAcceptedArray['userType'];
  295. // Return if no qualifying Projects
  296. if ($recentlyAccepted === []) {
  297. return [
  298. 'blurb' => 'You have not accepted any invitations in the last 30 days.',
  299. ];
  300. }
  301. // All recently accepted Projects that have a renewal date
  302. $eligibleProjects = $this->getEligibleRenewalProjects($recentlyAccepted, $renewalHelperService);
  303. $projectCount = count($recentlyAccepted);
  304. $blurbText = $projectCount === 1 ? '1 Invitation accepted in the last 30 days.' : sprintf('%d %s', $projectCount, 'Invitations accepted in the last 30 days.');
  305. // Paginate with a specific page and limit
  306. $pagination = $this->paginator->paginate(
  307. $recentlyAccepted, // the array to paginate
  308. $request->query->getInt('page', 1), // current page number, default is 1
  309. 10 // items per page
  310. );
  311. return [
  312. 'pagination' => $pagination,
  313. 'totalProjectCount' => $projectCount,
  314. 'eligibleProjectsToDisplayRenewalDate' => $eligibleProjects,
  315. 'blurb' => $blurbText,
  316. 'userType' => $userType,
  317. ];
  318. }
  319. /**
  320. * List Matters due for renewal
  321. *
  322. * @Template("Default/Partials/renewalsTab.html.twig")
  323. *
  324. * @param Request $request
  325. * @param ProjectRepository $projectRepository
  326. * @param UserHelper $userHelper
  327. * @param ProjectHelper $projectHelper
  328. * @param MatchExpertUser $matchExpertUserService
  329. * @param RenewalHelperService $renewalHelperService
  330. *
  331. * @return array
  332. */
  333. public function dashboardRenewalsAjaxAction(Request $request, ProjectRepository $projectRepository, UserHelper $userHelper, ProjectHelper $projectHelper, MatchExpertUser $matchExpertUserService, RenewalHelperService $renewalHelperService): RedirectResponse|array
  334. {
  335. // Redirect to pending invitations page if User has pending role invitations.
  336. if ($this->userHasPendingInvitations()) {
  337. return $this->redirect($this->pendingInvitationsUrlWithFlash());
  338. }
  339. $userHelper->setUser($this->getUser());
  340. // All Projects that are due for renewal within the next 30 days
  341. $renewalProjects = $projectRepository->findRenewalsDueWithin30DaysForUser($userHelper);
  342. // Filter out projects whose accounts no longer have active licence renewal terms.
  343. // Use array_values(array_filter()) instead of getEligibleRenewalProjects() to preserve
  344. // the DB query's nextRenewalDate ASC sort order (soonest renewals first).
  345. $renewalProjects = array_values(array_filter(
  346. $renewalProjects,
  347. fn (Project $project): ?bool => $renewalHelperService->isMatterEligibleForRenewal($project)
  348. ));
  349. $projectCount = count($renewalProjects);
  350. $blurbText = $projectCount === 1 ? '1 Matter due for renewal within the next 30 days.' : sprintf('%d %s', $projectCount, 'Matters due for renewal within the next 30 days.');
  351. // Return if no qualifying Projects
  352. if (empty($renewalProjects)) {
  353. return [
  354. 'blurb' => 'There are no matters due for renewal in the next 30 days.',
  355. ];
  356. }
  357. // Paginate with a specific page and limit
  358. $pagination = $this->paginator->paginate(
  359. $renewalProjects, // the array to paginate
  360. $request->query->getInt('page', 1), // current page number, default is 1
  361. 10 // items per page
  362. );
  363. // Determine user type for displaying unread message counts (firm/expert)
  364. $userType = $matchExpertUserService->getUserType($this->getUser());
  365. // This sets the unread message counts on each Project entity
  366. $projectHelper->setUnreadMessageCount(iterator_to_array($pagination), $userType, $this->getUser());
  367. return [
  368. 'pagination' => $pagination,
  369. 'totalProjectCount' => $projectCount,
  370. 'eligibleProjectsToDisplayRenewalDate' => $renewalProjects,
  371. 'blurb' => $blurbText,
  372. 'userType' => $userType,
  373. ];
  374. }
  375. /**
  376. * @Template("Default/analytics.html.twig")
  377. *
  378. * @Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
  379. *
  380. * @param AnalyticsService $analyticsService
  381. */
  382. public function analyticsAction(AnalyticsService $analyticsService): RedirectResponse|array
  383. {
  384. $analyticsEmbeddedReport = $analyticsService->generateAnalyticsEmbeddedReport($this->getUser(), AnalyticsReport::REPORT_TYPE_MAIN);
  385. if (!$analyticsEmbeddedReport instanceof AnalyticsEmbeddedReport) {
  386. $this->addFlash('warning', 'No Analytics Report for this case');
  387. return $this->redirectToRoute('infology_medbrief_dashboard');
  388. }
  389. return [
  390. 'analyticsEmbeddedReport' => $analyticsEmbeddedReport,
  391. ];
  392. }
  393. /**
  394. * This action is the click through from the email that is sent to a user asking
  395. * them to finalise their registration in order to enable their account
  396. *
  397. * @Template("Default/enableAccount.html.twig")
  398. *
  399. * @param Request $request
  400. * @param TokenStorageInterface $tokenStorage
  401. * @param EventDispatcherInterface $eventDispatcher
  402. * @param EntityManagerInterface $entityManager
  403. * @param UserPasswordEncoderInterface $userPasswordEncoder
  404. * @param UserHelper $userHelper
  405. *
  406. * @throws Exception
  407. */
  408. public function enableAccountAction(
  409. Request $request,
  410. TokenStorageInterface $tokenStorage,
  411. EventDispatcherInterface $eventDispatcher,
  412. EntityManagerInterface $entityManager,
  413. UserPasswordEncoderInterface $userPasswordEncoder,
  414. UserHelper $userHelper
  415. ): RedirectResponse|array {
  416. // if the user is logged in
  417. if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  418. // log them out
  419. $tokenStorage->setToken();
  420. $request->getSession()->invalidate();
  421. // redirect them back here
  422. return $this->redirect($request->getRequestUri());
  423. }
  424. // grab the invitation code from the URL
  425. $invitationCode = $request->query->get('i');
  426. // if none was provided, we have a problem
  427. if (empty($invitationCode)) {
  428. throw $this->createNotFoundException('Invitation could not be found.');
  429. }
  430. // try to find a matching invitation
  431. $invitation = $this->getDoctrine()->getRepository(Invitation::class)->findOneByCode($invitationCode);
  432. // if we cant find one, we have a problem
  433. if (!$invitation) {
  434. throw $this->createNotFoundException('Unable to find Invitation.');
  435. }
  436. // try to find a user who matches this invitation
  437. $matchingUser = $entityManager->getRepository(User::class)
  438. ->findOneByEmail($invitation->getEmail())
  439. ;
  440. if (!$matchingUser) {
  441. throw $this->createNotFoundException('Unable to find User.');
  442. }
  443. // if the user is already enabled, then we assume this invitation has been processed already
  444. if ($matchingUser->isEnabled()) {
  445. return $this->redirectToRoute('infology_medbrief_invitation_already_processed');
  446. }
  447. // if we get here then we have found a user who is not yet enabled and may now complete their registration
  448. $form = $this->createForm(ChangePasswordFormType::class, $matchingUser, [
  449. 'action' => $this->generateUrl('infology_medbrief_user_complete_registration', ['id' => $matchingUser->getId()]),
  450. ]);
  451. $form->handleRequest($request);
  452. if ($form->isSubmitted() && $form->isValid()) {
  453. // Accept the Medbrief policies
  454. $userHelper->acceptDeclineMedbriefPolicies($matchingUser);
  455. $encodedPassword = $userPasswordEncoder->encodePassword(
  456. $matchingUser,
  457. $form->get('plainPassword')->getData()
  458. );
  459. // Set the password
  460. $matchingUser->setPassword($encodedPassword);
  461. // set the user enabled now
  462. $matchingUser->setEnabled(true);
  463. $entityManager->flush();
  464. // log the user in
  465. $token = new PostAuthenticationGuardToken($matchingUser, 'main', $matchingUser->getRoles());
  466. $tokenStorage->setToken($token); //now the user is logged in
  467. //now dispatch the login event
  468. $eventDispatcher->dispatch(
  469. new InteractiveLoginEvent($request, $token),
  470. 'security.interactive_login'
  471. );
  472. // Determine if th user requires 2FA to be enabled (if they don't already) and store it in the session
  473. // to prevent navigating to any part of the site, except the 2FA enable page, or logout page.
  474. // @see MedBrief\MSR\EventSubscriber\Enforce2FASubscriber
  475. /** @var User $user */
  476. $user = $this->getUser();
  477. $userHelper->setUser($user);
  478. if ($userHelper->twoFactoryAuthEnabledUser() && !$user->hasMultiMfaEnabled()) {
  479. $request->getSession()->set('enforce-two-factor-authentication-detail', [
  480. '2faRequired' => true,
  481. 'targetPath' => null,
  482. ]);
  483. return $this->redirectToRoute('mfa_enable_force');
  484. }
  485. // If the user has 2FA enabled and is rate limited, redirect them to the login page.
  486. if ($user->hasMultiMfaEnabled() && $request->getSession()->has('rateLimited')) {
  487. $this->addFlash('danger', 'You have entered the incorrect authentication code too many times. Please try again in five minutes.');
  488. return $this->redirectToRoute('logout');
  489. }
  490. // If the user has 2FA enabled and their IP Address has been blacklisted, redirect them to the login page.
  491. if ($user->hasMultiMfaEnabled() && $request->getSession()->has('ipBlacklisted')) {
  492. $this->addFlash('danger', 'You have entered the incorrect authentication code too many times from this IP address. Please try again in fifteen minutes.');
  493. return $this->redirectToRoute('logout');
  494. }
  495. return $this->redirectToRoute('infology_medbrief_dashboard');
  496. }
  497. return [
  498. 'user' => $matchingUser,
  499. 'form' => $form->createView(),
  500. ];
  501. }
  502. /**
  503. * Is the user logged in?
  504. *
  505. *
  506. *
  507. * @param Request $request
  508. *
  509. * @return JsonResponse 1/0
  510. */
  511. public function isUserLoggedInAction(Request $request)
  512. {
  513. // if the user is currently logged in
  514. if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  515. return new JsonResponse(['status' => 1], 200);
  516. }
  517. return new JsonResponse(['status' => 0], 200);
  518. }
  519. /**
  520. * Refresh the session upon user wishing to remain logged in.
  521. *
  522. *
  523. *
  524. * @param Request $request
  525. *
  526. * @return JsonResponse
  527. */
  528. public function refreshSessionAction(Request $request)
  529. {
  530. // if the user is currently logged in
  531. if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  532. // Extend the session
  533. try {
  534. $cookie_lifetime = ini_get('session.cookie_lifetime');
  535. if ($cookie_lifetime === false || $cookie_lifetime === '') {
  536. throw new Exception('session.cookie_lifetime not found!');
  537. }
  538. $lifeTime = (int) $cookie_lifetime;
  539. } catch (Exception) {
  540. $lifeTime = $request->getSession()->getMetadataBag()->getLifetime();
  541. }
  542. $request->getSession()->getMetadataBag()->stampNew($lifeTime);
  543. $now = new DateTime();
  544. $expire = $request->getSession()->getMetadataBag()->getCreated() + $request->getSession()->getMetadataBag()->getLifetime();
  545. $response = new JsonResponse([
  546. 'sessionExpire' => $expire,
  547. ]);
  548. $sessionName = $this->getParameter('session.name');
  549. $sessionCookieValue = $request->cookies->get($sessionName);
  550. $sessionCookie = Cookie::create($sessionName, $sessionCookieValue, $expire);
  551. $response->headers->setCookie($sessionCookie);
  552. return $response;
  553. }
  554. return new JsonResponse([], 404);
  555. }
  556. /**
  557. * Refresh the session upon user wishing to remain logged in.
  558. *
  559. *
  560. *
  561. * @param Request $request
  562. *
  563. * @return JsonResponse
  564. */
  565. public function refreshUserSessionAction(Request $request)
  566. {
  567. // if the user is currently logged in
  568. if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  569. // Expiration time
  570. $expire = time() + (20 * 60 * 1000);
  571. return new JsonResponse([
  572. 'sessionExpire' => $expire,
  573. ]);
  574. }
  575. return new JsonResponse(['status' => 0], Response::HTTP_FORBIDDEN);
  576. }
  577. /**
  578. * Redirect the user to the login page with a message
  579. *
  580. * Used by the session timeout feature to logout inactive users while preserving
  581. * the return URL so they can resume where they left off after logging back in.
  582. *
  583. * @param Request $request
  584. */
  585. public function userInactivityLoginRedirectAction(Request $request): RedirectResponse
  586. {
  587. $this->addFlash('warning', 'You have been automatically logged out due to inactivity');
  588. // Get the return URL from the query parameter (passed from JavaScript)
  589. $returnUrl = $request->query->get('returnUrl');
  590. // Note: Uses 'logout' route (not legacy 'fos_user_security_logout' which no longer exists)
  591. $response = $this->redirectToRoute('logout');
  592. // Store return URL in a cookie that survives logout (session is cleared on logout)
  593. // The login authenticator will read this cookie and redirect after successful login
  594. if ($returnUrl) {
  595. $response->headers->setCookie(
  596. new Cookie(
  597. 'inactivity_return_url',
  598. $returnUrl,
  599. time() + 3600, // 1 hour expiry
  600. '/',
  601. null,
  602. $request->isSecure(),
  603. true, // httpOnly
  604. false,
  605. Cookie::SAMESITE_LAX
  606. )
  607. );
  608. }
  609. return $response;
  610. }
  611. /**
  612. * Helper function which determines if the user is using a deprecated browser.
  613. *
  614. *
  615. *
  616. * @param Request $request
  617. * @param DeviceDetectorService $deviceDetector
  618. *
  619. * @return bool
  620. */
  621. protected function isDeprecatedBrowser(Request $request, DeviceDetectorService $deviceDetector)
  622. {
  623. $dci = $deviceDetector->getClientInfoFromRequest($request);
  624. if (is_array($dci)) {
  625. // Check if the browser matches IE10 or lower (which we won't support in future).
  626. return $dci['type'] === 'browser' && $dci['short_name'] === 'IE' && floor($dci['version']) <= 10;
  627. }
  628. // If we didn't get an array of results, this is probably an automated action
  629. return true;
  630. }
  631. /**
  632. * Helper function to determine whether the User has any pending Role Invitations
  633. */
  634. private function userHasPendingInvitations(): bool
  635. {
  636. return $this->getUser()->hasUnsuppressedRoleInvitationsPendingApproval();
  637. }
  638. /**
  639. * Generate the Url to the role invitation listing page and
  640. * add a flash message to current session
  641. */
  642. private function pendingInvitationsUrlWithFlash(): string
  643. {
  644. $this->addFlash('info', 'You have pending invitations. Before you continue, please accept or decline all of your invitations.');
  645. return $this->generateUrl('infology_medbrief_role_invitation_list_pending');
  646. }
  647. /**
  648. * Generate the Url to the role invitation listing page without adding a flash message to current session
  649. * Used for AJAX calls where we want to redirect the user but not show a flash message as well
  650. */
  651. private function pendingInvitationsUrlWithoutFlash(): string
  652. {
  653. return $this->generateUrl('infology_medbrief_role_invitation_list_pending');
  654. }
  655. /**
  656. * Get all Projects the User has recently viewed
  657. *
  658. * @param ProjectRepository $projectRepository
  659. * @param UserHelper $userHelper
  660. * @param ProjectHelper $projectHelper
  661. * @param int $limit
  662. * @param bool $calculateUnreadMessages
  663. * @param MatchExpertUser $matchExpertUserService
  664. *
  665. * @return array ['projects' => Project[], 'userType' => string|null]
  666. */
  667. private function getRecentlyViewedProjects(
  668. ProjectRepository $projectRepository,
  669. UserHelper $userHelper,
  670. ProjectHelper $projectHelper,
  671. MatchExpertUser $matchExpertUserService,
  672. bool $calculateUnreadMessages = true,
  673. int $limit = 20
  674. ): array {
  675. $projects = $projectRepository->findRecentlyAccessedByUser($userHelper, $limit);
  676. // if calculating unread messages, set them on each Project entity
  677. if ($calculateUnreadMessages) {
  678. // Determine user type for displaying unread message counts (firm/expert)
  679. $userType = $matchExpertUserService->getUserType($this->getUser());
  680. // This sets the unread message counts on each Project entity
  681. $projectHelper->setUnreadMessageCount(iterator_to_array($projects), $userType, $userHelper->getUser());
  682. return ['projects' => $projects, 'userType' => $userType];
  683. }
  684. return ['projects' => $projects, 'userType' => null];
  685. }
  686. /**
  687. * Get all Projects the User has recently accepted
  688. *
  689. * @param RoleInvitationRepository $roleInvitationRepository
  690. * @param RoleParserService $roleParser
  691. * @param ProjectHelper $projectHelper
  692. * @param bool $calculateUnreadMessages
  693. * @param MatchExpertUser $matchExpertUserService
  694. *
  695. * @return array ['projects' => Project[], 'userType' => string|null]
  696. */
  697. private function getRecentlyAcceptedProjects(RoleInvitationRepository $roleInvitationRepository, RoleParserService $roleParser, ProjectHelper $projectHelper, MatchExpertUser $matchExpertUserService, bool $calculateUnreadMessages = true): array
  698. {
  699. /**
  700. * Not Accessed
  701. */
  702. $recentlyAccepted = $roleInvitationRepository->findLatestProjectRoleInvitationsByUser($this->getUser());
  703. // Map Role Invitations to obtain Projects via the RoleParserService
  704. $recentlyAccepted = array_map(fn (RoleInvitation $roleInvitation)
  705. => $roleParser->parseRole($roleInvitation)->getSubject(), $recentlyAccepted);
  706. // Filter out Projects with any type of deleted or archived status
  707. $recentlyAccepted = array_filter($recentlyAccepted, fn ($project): bool => !$project->isCloseInProgressOrComplete());
  708. // if calculating unread messages, set them on each Project entity
  709. if ($calculateUnreadMessages) {
  710. // Determine user type for displaying unread message counts (firm/expert)
  711. $userType = $matchExpertUserService->getUserType($this->getUser());
  712. // This sets the unread message counts on each Project entity
  713. $projectHelper->setUnreadMessageCount(iterator_to_array($recentlyAccepted), $userType, $this->getUser());
  714. return ['projects' => $recentlyAccepted, 'userType' => $userType];
  715. }
  716. return ['projects' => $recentlyAccepted, 'userType' => null];
  717. }
  718. /**
  719. * Get all the User's favourite Projects
  720. *
  721. * @param ProjectHelper $projectHelper
  722. * @param bool $calculateUnreadMessages
  723. * @param MatchExpertUser $matchExpertUserService
  724. *
  725. * @return array ['projects' => Project[], 'userType' => string|null]
  726. */
  727. private function getFavouriteProjects(ProjectHelper $projectHelper, MatchExpertUser $matchExpertUserService, bool $calculateUnreadMessages = true): array
  728. {
  729. $favouriteProjects = $this->getUser()->getFavouriteProjects()->toArray();
  730. // Filter out deleted and archived Projects
  731. $favouriteProjects = array_filter($favouriteProjects, fn ($project): bool => !$project->isDeleteStatusComplete() && !$project->isArchiveStatusComplete());
  732. // Converts favourite projects to project_id's and removes ones where access is no longer granted
  733. foreach ($favouriteProjects as $key => $project) {
  734. if (!$this->isGranted('READ', $project)) {
  735. unset($favouriteProjects[$key]);
  736. }
  737. }
  738. // if calculating unread messages, set them on each Project entity
  739. if ($calculateUnreadMessages) {
  740. // Determine user type for displaying unread message counts (firm/expert)
  741. $userType = $matchExpertUserService->getUserType($this->getUser());
  742. // This sets the unread message counts on each Project entity
  743. $projectHelper->setUnreadMessageCount(iterator_to_array($favouriteProjects), $userType, $this->getUser());
  744. return ['projects' => $favouriteProjects, 'userType' => $userType];
  745. }
  746. // TODO: create a UserProject Entity to store the date when the Project was favourited
  747. return ['projects' => $favouriteProjects, 'userType' => null];
  748. }
  749. /**
  750. * @param Project[] $projects
  751. * @param RenewalHelperService $renewalHelperService
  752. *
  753. * @return Projects[]|[]
  754. */
  755. private function getEligibleRenewalProjects(array $projects, RenewalHelperService $renewalHelperService): array
  756. {
  757. $eligibleProjectsToDisplayRenewalDate = array_filter($projects, fn ($project): ?bool => $renewalHelperService->isMatterEligibleForRenewal($project));
  758. return $this->sortProjectsByDateOrder($eligibleProjectsToDisplayRenewalDate, 'descending');
  759. }
  760. /**
  761. * Sort an array of Projects by their Updated date in specified order.
  762. *
  763. *
  764. *
  765. * @param array $projects
  766. * @param string $order
  767. *
  768. * @return array $projects
  769. */
  770. private function sortProjectsByDateOrder(array $projects, string $order = 'descending'): array
  771. {
  772. // Use usort to sort the array using the custom comparison function
  773. if ($order === 'descending') {
  774. usort($projects, self::compareByDateDescending(...));
  775. } else {
  776. usort($projects, self::compareByDateAscending(...));
  777. }
  778. return $projects;
  779. }
  780. /**
  781. * Callback function for the comparison of two Projects by Updated date Descending.
  782. *
  783. * @param Project $project1
  784. * @param Project $project2
  785. */
  786. private function compareByDateDescending($project1, $project2): bool
  787. {
  788. $date1 = $project1->getUpdated();
  789. $date2 = $project2->getUpdated();
  790. return $date2 <=> $date1;
  791. }
  792. /**
  793. * Callback function for the comparison of two Projects by Updated date Ascending.
  794. *
  795. * @param Project $project1
  796. * @param Project $project2
  797. */
  798. private function compareByDateAscending($project1, $project2): bool
  799. {
  800. $date1 = $project1->getUpdated();
  801. $date2 = $project2->getUpdated();
  802. return $date1 <=> $date2;
  803. }
  804. }