1
0

ApiController.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCP\AppFramework;
  8. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  9. use OCP\AppFramework\Http\Attribute\PublicPage;
  10. use OCP\AppFramework\Http\Response;
  11. use OCP\IRequest;
  12. /**
  13. * Base class to inherit your controllers from that are used for RESTful APIs
  14. * @since 7.0.0
  15. */
  16. abstract class ApiController extends Controller {
  17. private $corsMethods;
  18. private $corsAllowedHeaders;
  19. private $corsMaxAge;
  20. /**
  21. * constructor of the controller
  22. * @param string $appName the name of the app
  23. * @param IRequest $request an instance of the request
  24. * @param string $corsMethods comma separated string of HTTP verbs which
  25. * should be allowed for websites or webapps when calling your API, defaults to
  26. * 'PUT, POST, GET, DELETE, PATCH'
  27. * @param string $corsAllowedHeaders comma separated string of HTTP headers
  28. * which should be allowed for websites or webapps when calling your API,
  29. * defaults to 'Authorization, Content-Type, Accept'
  30. * @param int $corsMaxAge number in seconds how long a preflighted OPTIONS
  31. * request should be cached, defaults to 1728000 seconds
  32. * @since 7.0.0
  33. */
  34. public function __construct($appName,
  35. IRequest $request,
  36. $corsMethods = 'PUT, POST, GET, DELETE, PATCH',
  37. $corsAllowedHeaders = 'Authorization, Content-Type, Accept',
  38. $corsMaxAge = 1728000) {
  39. parent::__construct($appName, $request);
  40. $this->corsMethods = $corsMethods;
  41. $this->corsAllowedHeaders = $corsAllowedHeaders;
  42. $this->corsMaxAge = $corsMaxAge;
  43. }
  44. /**
  45. * This method implements a preflighted cors response for you that you can
  46. * link to for the options request
  47. *
  48. * @NoAdminRequired
  49. * @NoCSRFRequired
  50. * @PublicPage
  51. * @since 7.0.0
  52. */
  53. #[NoCSRFRequired]
  54. #[PublicPage]
  55. public function preflightedCors() {
  56. if (isset($this->request->server['HTTP_ORIGIN'])) {
  57. $origin = $this->request->server['HTTP_ORIGIN'];
  58. } else {
  59. $origin = '*';
  60. }
  61. $response = new Response();
  62. $response->addHeader('Access-Control-Allow-Origin', $origin);
  63. $response->addHeader('Access-Control-Allow-Methods', $this->corsMethods);
  64. $response->addHeader('Access-Control-Max-Age', (string)$this->corsMaxAge);
  65. $response->addHeader('Access-Control-Allow-Headers', $this->corsAllowedHeaders);
  66. $response->addHeader('Access-Control-Allow-Credentials', 'false');
  67. return $response;
  68. }
  69. }