ApiController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 'redirect_add' --
  208. * >> Requires query params named 'from-domain' (string) and 'to-domain' (string)
  209. *
  210. * Add or update a redirection from 'from-domain' to 'to-domain'
  211. *
  212. * @param ServerRequest $request
  213. * @return JsonResponse
  214. * @throws \Exception
  215. */
  216. public function addRedirectionAction(ServerRequest $request): JsonResponse
  217. {
  218. $this->assertIpAllowed();
  219. $fromDomain = (isset($queryParams['from-domain']) && $queryParams['from-domain']);
  220. $toDomain = (isset($queryParams['to-domain']) && $queryParams['to-domain']);
  221. $res = $this->siteController->addRedirection($fromDomain, $toDomain);
  222. if ($res === SiteController::REDIRECTION_UPDATED) {
  223. $msg = "An existing redirection has been updated ";
  224. } elseif ($res === SiteController::REDIRECTION_CREATED) {
  225. $msg = "A redirection has been added ";
  226. }
  227. $this->logger->info(sprintf(
  228. "OtAdmin API: " . $msg . " from " . $fromDomain . " to " . $toDomain
  229. ));
  230. return new JsonResponse(
  231. [
  232. 'msg' => $msg . " from " . $fromDomain . " to " . $toDomain,
  233. ]
  234. );
  235. }
  236. /**
  237. * -- Target of the route 'site_delete' --
  238. * >> Requires a query param named 'organization-id' (int)
  239. *
  240. * Proceeds to a soft-deletion of the organization's website
  241. *
  242. * In the case of a hard deletion, a special header is requested as a confirmation token. The header
  243. * shall be named 'Confirmation-Token' and its value shall be DEL-XXXX-YYYYMMDD, where XXXX is the id of
  244. * the organization owning the website, and YYYYMMDD is the date of the current day.
  245. *
  246. * /!\ Warning: this is a destructive operation
  247. *
  248. * @param ServerRequest $request
  249. * @return JsonResponse
  250. * @throws \Exception
  251. */
  252. public function deleteSiteAction(ServerRequest $request): JsonResponse
  253. {
  254. $this->assertIpAllowed();
  255. $organizationId = $this->getOrganizationId($request);
  256. $params = $request->getQueryParams();
  257. $hard = (isset($params['hard']) && $params['hard']);
  258. if ($hard) {
  259. $this->preventIfIsDubious();
  260. $this->preventOnMissingConfirmationToken($organizationId);
  261. }
  262. $rootUid = $this->siteController->deleteSiteAction($organizationId, $hard, true, true);
  263. $this->logger->info(sprintf(
  264. "OtAdmin API: The website with root uid " . $rootUid . " has been soft-deleted " .
  265. " (organization: " . $organizationId . ")"));
  266. $msg = $hard ?
  267. "The website with root uid " . $rootUid . " has been hard-deleted." :
  268. "The website with root uid " . $rootUid . " has been soft-deleted. Use the /site/undelete route to restore it.";
  269. return new JsonResponse(
  270. [
  271. 'organization_id' => $organizationId,
  272. 'msg' => $msg,
  273. 'root_uid' => $rootUid
  274. ]
  275. );
  276. }
  277. /**
  278. * -- Target of the route 'site_undelete' --
  279. * >> Requires a query param named 'organization-id' (int)
  280. *
  281. * Restore a soft-deleted organization's website
  282. *
  283. * @param ServerRequest $request
  284. * @return JsonResponse
  285. * @throws \Exception
  286. */
  287. public function undeleteSiteAction(ServerRequest $request): JsonResponse
  288. {
  289. $this->assertIpAllowed();
  290. $organizationId = $this->getOrganizationId($request);
  291. $rootUid = $this->siteController->undeleteSiteAction($organizationId);
  292. $this->logger->info(sprintf(
  293. "OtAdmin API: The website with root uid " . $rootUid . " has been restored " .
  294. " (organization: " . $organizationId . ")"));
  295. return new JsonResponse(
  296. [
  297. 'organization_id' => $organizationId,
  298. 'msg' => "The website with root uid " . $rootUid . " has been restored",
  299. 'root_uid' => $rootUid
  300. ]
  301. );
  302. }
  303. /**
  304. * -- Target of the route 'site_clearcache' --
  305. * >> Requires a query param named 'organization-id' (int)
  306. *
  307. * Clear the cache of the organization's website
  308. *
  309. * @param ServerRequest $request
  310. * @return JsonResponse
  311. * @throws \Exception
  312. */
  313. public function clearSiteCacheAction(ServerRequest $request): JsonResponse
  314. {
  315. $this->assertIpAllowed();
  316. $organizationId = $this->getOrganizationId($request);
  317. $queryParams = $request->getQueryParams();
  318. $clearAll = (isset($queryParams['all']) && $queryParams['all']);;
  319. $rootUid = $this->siteController->clearSiteCacheAction($organizationId, $clearAll);
  320. return new JsonResponse(
  321. [
  322. 'organization_id' => $organizationId,
  323. 'msg' => "The cache has been cleared for the website with root uid " . $rootUid . "",
  324. 'root_uid' => $rootUid
  325. ]
  326. );
  327. }
  328. /**
  329. * -- Target of the route 'site_setdomain' --
  330. * >> Requires a query param named 'organization-id' (int)
  331. * and a parameter named 'domain' (string)
  332. *
  333. * Set a new domain for the organization website
  334. *
  335. * @param ServerRequest $request
  336. * @return JsonResponse
  337. * @throws \Exception
  338. */
  339. public function setSiteCustomDomainAction(ServerRequest $request): JsonResponse
  340. {
  341. $this->assertIpAllowed();
  342. $organizationId = $this->getOrganizationId($request);
  343. $queryParams = $request->getQueryParams();
  344. $domain = $queryParams['domain'];
  345. if (!$domain) {
  346. throw new \RuntimeException("Missing 'domain' parameter");
  347. }
  348. $redirect = (isset($queryParams['redirect']) && $queryParams['redirect']);
  349. $rootUid = $this->siteController->setSiteCustomDomainAction($organizationId, $domain, $redirect);
  350. return new JsonResponse(
  351. [
  352. 'organization_id' => $organizationId,
  353. 'msg' => "The cache has been cleared for the website with root uid " . $rootUid . "",
  354. 'root_uid' => $rootUid
  355. ]
  356. );
  357. }
  358. /**
  359. * -- Target of the route 'site_resetperms' --
  360. * >> Requires a query param named 'organization-id' (int)
  361. *
  362. * Reset the permissions of the website be users (admin, editors...)
  363. *
  364. * @param ServerRequest $request
  365. * @return JsonResponse
  366. * @throws \Exception
  367. */
  368. public function resetBeUserPermsAction(ServerRequest $request): JsonResponse
  369. {
  370. $this->assertIpAllowed();
  371. $organizationId = $this->getOrganizationId($request);
  372. $rootUid = $this->siteController->resetBeUserPermsAction($organizationId);
  373. return new JsonResponse(
  374. [
  375. 'organization_id' => $organizationId,
  376. 'msg' => "The website with root uid " . $rootUid . " had its be users permissions reset",
  377. 'root_uid' => $rootUid
  378. ]
  379. );
  380. }
  381. /**
  382. * -- Target of the route 'site_status' --
  383. * >> Requires a query param named 'organization-id' (int)
  384. *
  385. * Returns the current status of the website
  386. *
  387. * @param ServerRequest $request
  388. * @param SiteController $siteController
  389. * @return JsonResponse
  390. * @throws Exception
  391. * @throws InvalidWebsiteConfigurationException
  392. * @throws NoSuchOrganizationException
  393. * @throws NoSuchRecordException
  394. * @throws NoSuchWebsiteException
  395. */
  396. public function getSiteStatusAction(
  397. ServerRequest $request
  398. ): JsonResponse
  399. {
  400. $this->assertIpAllowed();
  401. $organizationId = $this->getOrganizationId($request);
  402. $queryParams = $request->getQueryParams();
  403. $full = (isset($queryParams['full']) && $queryParams['full']);
  404. $status = $this->siteController->getSiteStatusAction($organizationId, $full);
  405. return new JsonResponse($status->toArray());
  406. }
  407. /**
  408. * -- Target of the route 'scan' --
  409. *
  410. * Scan the whole Typo3 database and return the results
  411. *
  412. * @param ServerRequest $request
  413. * @return JsonResponse
  414. * @throws \Exception
  415. */
  416. public function scanAllAction(ServerRequest $request): JsonResponse
  417. {
  418. $this->assertIpAllowed();
  419. $queryParams = $request->getQueryParams();
  420. $full = (isset($queryParams['full']) && $queryParams['full']);
  421. $results = $this->siteController->scanAllAction($full);
  422. return new JsonResponse($results);
  423. }
  424. /**
  425. * -- Target of the route 'delete-user-created-pages' --
  426. * >> Requires a query param named 'organization-id' (int)
  427. *
  428. * Delete all user-created pages for the organization's website
  429. *
  430. * /!\ Warning: this is a destructive operation
  431. *
  432. * @param ServerRequest $request
  433. * @return JsonResponse
  434. * @throws \Exception
  435. */
  436. public function deleteUserCreatedPagesAction(ServerRequest $request): JsonResponse
  437. {
  438. $this->assertIpAllowed();
  439. $organizationId = $this->getOrganizationId($request);
  440. $this->preventIfIsDubious();
  441. $this->preventOnMissingConfirmationToken($organizationId);
  442. $rootUid = $this->siteController->deleteUserCreatedPagesAction($organizationId);
  443. return new JsonResponse(
  444. [
  445. 'organization_id' => $organizationId,
  446. 'msg' => "The website with root uid " . $rootUid . " had its user-created pages deleted.",
  447. 'root_uid' => $rootUid
  448. ]
  449. );
  450. }
  451. }