AnonymousResourceSecurity.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\WebapiSecurity\Model\Plugin;
  7. use Magento\Webapi\Model\Config\Converter;
  8. class AnonymousResourceSecurity
  9. {
  10. /**
  11. * Config path
  12. */
  13. const XML_ALLOW_INSECURE = 'webapi/webapisecurity/allow_insecure';
  14. /**
  15. * @var \Magento\Framework\App\Config\ReinitableConfigInterface
  16. */
  17. protected $config;
  18. /**
  19. * @var array
  20. */
  21. protected $resources;
  22. /**
  23. * AnonymousResourceSecurity constructor.
  24. *
  25. * @param \Magento\Framework\App\Config\ReinitableConfigInterface $config
  26. * @param array $resources
  27. */
  28. public function __construct(\Magento\Framework\App\Config\ReinitableConfigInterface $config, $resources)
  29. {
  30. $this->config = $config;
  31. $this->resources = $resources;
  32. }
  33. /**
  34. * Filter config values.
  35. *
  36. * @param Converter $subject
  37. * @param array $nodes
  38. * @return array
  39. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  40. */
  41. public function afterConvert(Converter $subject, $nodes)
  42. {
  43. if (empty($nodes)) {
  44. return $nodes;
  45. }
  46. $useInsecure = $this->config->getValue(self::XML_ALLOW_INSECURE);
  47. if ($useInsecure) {
  48. foreach (array_keys($this->resources) as $resource) {
  49. list($route, $requestType) = explode("::", $resource);
  50. if ($result = $this->getNode($route, $requestType, $nodes["routes"])) {
  51. if (isset($result[$requestType]['resources'])) {
  52. $result[$requestType]['resources'] = ['anonymous' => true];
  53. $nodes['routes'][$route] = $result;
  54. }
  55. if (isset($result[$requestType]['service']['class'])
  56. && isset($result[$requestType]['service']['method'])
  57. ) {
  58. $serviceName = $result[$requestType]['service']['class'];
  59. $serviceMethod = $result[$requestType]['service']['method'];
  60. $nodes['services'][$serviceName]['V1']['methods'][$serviceMethod]['resources'] = ['anonymous'];
  61. }
  62. }
  63. }
  64. }
  65. return $nodes;
  66. }
  67. /**
  68. * Get node by path.
  69. *
  70. * @param string $route
  71. * @param string $requestType
  72. * @param array $source
  73. * @return array|null
  74. */
  75. private function getNode($route, $requestType, $source)
  76. {
  77. if (isset($source[$route][$requestType])) {
  78. return $source[$route];
  79. }
  80. return null;
  81. }
  82. }