ApiController.php 2.6 KB

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