ApiController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. <?php
  2. declare(strict_types=1);
  3. namespace Opentalent\OtAdmin\Http;
  4. use Doctrine\DBAL\Driver\Exception;
  5. use Opentalent\OtAdmin\Controller\SiteController;
  6. use Opentalent\OtCore\Exception\InvalidWebsiteConfigurationException;
  7. use Opentalent\OtCore\Exception\NoSuchOrganizationException;
  8. use Opentalent\OtCore\Exception\NoSuchRecordException;
  9. use Opentalent\OtCore\Exception\NoSuchWebsiteException;
  10. use Psr\Log\LoggerAwareInterface;
  11. use Psr\Log\LoggerAwareTrait;
  12. use Psr\Log\LoggerInterface;
  13. use TYPO3\CMS\Core\Http\JsonResponse;
  14. use TYPO3\CMS\Core\Http\ServerRequest;
  15. use TYPO3\CMS\Core\Utility\GeneralUtility;
  16. /**
  17. * Actions for Http API calls
  18. *
  19. * @package Opentalent\OtAdmin\Http
  20. */
  21. class ApiController implements LoggerAwareInterface
  22. {
  23. use LoggerAwareTrait;
  24. const PROD_FRONT_IP = "172.16.0.68";
  25. const PROD_BACK_IP = "172.16.0.70";
  26. const PROD_V2_IP = "172.16.0.35";
  27. const PUBLIC_PRODFRONT_IP = "141.94.117.38";
  28. const PUBLIC_PROD_BACK_IP = "141.94.117.40";
  29. const PUBLIC_PROD_V2_IP = "141.94.117.35";
  30. const array ALLOWED_IPS = [
  31. '/^127\.0\.0\.[0-1]$/', // Localhost
  32. '/^localhost$/', // Localhost
  33. '/^10\.8\.0\.\d{1,3}$/', // 10.8.0.[0-255] - VPN
  34. '/^141\.94\.117\.((3[3-9])|(4\d)|(5\d)|(6[0-1]))$/', // 141.94.117.[33-61] - Opentalent hosts public ips
  35. '/^172\.16\.0.\d{1,3}$/', // 172.16.0.[0-255] - Opentalent hosts private ips
  36. '/^172\.20\.\d{1,3}\.\d{1,3}$/', // 172.20.[0-255].[0-255] - Docker
  37. ];
  38. private readonly SiteController $siteController;
  39. public function __construct() {
  40. $this->siteController = GeneralUtility::makeInstance(SiteController::class);
  41. }
  42. /**
  43. * Returns true if the client Ip is allowed
  44. *
  45. * @param string $clientIp
  46. * @return bool
  47. */
  48. public static function isIpAllowed(string $clientIp): bool
  49. {
  50. foreach (self::ALLOWED_IPS as $ipRule) {
  51. if (preg_match($ipRule, $clientIp)) {
  52. return true;
  53. }
  54. }
  55. return false;
  56. }
  57. /**
  58. * Check that the client Ip is allowed, else throw a Runtime error
  59. *
  60. * @return bool
  61. */
  62. private function assertIpAllowed(): bool
  63. {
  64. $clientIp = $_SERVER['REMOTE_ADDR'];
  65. if (!self::isIpAllowed($clientIp)){
  66. $route = $_REQUEST['route'];
  67. $this->logger->error(sprintf(
  68. "OtAdmin API: an attempt was made to call the route " .
  69. $route . " from an non-allowed IP (" . $clientIp . ")"));
  70. throw new \RuntimeException("Not allowed");
  71. }
  72. return true;
  73. }
  74. /**
  75. * Lève une erreur si l'environnement est la prod et que la requête provient d'un autre environnement, car
  76. * cette requête a probablement été envoyée à la prod par erreur.
  77. *
  78. * Permet de sécuriser certaines opérations destructives, comme la suppression d'organisation.
  79. *
  80. * @return void
  81. */
  82. private function preventIfIsDubious(): void
  83. {
  84. if (
  85. $_SERVER &&
  86. (
  87. (
  88. $_SERVER['SERVER_ADDR'] === self::PROD_FRONT_IP
  89. && $_SERVER['REMOTE_ADDR'] !== self::PROD_V2_IP
  90. && $_SERVER['REMOTE_ADDR'] !== self::PROD_BACK_IP
  91. ) || (
  92. $_SERVER['SERVER_ADDR'] === self::PUBLIC_PRODFRONT_IP
  93. && $_SERVER['REMOTE_ADDR'] !== self::PUBLIC_PROD_V2_IP
  94. && $_SERVER['REMOTE_ADDR'] !== self::PUBLIC_PROD_BACK_IP
  95. )
  96. )
  97. ) {
  98. throw new \RuntimeException("Invalid client ip : " . $_SERVER['REMOTE_ADDR']);
  99. }
  100. }
  101. /**
  102. * Lève une erreur si le token de confirmation n'a pas était ajouté, ou si sa valeur est invalide.
  103. *
  104. * Permet de sécuriser certaines opérations destructives, comme la suppression d'organisation.
  105. *
  106. * @param int $organizationId
  107. * @return void
  108. */
  109. private function preventOnMissingConfirmationToken(int $organizationId): void
  110. {
  111. $headers = getallheaders();
  112. if (
  113. !isset($headers['Confirmation-Token']) ||
  114. $headers['Confirmation-Token'] !== 'DEL-'.$organizationId.'-'.date('Ymd')
  115. ) {
  116. throw new \RuntimeException("Missing or invalid confirmation token");
  117. }
  118. }
  119. /**
  120. * Retrieve the organization's id from the given request parameters
  121. *
  122. * @param ServerRequest $request
  123. * @return int
  124. */
  125. private function getOrganizationId(ServerRequest $request): int
  126. {
  127. $params = $request->getQueryParams();
  128. $organizationId = $params['organization-id'];
  129. if (!$organizationId) {
  130. throw new \RuntimeException("Missing parameter: 'organization-id'");
  131. }
  132. return (int)$organizationId;
  133. }
  134. /**
  135. * -- Target of the route 'site_infos' --
  136. *
  137. * Return the main information about the organization's website
  138. *
  139. * @param ServerRequest $request
  140. * @return JsonResponse
  141. * @throws \Exception
  142. */
  143. public function getSiteInfosAction(
  144. ServerRequest $request,
  145. SiteController $siteController
  146. ): JsonResponse
  147. {
  148. $this->assertIpAllowed();
  149. $organizationId = $this->getOrganizationId($request);
  150. $infos = $siteController->getSiteInfosAction($organizationId);
  151. return new JsonResponse($infos);
  152. }
  153. /**
  154. * -- Target of the route 'site_create' --
  155. * >> Requires a query param named 'organization-id' (int)
  156. *
  157. * Create the organization's website
  158. *
  159. * @param ServerRequest $request
  160. * @return JsonResponse
  161. * @throws \Exception
  162. */
  163. public function createSiteAction(ServerRequest $request): JsonResponse
  164. {
  165. $this->assertIpAllowed();
  166. $organizationId = $this->getOrganizationId($request);
  167. $rootUid = $this->siteController->createSiteAction($organizationId);
  168. $this->logger->info(sprintf(
  169. "OtAdmin API: A new website has been created with root page uid=" . $rootUid .
  170. " for the organization " . $organizationId));
  171. return new JsonResponse(
  172. [
  173. 'organization_id' => $organizationId,
  174. 'msg' => "A new website has been created with root page uid=" . $rootUid,
  175. 'root_uid' => $rootUid
  176. ]
  177. );
  178. }
  179. /**
  180. * -- Target of the route 'site_update' --
  181. * >> Requires a query param named 'organization-id' (int)
  182. *
  183. * Update the settings of the organization's website
  184. *
  185. * @param ServerRequest $request
  186. * @return JsonResponse
  187. * @throws \Exception
  188. */
  189. public function updateSiteConstantsAction(ServerRequest $request): JsonResponse
  190. {
  191. $this->assertIpAllowed();
  192. $organizationId = $this->getOrganizationId($request);
  193. $deep = (isset($queryParams['deep']) && $queryParams['deep']);
  194. $rootUid = $this->siteController->updateSiteAction($organizationId, $deep);
  195. $this->logger->info(sprintf(
  196. "OtAdmin API: The website with root uid " . $rootUid . " has been updated " .
  197. " (organization: " . $organizationId . ")"));
  198. return new JsonResponse(
  199. [
  200. 'organization_id' => $organizationId,
  201. 'msg' => "The website with root uid " . $rootUid . " has been updated",
  202. 'root_uid' => $rootUid
  203. ]
  204. );
  205. }
  206. /**
  207. * -- Target of the route 'site_make_it_work' --
  208. * >> Requires a query param named 'organization-id' (int)
  209. *
  210. * Updates the organization's website if it exists, restores
  211. * it if it has been deleted, or creates it if it does not exist.
  212. * It also removes any redirections that may have been set on the domain.
  213. *
  214. * @param ServerRequest $request
  215. * @return JsonResponse
  216. * @throws \Exception
  217. */
  218. public function justMakeItWorkSiteAction(ServerRequest $request): JsonResponse
  219. {
  220. $this->assertIpAllowed();
  221. $organizationId = $this->getOrganizationId($request);
  222. $rootUid = $this->siteController->justeMakeItWorkSiteAction($organizationId);
  223. $this->logger->info(sprintf(
  224. "OtAdmin API: The website with root uid " . $rootUid . " has been updated / restored / created " .
  225. " (organization: " . $organizationId . ")"));
  226. return new JsonResponse(
  227. [
  228. 'organization_id' => $organizationId,
  229. 'msg' => "The website with root uid " . $rootUid . " has been updated / restored / created",
  230. 'root_uid' => $rootUid
  231. ]
  232. );
  233. }
  234. /**
  235. * -- Target of the route 'redirect_add' --
  236. * >> Requires query params named 'from-domain' (string) and 'to-domain' (string)
  237. *
  238. * Add or update a redirection from 'from-domain' to 'to-domain'
  239. *
  240. * @param ServerRequest $request
  241. * @return JsonResponse
  242. * @throws \Exception
  243. */
  244. public function addRedirectionAction(ServerRequest $request): JsonResponse
  245. {
  246. $this->assertIpAllowed();
  247. $fromDomain = (isset($queryParams['from-domain']) && $queryParams['from-domain']);
  248. $toDomain = (isset($queryParams['to-domain']) && $queryParams['to-domain']);
  249. $res = $this->siteController->addRedirection($fromDomain, $toDomain);
  250. if ($res === SiteController::REDIRECTION_UPDATED) {
  251. $msg = "An existing redirection has been updated ";
  252. } elseif ($res === SiteController::REDIRECTION_CREATED) {
  253. $msg = "A redirection has been added ";
  254. }
  255. $this->logger->info(sprintf(
  256. "OtAdmin API: " . $msg . " from " . $fromDomain . " to " . $toDomain
  257. ));
  258. return new JsonResponse(
  259. [
  260. 'msg' => $msg . " from " . $fromDomain . " to " . $toDomain,
  261. ]
  262. );
  263. }
  264. /**
  265. * -- Target of the route 'site_delete' --
  266. * >> Requires a query param named 'organization-id' (int)
  267. *
  268. * Proceeds to a soft-deletion of the organization's website
  269. *
  270. * In the case of a hard deletion, a special header is requested as a confirmation token. The header
  271. * shall be named 'Confirmation-Token' and its value shall be DEL-XXXX-YYYYMMDD, where XXXX is the id of
  272. * the organization owning the website, and YYYYMMDD is the date of the current day.
  273. *
  274. * /!\ Warning: this is a destructive operation
  275. *
  276. * @param ServerRequest $request
  277. * @return JsonResponse
  278. * @throws \Exception
  279. */
  280. public function deleteSiteAction(ServerRequest $request): JsonResponse
  281. {
  282. $this->assertIpAllowed();
  283. $organizationId = $this->getOrganizationId($request);
  284. $params = $request->getQueryParams();
  285. $hard = (isset($params['hard']) && $params['hard']);
  286. if ($hard) {
  287. $this->preventIfIsDubious();
  288. $this->preventOnMissingConfirmationToken($organizationId);
  289. }
  290. $rootUid = $this->siteController->deleteSiteAction($organizationId, $hard, true, true);
  291. $msg = $hard ?
  292. "The website with root uid " . $rootUid . " has been hard-deleted." :
  293. "The website with root uid " . $rootUid . " has been soft-deleted. Use the /site/undelete route to restore it.";
  294. $this->logger->info(sprintf(
  295. "OtAdmin API: " . $msg . " (organization: " . $organizationId . ")")
  296. );
  297. return new JsonResponse(
  298. [
  299. 'organization_id' => $organizationId,
  300. 'msg' => $msg,
  301. 'root_uid' => $rootUid
  302. ]
  303. );
  304. }
  305. /**
  306. * -- Target of the route 'site_undelete' --
  307. * >> Requires a query param named 'organization-id' (int)
  308. *
  309. * Restore a soft-deleted organization's website
  310. *
  311. * @param ServerRequest $request
  312. * @return JsonResponse
  313. * @throws \Exception
  314. */
  315. public function undeleteSiteAction(ServerRequest $request): JsonResponse
  316. {
  317. $this->assertIpAllowed();
  318. $organizationId = $this->getOrganizationId($request);
  319. $rootUid = $this->siteController->undeleteSiteAction($organizationId);
  320. $this->logger->info(sprintf(
  321. "OtAdmin API: The website with root uid " . $rootUid . " has been restored " .
  322. " (organization: " . $organizationId . ")"));
  323. return new JsonResponse(
  324. [
  325. 'organization_id' => $organizationId,
  326. 'msg' => "The website with root uid " . $rootUid . " has been restored",
  327. 'root_uid' => $rootUid
  328. ]
  329. );
  330. }
  331. /**
  332. * -- Target of the route 'site_clearcache' --
  333. * >> Requires a query param named 'organization-id' (int)
  334. *
  335. * Clear the cache of the organization's website
  336. *
  337. * @param ServerRequest $request
  338. * @return JsonResponse
  339. * @throws \Exception
  340. */
  341. public function clearSiteCacheAction(ServerRequest $request): JsonResponse
  342. {
  343. $this->assertIpAllowed();
  344. $organizationId = $this->getOrganizationId($request);
  345. $queryParams = $request->getQueryParams();
  346. $clearAll = (isset($queryParams['all']) && $queryParams['all']);;
  347. $rootUid = $this->siteController->clearSiteCacheAction($organizationId, $clearAll);
  348. return new JsonResponse(
  349. [
  350. 'organization_id' => $organizationId,
  351. 'msg' => "The cache has been cleared for the website with root uid " . $rootUid . "",
  352. 'root_uid' => $rootUid
  353. ]
  354. );
  355. }
  356. /**
  357. * -- Target of the route 'site_setdomain' --
  358. * >> Requires a query param named 'organization-id' (int)
  359. * and a parameter named 'domain' (string)
  360. *
  361. * Set a new domain for the organization website
  362. *
  363. * @param ServerRequest $request
  364. * @return JsonResponse
  365. * @throws \Exception
  366. */
  367. public function setSiteCustomDomainAction(ServerRequest $request): JsonResponse
  368. {
  369. $this->assertIpAllowed();
  370. $organizationId = $this->getOrganizationId($request);
  371. $queryParams = $request->getQueryParams();
  372. $domain = $queryParams['domain'];
  373. if (!$domain) {
  374. throw new \RuntimeException("Missing 'domain' parameter");
  375. }
  376. $redirect = (isset($queryParams['redirect']) && $queryParams['redirect']);
  377. $rootUid = $this->siteController->setSiteCustomDomainAction($organizationId, $domain, $redirect);
  378. return new JsonResponse(
  379. [
  380. 'organization_id' => $organizationId,
  381. 'msg' => "The cache has been cleared for the website with root uid " . $rootUid . "",
  382. 'root_uid' => $rootUid
  383. ]
  384. );
  385. }
  386. /**
  387. * -- Target of the route 'site_resetperms' --
  388. * >> Requires a query param named 'organization-id' (int)
  389. *
  390. * Reset the permissions of the website be users (admin, editors...)
  391. *
  392. * @param ServerRequest $request
  393. * @return JsonResponse
  394. * @throws \Exception
  395. */
  396. public function resetBeUserPermsAction(ServerRequest $request): JsonResponse
  397. {
  398. $this->assertIpAllowed();
  399. $organizationId = $this->getOrganizationId($request);
  400. $rootUid = $this->siteController->resetBeUserPermsAction($organizationId);
  401. return new JsonResponse(
  402. [
  403. 'organization_id' => $organizationId,
  404. 'msg' => "The website with root uid " . $rootUid . " had its be users permissions reset",
  405. 'root_uid' => $rootUid
  406. ]
  407. );
  408. }
  409. /**
  410. * -- Target of the route 'site_status' --
  411. * >> Requires a query param named 'organization-id' (int)
  412. *
  413. * Returns the current status of the website
  414. *
  415. * @param ServerRequest $request
  416. * @param SiteController $siteController
  417. * @return JsonResponse
  418. * @throws Exception
  419. * @throws InvalidWebsiteConfigurationException
  420. * @throws NoSuchOrganizationException
  421. * @throws NoSuchRecordException
  422. * @throws NoSuchWebsiteException
  423. */
  424. public function getSiteStatusAction(
  425. ServerRequest $request
  426. ): JsonResponse
  427. {
  428. $this->assertIpAllowed();
  429. $organizationId = $this->getOrganizationId($request);
  430. $queryParams = $request->getQueryParams();
  431. $full = (isset($queryParams['full']) && $queryParams['full']);
  432. $status = $this->siteController->getSiteStatusAction($organizationId, $full);
  433. return new JsonResponse($status->toArray());
  434. }
  435. /**
  436. * -- Target of the route 'scan' --
  437. *
  438. * Scan the whole Typo3 database and return the results
  439. *
  440. * @param ServerRequest $request
  441. * @return JsonResponse
  442. * @throws \Exception
  443. */
  444. public function scanAllAction(ServerRequest $request): JsonResponse
  445. {
  446. $this->assertIpAllowed();
  447. $queryParams = $request->getQueryParams();
  448. $full = (isset($queryParams['full']) && $queryParams['full']);
  449. $results = $this->siteController->scanAllAction($full);
  450. return new JsonResponse($results);
  451. }
  452. /**
  453. * -- Target of the route 'delete-user-created-pages' --
  454. * >> Requires a query param named 'organization-id' (int)
  455. *
  456. * Delete all user-created pages for the organization's website
  457. *
  458. * /!\ Warning: this is a destructive operation
  459. *
  460. * @param ServerRequest $request
  461. * @return JsonResponse
  462. * @throws \Exception
  463. */
  464. public function deleteUserCreatedPagesAction(ServerRequest $request): JsonResponse
  465. {
  466. $this->assertIpAllowed();
  467. $organizationId = $this->getOrganizationId($request);
  468. $this->preventIfIsDubious();
  469. $this->preventOnMissingConfirmationToken($organizationId);
  470. $rootUid = $this->siteController->deleteUserCreatedPagesAction($organizationId);
  471. return new JsonResponse(
  472. [
  473. 'organization_id' => $organizationId,
  474. 'msg' => "The website with root uid " . $rootUid . " had its user-created pages deleted.",
  475. 'root_uid' => $rootUid
  476. ]
  477. );
  478. }
  479. }