Token.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * Refer to LICENSE.txt distributed with the Temando Shipping module for notice of license
  4. */
  5. namespace Temando\Shipping\Controller\Adminhtml\Authentication;
  6. use Magento\Backend\App\Action as BackendAction;
  7. use Magento\Backend\App\Action\Context;
  8. use Magento\Framework\App\Request\Http;
  9. use Magento\Framework\Controller\ResultFactory;
  10. use Temando\Shipping\Rest\AuthenticationInterface;
  11. use Temando\Shipping\Webservice\Config\WsConfigInterface;
  12. /**
  13. * Temando Session Token Action
  14. *
  15. * @package Temando\Shipping\Controller
  16. * @author Christoph Aßmann <christoph.assmann@netresearch.de>
  17. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  18. * @link http://www.temando.com/
  19. */
  20. class Token extends BackendAction
  21. {
  22. const ADMIN_RESOURCE = 'Magento_Sales::sales';
  23. /**
  24. * @var WsConfigInterface
  25. */
  26. private $config;
  27. /**
  28. * @var AuthenticationInterface
  29. */
  30. private $auth;
  31. /**
  32. * @param Context $context
  33. * @param WsConfigInterface $config
  34. * @param AuthenticationInterface $auth
  35. */
  36. public function __construct(
  37. Context $context,
  38. WsConfigInterface $config,
  39. AuthenticationInterface $auth
  40. ) {
  41. $this->config = $config;
  42. $this->auth = $auth;
  43. parent::__construct($context);
  44. }
  45. /**
  46. * Only grant access for GET requests coming in via Javascript XMLHttpRequest.
  47. *
  48. * @return bool
  49. */
  50. protected function _isAllowed()
  51. {
  52. /** @var Http $request */
  53. $request = $this->getRequest();
  54. if (!$request->isXmlHttpRequest()) {
  55. return false;
  56. }
  57. return parent::_isAllowed();
  58. }
  59. /**
  60. * Print the current user's session token.
  61. *
  62. * @return \Magento\Framework\Controller\ResultInterface
  63. * @throws \Magento\Framework\Exception\NotFoundException
  64. */
  65. public function execute()
  66. {
  67. $this->auth->connect($this->config->getAccountId(), $this->config->getBearerToken());
  68. $token = $this->auth->getSessionToken();
  69. $tokenTtl = $this->auth->getSessionTokenExpiry();
  70. $response = [
  71. 'temando_api_token' => $token,
  72. 'temando_api_token_ttl' => $tokenTtl,
  73. ];
  74. /** @var \Magento\Framework\Controller\Result\Json $result */
  75. $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);
  76. $result->setData($response);
  77. return $result;
  78. }
  79. }