Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CustomerTokenService.php
Go to the documentation of this file.
1 <?php
8 
13 use Magento\Integration\Model\Oauth\TokenFactory as TokenModelFactory;
14 use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory as TokenCollectionFactory;
17 
19 {
25  private $tokenModelFactory;
26 
32  private $accountManagement;
33 
37  private $validatorHelper;
38 
44  private $tokenModelCollectionFactory;
45 
49  private $requestThrottler;
50 
59  public function __construct(
60  TokenModelFactory $tokenModelFactory,
61  AccountManagementInterface $accountManagement,
62  TokenCollectionFactory $tokenModelCollectionFactory,
63  CredentialsValidator $validatorHelper
64  ) {
65  $this->tokenModelFactory = $tokenModelFactory;
66  $this->accountManagement = $accountManagement;
67  $this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
68  $this->validatorHelper = $validatorHelper;
69  }
70 
74  public function createCustomerAccessToken($username, $password)
75  {
76  $this->validatorHelper->validate($username, $password);
77  $this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_CUSTOMER);
78  try {
79  $customerDataObject = $this->accountManagement->authenticate($username, $password);
80  } catch (\Exception $e) {
81  $this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER);
82  throw new AuthenticationException(
83  __(
84  'The account sign-in was incorrect or your account is disabled temporarily. '
85  . 'Please wait and try again later.'
86  )
87  );
88  }
89  $this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER);
90  return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken();
91  }
92 
103  {
104  $tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
105  if ($tokenCollection->getSize() == 0) {
106  throw new LocalizedException(__('This customer has no tokens.'));
107  }
108  try {
109  foreach ($tokenCollection as $token) {
110  $token->delete();
111  }
112  } catch (\Exception $e) {
113  throw new LocalizedException(__("The tokens couldn't be revoked."));
114  }
115  return true;
116  }
117 
124  private function getRequestThrottler()
125  {
126  if (!$this->requestThrottler instanceof RequestThrottler) {
127  return \Magento\Framework\App\ObjectManager::getInstance()->get(RequestThrottler::class);
128  }
129  return $this->requestThrottler;
130  }
131 }
__()
Definition: __.php:13
$accountManagement
__construct(TokenModelFactory $tokenModelFactory, AccountManagementInterface $accountManagement, TokenCollectionFactory $tokenModelCollectionFactory, CredentialsValidator $validatorHelper)