RequestValidator.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Webapi\Controller\Rest;
  7. use Magento\Framework\Exception\AuthorizationException;
  8. use Magento\Framework\Webapi\Authorization;
  9. use Magento\Framework\Webapi\Rest\Request as RestRequest;
  10. use Magento\Store\Model\StoreManagerInterface;
  11. /**
  12. * This class is responsible for validating the request
  13. */
  14. class RequestValidator
  15. {
  16. /**
  17. * @var RestRequest
  18. */
  19. private $request;
  20. /**
  21. * @var Router
  22. */
  23. private $router;
  24. /**
  25. * @var StoreManagerInterface
  26. */
  27. private $storeManager;
  28. /**
  29. * @var Authorization
  30. */
  31. private $authorization;
  32. /**
  33. * Initialize dependencies
  34. *
  35. * @param RestRequest $request
  36. * @param Router $router
  37. * @param StoreManagerInterface $storeManager
  38. * @param Authorization $authorization
  39. */
  40. public function __construct(
  41. RestRequest $request,
  42. Router $router,
  43. StoreManagerInterface $storeManager,
  44. Authorization $authorization
  45. ) {
  46. $this->request = $request;
  47. $this->router = $router;
  48. $this->storeManager = $storeManager;
  49. $this->authorization = $authorization;
  50. }
  51. /**
  52. * Validate request
  53. *
  54. * @throws AuthorizationException
  55. * @throws \Magento\Framework\Webapi\Exception
  56. * @return void
  57. */
  58. public function validate()
  59. {
  60. $this->checkPermissions();
  61. $route = $this->router->match($this->request);
  62. if ($route->isSecure() && !$this->request->isSecure()) {
  63. throw new \Magento\Framework\Webapi\Exception(__('Operation allowed only in HTTPS'));
  64. }
  65. }
  66. /**
  67. * Perform authentication and authorization.
  68. *
  69. * @throws \Magento\Framework\Exception\AuthorizationException
  70. * @return void
  71. */
  72. private function checkPermissions()
  73. {
  74. $route = $this->router->match($this->request);
  75. if (!$this->authorization->isAllowed($route->getAclResources())) {
  76. $params = ['resources' => implode(', ', $route->getAclResources())];
  77. throw new AuthorizationException(
  78. __("The consumer isn't authorized to access %resources.", $params)
  79. );
  80. }
  81. }
  82. }