/** * Login registered users and initiate a session. * * Expects a POST. ex for JSON {"username":"******", "password":"******"} * * @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); }
/** * 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(); }
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('*****@*****.**', 'password'); $session->setCustomerDataAsLoggedIn($customer); }
/** * @magentoDataFixture Magento/Customer/_files/customer.php */ public function testCreateCustomerAccessToken() { $customerUserName = '******'; $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); }
/** * @magentoApiDataFixture Magento/Customer/_files/customer.php */ public function testCreateCustomerAccessToken() { $customerUserName = '******'; $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); }
/** * {@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(); }
/** * Login registered users and initiate a session. * * Expects a POST. ex for JSON {"username":"******", "password":"******"} * * @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); }
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()); }
/** * @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; }
/** * @magentoApiDataFixture Magento/Customer/_files/customer.php */ public function testCreateCustomerAccessToken() { $customerUserName = '******'; $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); }
/** * 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(); }
/** * 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); }
/** * @magentoAppArea frontend * @magentoDataFixture Magento/Customer/_files/customer.php */ public function testCreateNewCustomerFromClone() { $email = '*****@*****.**'; $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); }
/** * @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 = '*****@*****.**'; $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)); }
/** * {@inheritdoc} */ public function createCustomerAccessToken($username, $password) { $this->validatorHelper->validateCredentials($username, $password); $customerDataObject = $this->accountManagement->authenticate($username, $password); return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken(); }