SubdomainService.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. namespace App\Service\Typo3;
  3. use App\Entity\Access\Access;
  4. use App\Entity\Organization\Organization;
  5. use App\Entity\Organization\Subdomain;
  6. use App\Message\Command\MailerCommand;
  7. use App\Message\Command\Typo3\Typo3UpdateCommand;
  8. use App\Repository\Access\AccessRepository;
  9. use App\Repository\Organization\SubdomainRepository;
  10. use App\Service\Mailer\Model\SubdomainChangeModel;
  11. use App\Service\Organization\Utils as OrganizationUtils;
  12. use Doctrine\DBAL\Connection;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Symfony\Bundle\SecurityBundle\Security;
  15. use Symfony\Component\Console\Exception\InvalidArgumentException;
  16. use Symfony\Component\Messenger\MessageBusInterface;
  17. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  18. /**
  19. * Service de gestion des sous-domaines des utilisateurs
  20. */
  21. class SubdomainService
  22. {
  23. // Max number of subdomains that an organization can own
  24. const MAX_SUBDOMAINS_NUMBER = 3;
  25. // Validation regex for subdomains
  26. const RX_VALIDATE_SUBDOMAIN = '/^[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?$/';
  27. public function __construct(
  28. private readonly SubdomainRepository $subdomainRepository,
  29. private readonly EntityManagerInterface $em,
  30. private readonly MessageBusInterface $messageBus,
  31. private readonly OrganizationUtils $organizationUtils,
  32. private readonly BindFileService $bindFileService,
  33. private readonly AccessRepository $accessRepository,
  34. private readonly ParameterBagInterface $parameterBag
  35. ) {}
  36. /**
  37. * Is the organization allowed to register a new subdomain
  38. *
  39. * @param Organization $organization
  40. * @return bool
  41. */
  42. public function canRegisterNewSubdomain(Organization $organization): bool {
  43. return count($organization->getSubdomains()) < self::MAX_SUBDOMAINS_NUMBER;
  44. }
  45. /**
  46. * Is the input a valid value for a subdomain
  47. *
  48. * @see https://www.rfc-editor.org/rfc/rfc3986#section-3.2.2
  49. * @see https://www.rfc-editor.org/rfc/rfc1034#section-3.5
  50. * @see https://www.rfc-editor.org/rfc/rfc1123#section-2.1
  51. *
  52. * @param string $subdomainValue
  53. * @return bool
  54. */
  55. public function isValidSubdomain(string $subdomainValue): bool
  56. {
  57. return (bool)preg_match(self::RX_VALIDATE_SUBDOMAIN, $subdomainValue);
  58. }
  59. /**
  60. * Is the subdomain a reserved one
  61. * @see https://ressources.opentalent.fr/display/SPEC/Nom+de+sous+domaines+reserves+pour+2IOS
  62. *
  63. * @param string $subdomainValue
  64. * @return bool
  65. * @throws \Exception
  66. */
  67. public function isReservedSubdomain(string $subdomainValue): bool {
  68. $reservedSubdomains = $this->parameterBag->get('opentalent.subdomains')['reserved'];
  69. $subRegexes = array_map(
  70. function (string $s) { return '(\b' . trim($s, '^$/\s') . '\b)'; },
  71. $reservedSubdomains
  72. );
  73. $regex = '/^' . strtolower(implode("|", $subRegexes)) . '$/';
  74. return preg_match($regex, $subdomainValue) !== 0;
  75. }
  76. /**
  77. * Returns true if the subdomain has already been registered
  78. *
  79. * @param string $subdomainValue
  80. * @return bool
  81. */
  82. public function isRegistered(string $subdomainValue): bool {
  83. return count($this->subdomainRepository->findBy(['subdomain' => $subdomainValue])) !== 0;
  84. }
  85. /**
  86. * Register a new subdomain for the organization
  87. * Is $activate is true, makes this new subdomain the active one too.
  88. *
  89. * @param Organization $organization
  90. * @param string $subdomainValue
  91. * @param bool $activate
  92. * @return Subdomain
  93. */
  94. public function addNewSubdomain(
  95. Organization $organization,
  96. string $subdomainValue,
  97. bool $activate = false
  98. ): Subdomain {
  99. if (!$this->isValidSubdomain($subdomainValue)) {
  100. throw new \RuntimeException("Not a valid subdomain");
  101. }
  102. if (!$this->canRegisterNewSubdomain($organization)) {
  103. throw new \RuntimeException("This organization can not register new subdomains");
  104. }
  105. if ($this->isReservedSubdomain($subdomainValue)) {
  106. throw new \RuntimeException('This subdomain is not available');
  107. }
  108. if ($this->isRegistered($subdomainValue)) {
  109. throw new \RuntimeException('This subdomain is already registered');
  110. }
  111. $subdomain = new Subdomain();
  112. $subdomain->setSubdomain($subdomainValue);
  113. $subdomain->setOrganization($organization);
  114. $subdomain->setActive(false);
  115. $this->em->persist($subdomain);
  116. $this->em->flush();
  117. // Register into the BindFile (takes up to 5min to take effect)
  118. $this->bindFileService->registerSubdomain($subdomain->getSubdomain());
  119. if ($activate) {
  120. $subdomain = $this->activateSubdomain($subdomain);
  121. }
  122. return $subdomain;
  123. }
  124. /**
  125. * Makes the $subdomain the active one for the organization.
  126. *
  127. * @param Subdomain $subdomain
  128. * @return Subdomain
  129. */
  130. public function activateSubdomain(Subdomain $subdomain): Subdomain {
  131. $currentActiveSubdomain = $this->subdomainRepository->getActiveSubdomainOf($subdomain->getOrganization());
  132. if ($currentActiveSubdomain && $subdomain->getId() === $currentActiveSubdomain->getId()) {
  133. throw new \RuntimeException('The subdomain is already active');
  134. }
  135. if (!$subdomain->getId()) {
  136. throw new \RuntimeException('Can not activate a non-persisted subdomain');
  137. }
  138. $subdomain = $this->setOrganizationActiveSubdomain($subdomain);
  139. $this->renameAdminUserToMatchSubdomain($subdomain);
  140. // Update the typo3 website (asynchronously with messenger)
  141. $this->updateTypo3Website($subdomain->getOrganization());
  142. // Send confirmation email
  143. $this->sendConfirmationEmail($subdomain);
  144. return $subdomain;
  145. }
  146. /**
  147. * The subdomain becomes the only active subdomain of its organization.
  148. * New state is persisted is database.
  149. *
  150. * @param Subdomain $subdomain
  151. * @return Subdomain
  152. */
  153. protected function setOrganizationActiveSubdomain(Subdomain $subdomain): Subdomain {
  154. foreach ($subdomain->getOrganization()->getSubdomains() as $other) {
  155. if ($other !== $subdomain && $other->isActive()) {
  156. $other->setActive(false);
  157. }
  158. }
  159. $subdomain->setActive(true);
  160. // TODO: comprendre pourquoi ce refresh est indispensable pour que l'organisation soit à jour
  161. $this->em->flush();
  162. $this->em->refresh($subdomain->getOrganization());
  163. return $subdomain;
  164. }
  165. /**
  166. * Rename the admin user of the organization to match the given subdomain
  167. *
  168. * @param Subdomain $subdomain
  169. * @return void
  170. */
  171. protected function renameAdminUserToMatchSubdomain(Subdomain $subdomain): void {
  172. $adminAccess = $this->accessRepository->findAdminAccess($subdomain->getOrganization());
  173. $adminAccess->getPerson()->setUsername('admin' . $subdomain->getSubdomain());
  174. $this->em->flush();
  175. }
  176. /**
  177. * Trigger an update of the typo3 organization's website
  178. *
  179. * @param $organization
  180. * @return void
  181. */
  182. protected function updateTypo3Website(Organization $organization): void
  183. {
  184. $this->messageBus->dispatch(
  185. new Typo3UpdateCommand($organization->getId())
  186. );
  187. }
  188. /**
  189. * Build the data model for the confirmation email
  190. *
  191. * @param Subdomain $subdomain
  192. * @return SubdomainChangeModel
  193. */
  194. protected function getMailModel(Subdomain $subdomain): SubdomainChangeModel {
  195. $adminAccess = $this->accessRepository->findAdminAccess($subdomain->getOrganization());
  196. /** @phpstan-ignore-next-line */
  197. return (new SubdomainChangeModel())
  198. ->setOrganizationId($subdomain->getOrganization()->getId())
  199. ->setSubdomainId($subdomain->getId())
  200. ->setUrl($this->organizationUtils->getOrganizationWebsite($subdomain->getOrganization()))
  201. ->setSenderId($adminAccess->getId());
  202. }
  203. /**
  204. * Send the confirmation email to the organization after a new subdomain has been activated
  205. *
  206. * @param Subdomain $subdomain
  207. * @return void
  208. */
  209. protected function sendConfirmationEmail(Subdomain $subdomain): void {
  210. // TODO: revoir quel sender par défaut
  211. $model = $this->getMailModel($subdomain);
  212. // Envoi d'un email
  213. $this->messageBus->dispatch(
  214. new MailerCommand($model)
  215. );
  216. }
  217. }