本文整理汇总了PHP中Magento\Customer\Api\AccountManagementInterface::authenticate方法的典型用法代码示例。如果您正苦于以下问题:PHP AccountManagementInterface::authenticate方法的具体用法?PHP AccountManagementInterface::authenticate怎么用?PHP AccountManagementInterface::authenticate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Magento\Customer\Api\AccountManagementInterface
的用法示例。
在下文中一共展示了AccountManagementInterface::authenticate方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
/**
* Login registered users and initiate a session.
*
* Expects a POST. ex for JSON {"username":"user@magento.com", "password":"userpassword"}
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$credentials = null;
$httpBadRequestCode = 400;
/** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
$resultRaw = $this->resultRawFactory->create();
try {
$credentials = $this->helper->jsonDecode($this->getRequest()->getContent());
} catch (\Exception $e) {
return $resultRaw->setHttpResponseCode($httpBadRequestCode);
}
if (!$credentials || $this->getRequest()->getMethod() !== 'POST' || !$this->getRequest()->isXmlHttpRequest()) {
return $resultRaw->setHttpResponseCode($httpBadRequestCode);
}
$response = ['errors' => false, 'message' => __('Login successful.')];
try {
$customer = $this->customerAccountManagement->authenticate($credentials['username'], $credentials['password']);
$this->customerSession->setCustomerDataAsLoggedIn($customer);
$this->customerSession->regenerateId();
} catch (EmailNotConfirmedException $e) {
$response = ['errors' => true, 'message' => $e->getMessage()];
} catch (InvalidEmailOrPasswordException $e) {
$response = ['errors' => true, 'message' => $e->getMessage()];
} catch (\Exception $e) {
$response = ['errors' => true, 'message' => __('Something went wrong while validating the login and password.')];
}
/** @var \Magento\Framework\Controller\Result\Json $resultJson */
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData($response);
}
示例2: execute
/**
* Login post action
*
* @return \Magento\Framework\Controller\Result\Redirect
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
if ($this->_getSession()->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*/');
return $resultRedirect;
}
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
$this->_getSession()->setCustomerDataAsLoggedIn($customer);
$this->_getSession()->regenerateId();
} catch (EmailNotConfirmedException $e) {
$value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
$message = __('This account is not confirmed.' . ' <a href="%1">Click here</a> to resend confirmation email.', $value);
$this->messageManager->addError($message);
$this->_getSession()->setUsername($login['username']);
} catch (AuthenticationException $e) {
$message = __('Invalid login or password.');
$this->messageManager->addError($message);
$this->_getSession()->setUsername($login['username']);
} catch (\Exception $e) {
$this->messageManager->addError(__('There was an error validating the login and password.'));
}
} else {
$this->messageManager->addError(__('Login and password are required.'));
}
}
return $this->accountRedirect->getRedirect();
}
示例3: setUp
protected function setUp()
{
parent::setUp();
$logger = $this->getMock('Psr\\Log\\LoggerInterface', [], [], '', false);
$session = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Customer\\Model\\Session', [$logger]);
$this->accountManagement = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\AccountManagementInterface');
$customer = $this->accountManagement->authenticate('customer@example.com', 'password');
$session->setCustomerDataAsLoggedIn($customer);
}
示例4: testCreateCustomerAccessToken
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testCreateCustomerAccessToken()
{
$customerUserName = 'customer@example.com';
$password = 'password';
$accessToken = $this->tokenService->createCustomerAccessToken($customerUserName, $password);
$customerData = $this->accountManagement->authenticate($customerUserName, $password);
/** @var $token TokenModel */
$token = $this->tokenModel->loadByCustomerId($customerData->getId())->getToken();
$this->assertEquals($accessToken, $token);
}
示例5: testCreateCustomerAccessToken
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testCreateCustomerAccessToken()
{
$customerUserName = 'customer@example.com';
$password = 'password';
$serviceInfo = ['rest' => ['resourcePath' => self::RESOURCE_PATH_CUSTOMER_TOKEN, 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST]];
$requestData = ['username' => $customerUserName, 'password' => $password];
$accessToken = $this->_webApiCall($serviceInfo, $requestData);
$customerData = $this->customerAccountManagement->authenticate($customerUserName, $password);
/** @var $token TokenModel */
$token = $this->tokenModel->loadByCustomerId($customerData->getId())->getToken();
$this->assertEquals($accessToken, $token);
}
示例6: createCustomerAccessToken
/**
* {@inheritdoc}
*/
public function createCustomerAccessToken($username, $password)
{
$this->validatorHelper->validate($username, $password);
$this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_CUSTOMER);
try {
$customerDataObject = $this->accountManagement->authenticate($username, $password);
} catch (\Exception $e) {
$this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER);
throw new AuthenticationException(__('You did not sign in correctly or your account is temporarily disabled.'));
}
$this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER);
return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken();
}
示例7: execute
/**
* Login registered users and initiate a session.
*
* Expects a POST. ex for JSON {"username":"user@magento.com", "password":"userpassword"}
*
* @return \Magento\Framework\Controller\ResultInterface
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
$credentials = null;
$httpBadRequestCode = 400;
/** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
$resultRaw = $this->resultRawFactory->create();
try {
$credentials = $this->helper->jsonDecode($this->getRequest()->getContent());
} catch (\Exception $e) {
return $resultRaw->setHttpResponseCode($httpBadRequestCode);
}
if (!$credentials || $this->getRequest()->getMethod() !== 'POST' || !$this->getRequest()->isXmlHttpRequest()) {
return $resultRaw->setHttpResponseCode($httpBadRequestCode);
}
$response = ['errors' => false, 'message' => __('Login successful.')];
try {
$customer = $this->customerAccountManagement->authenticate($credentials['username'], $credentials['password']);
$this->customerSession->setCustomerDataAsLoggedIn($customer);
$this->customerSession->regenerateId();
$redirectRoute = $this->getAccountRedirect()->getRedirectCookie();
if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectRoute) {
$response['redirectUrl'] = $this->_redirect->success($redirectRoute);
$this->getAccountRedirect()->clearRedirectCookie();
}
} catch (EmailNotConfirmedException $e) {
$response = ['errors' => true, 'message' => $e->getMessage()];
} catch (InvalidEmailOrPasswordException $e) {
$response = ['errors' => true, 'message' => $e->getMessage()];
} catch (\Exception $e) {
$response = ['errors' => true, 'message' => __('Invalid login or password.')];
}
/** @var \Magento\Framework\Controller\Result\Json $resultJson */
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData($response);
}
示例8: testChangePassword
public function testChangePassword()
{
$serviceInfo = ['rest' => ['resourcePath' => self::RESOURCE_PATH . '/password', 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT, 'token' => $this->token]];
$requestData = ['currentPassword' => 'test@123', 'newPassword' => '123@test'];
$this->assertTrue($this->_webApiCall($serviceInfo, $requestData));
$customerResponseData = $this->customerAccountManagement->authenticate($this->customerData[CustomerInterface::EMAIL], '123@test');
$this->assertEquals($this->customerData[CustomerInterface::ID], $customerResponseData->getId());
}
示例9: auth
/**
* @return bool
*/
protected function auth()
{
if (!$this->customerSession->isLoggedIn()) {
list($login, $password) = $this->httpAuthentication->getCredentials();
try {
$customer = $this->customerAccountManagement->authenticate($login, $password);
$this->customerSession->setCustomerDataAsLoggedIn($customer);
$this->customerSession->regenerateId();
} catch (\Exception $e) {
$this->logger->critical($e);
}
}
if (!$this->customerSession->isLoggedIn()) {
$this->httpAuthentication->setAuthenticationFailed('RSS Feeds');
return false;
}
return true;
}
示例10: testCreateCustomerAccessToken
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testCreateCustomerAccessToken()
{
$customerUserName = 'customer@example.com';
$password = 'password';
$isTokenCorrect = false;
$serviceInfo = ['rest' => ['resourcePath' => self::RESOURCE_PATH_CUSTOMER_TOKEN, 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST]];
$requestData = ['username' => $customerUserName, 'password' => $password];
$accessToken = $this->_webApiCall($serviceInfo, $requestData);
$customerData = $this->customerAccountManagement->authenticate($customerUserName, $password);
/** @var $this->tokenCollection \Magento\Integration\Model\Resource\Oauth\Token\Collection */
$this->tokenCollection->addFilterByCustomerId($customerData->getId());
foreach ($this->tokenCollection->getItems() as $item) {
/** @var $item TokenModel */
if ($item->getToken() == $accessToken) {
$isTokenCorrect = true;
}
}
$this->assertTrue($isTokenCorrect);
}
示例11: execute
/**
* Login post action
*
* @return \Magento\Framework\Controller\Result\Redirect
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*/');
return $resultRedirect;
}
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
$this->session->setCustomerDataAsLoggedIn($customer);
$this->session->regenerateId();
if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
}
$redirectUrl = $this->accountRedirect->getRedirectCookie();
if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) {
$this->accountRedirect->clearRedirectCookie();
$resultRedirect = $this->resultRedirectFactory->create();
// URL is checked to be internal in $this->_redirect->success()
$resultRedirect->setUrl($this->_redirect->success($redirectUrl));
return $resultRedirect;
}
} catch (EmailNotConfirmedException $e) {
$value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
$message = __('This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.', $value);
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (UserLockedException $e) {
$message = __('The account is locked. Please wait and try again or contact %1.', $this->getScopeConfig()->getValue('contact/email/recipient_email'));
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (AuthenticationException $e) {
$message = __('Invalid login or password.');
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (LocalizedException $e) {
$message = $e->getMessage();
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (\Exception $e) {
// PA DSS violation: throwing or logging an exception here can disclose customer password
$this->messageManager->addError(__('An unspecified error occurred. Please contact us for assistance.'));
}
} else {
$this->messageManager->addError(__('A login and a password are required.'));
}
}
return $this->accountRedirect->getRedirect();
}
示例12: assertToken
/**
* Make sure provided token is valid and belongs to the specified user.
*
* @param string $accessToken
* @param string $userName
* @param string $password
*/
private function assertToken($accessToken, $userName, $password)
{
$customerData = $this->customerAccountManagement->authenticate($userName, $password);
/** @var $this ->tokenCollection \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection */
$this->tokenCollection->addFilterByCustomerId($customerData->getId());
$isTokenCorrect = false;
foreach ($this->tokenCollection->getItems() as $item) {
/** @var $item TokenModel */
if ($item->getToken() == $accessToken) {
$isTokenCorrect = true;
}
}
$this->assertTrue($isTokenCorrect);
}
示例13: testCreateNewCustomerFromClone
/**
* @magentoAppArea frontend
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testCreateNewCustomerFromClone()
{
$email = 'savecustomer@example.com';
$firstName = 'Firstsave';
$lastname = 'Lastsave';
$existingCustId = 1;
$existingCustomer = $this->customerRepository->getById($existingCustId);
$customerEntity = $this->customerFactory->create();
$this->dataObjectHelper->mergeDataObjects('\\Magento\\Customer\\Api\\Data\\CustomerInterface', $customerEntity, $existingCustomer);
$customerEntity->setEmail($email)->setFirstname($firstName)->setLastname($lastname)->setId(null);
$customer = $this->accountManagement->createAccount($customerEntity, 'aPassword');
$this->assertNotEmpty($customer->getId());
$this->assertEquals($email, $customer->getEmail());
$this->assertEquals($firstName, $customer->getFirstname());
$this->assertEquals($lastname, $customer->getLastname());
$this->accountManagement->authenticate($customer->getEmail(), 'aPassword', true);
}
示例14: testUpdateCustomer
/**
* @dataProvider updateCustomerDataProvider
* @magentoAppArea frontend
* @magentoDataFixture Magento/Customer/_files/customer.php
* @param int|null $defaultBilling
* @param int|null $defaultShipping
*/
public function testUpdateCustomer($defaultBilling, $defaultShipping)
{
$existingCustomerId = 1;
$email = 'savecustomer@example.com';
$firstName = 'Firstsave';
$lastName = 'Lastsave';
$customerBefore = $this->customerRepository->getById($existingCustomerId);
$customerData = array_merge($customerBefore->__toArray(), ['id' => 1, 'email' => $email, 'firstname' => $firstName, 'lastname' => $lastName, 'created_in' => 'Admin', 'password' => 'notsaved', 'default_billing' => $defaultBilling, 'default_shipping' => $defaultShipping]);
$customerDetails = $this->customerFactory->create();
$this->dataObjectHelper->populateWithArray($customerDetails, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
$this->customerRepository->save($customerDetails);
$customerAfter = $this->customerRepository->getById($existingCustomerId);
$this->assertEquals($email, $customerAfter->getEmail());
$this->assertEquals($firstName, $customerAfter->getFirstname());
$this->assertEquals($lastName, $customerAfter->getLastname());
$this->assertEquals($defaultBilling, $customerAfter->getDefaultBilling());
$this->assertEquals($defaultShipping, $customerAfter->getDefaultShipping());
$this->expectedDefaultShippingsInCustomerModelAttributes($existingCustomerId, $defaultBilling, $defaultShipping);
$this->assertEquals('Admin', $customerAfter->getCreatedIn());
$passwordFromFixture = 'password';
$this->accountManagement->authenticate($customerAfter->getEmail(), $passwordFromFixture);
$attributesBefore = $this->converter->toFlatArray($customerBefore, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
$attributesAfter = $this->converter->toFlatArray($customerAfter, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
// ignore 'updated_at'
unset($attributesBefore['updated_at']);
unset($attributesAfter['updated_at']);
$inBeforeOnly = array_diff_assoc($attributesBefore, $attributesAfter);
$inAfterOnly = array_diff_assoc($attributesAfter, $attributesBefore);
$expectedInBefore = ['firstname', 'lastname', 'email'];
foreach ($expectedInBefore as $key) {
$this->assertContains($key, array_keys($inBeforeOnly));
}
$this->assertContains('created_in', array_keys($inAfterOnly));
$this->assertContains('firstname', array_keys($inAfterOnly));
$this->assertContains('lastname', array_keys($inAfterOnly));
$this->assertContains('email', array_keys($inAfterOnly));
$this->assertNotContains('password_hash', array_keys($inAfterOnly));
}