CoreApiAccess.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * Refer to LICENSE.txt distributed with the Temando Shipping module for notice of license
  4. */
  5. namespace Temando\Shipping\ViewModel\DataProvider;
  6. use Magento\Backend\Model\Auth\Session;
  7. use Magento\Backend\Model\Auth\StorageInterface;
  8. use Magento\Framework\Stdlib\DateTime\DateTime;
  9. use Magento\Integration\Model\Oauth\Token;
  10. use Magento\Security\Model\Config;
  11. /**
  12. * M2 Core API Access Provider
  13. *
  14. * @package Temando\Shipping\ViewModel
  15. * @author Christoph Aßmann <christoph.assmann@netresearch.de>
  16. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  17. * @link http://www.temando.com/
  18. */
  19. class CoreApiAccess implements CoreApiAccessInterface
  20. {
  21. /**
  22. * @var StorageInterface|Session
  23. */
  24. private $session;
  25. /**
  26. * @var Config
  27. */
  28. private $securityConfig;
  29. /**
  30. * @var Token
  31. */
  32. private $token;
  33. /**
  34. * @var DateTime
  35. */
  36. private $dateTime;
  37. /**
  38. * ApiAccess constructor.
  39. * @param StorageInterface $session
  40. * @param Config $securityConfig
  41. * @param Token $token
  42. * @param DateTime $dateTime
  43. */
  44. public function __construct(
  45. StorageInterface $session,
  46. Config $securityConfig,
  47. Token $token,
  48. DateTime $dateTime
  49. ) {
  50. $this->session = $session;
  51. $this->securityConfig = $securityConfig;
  52. $this->token = $token;
  53. $this->dateTime = $dateTime;
  54. }
  55. /**
  56. * Obtain authentication token for Magento REST API access.
  57. *
  58. * @return string
  59. */
  60. public function getAccessToken(): string
  61. {
  62. $adminId = $this->session->getUser()->getId();
  63. try {
  64. $token = $this->token->loadByAdminId($adminId)->getToken();
  65. if (!$token) {
  66. $token = $this->token->createAdminToken($adminId)->getToken();
  67. } else {
  68. $this->token->setCreatedAt($this->dateTime->gmtDate());
  69. $this->token->save();
  70. }
  71. } catch (\Exception $exception) {
  72. return '';
  73. }
  74. return (string) $token;
  75. }
  76. /**
  77. * Obtain admin session expiration timestamp.
  78. *
  79. * @return int
  80. */
  81. public function getSessionExpirationTime(): int
  82. {
  83. $sessionStart = $this->session->getUpdatedAt();
  84. $sessionDuration = $this->securityConfig->getAdminSessionLifetime();
  85. return $sessionStart + $sessionDuration;
  86. }
  87. }