protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { $def = $this->manTrans->begin(); try { foreach ($this->DEFAULT_DWNL_TREE as $custId => $parentId) { $first = 'User' . $custId; $last = 'Last'; $email = "customer_{$custId}@test.com"; if ($custId != $parentId) { /* save parent ID to registry */ $referralCode = $this->mapCustomerMageIdByIndex[$parentId]; $this->toolReferral->replaceCodeInRegistry($referralCode); } /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */ $customer = $this->_manObj->create(\Magento\Customer\Api\Data\CustomerInterface::class); $customer->setEmail($email); $customer->setFirstname($first); $customer->setLastname($last); /* MOBI-427: change group ID for retail customers */ if (in_array($custId, $this->GROUP_RETAIL)) { $customer->setGroupId(BusinessCodesManager::M_CUST_GROUP_RETAIL); } /** @var \Magento\Customer\Api\Data\CustomerInterface $saved */ $saved = $this->repoCustomer->save($customer, $this->DEFAULT_PASSWORD_HASH); $this->mapCustomerMageIdByIndex[$custId] = $saved->getId(); $this->mapCustomerIndexByMageId[$saved->getId()] = $custId; } /* MOBI-426 : rename customer groups according to Generic App scheme. */ $this->subCustomerGroups->renameGroups(); $this->manTrans->commit($def); } finally { // transaction will be rolled back if commit is not done (otherwise - do nothing) $this->manTrans->end($def); } }
/** * Save newsletter subscription preference action * * @return void|null */ public function executeInternal() { if (!$this->formKeyValidator->validate($this->getRequest())) { return $this->_redirect('customer/account/'); } $customerId = $this->_customerSession->getCustomerId(); if ($customerId === null) { $this->messageManager->addError(__('Something went wrong while saving your subscription.')); } else { try { $customer = $this->customerRepository->getById($customerId); $storeId = $this->storeManager->getStore()->getId(); $customer->setStoreId($storeId); $this->customerRepository->save($customer); if ((bool) $this->getRequest()->getParam('is_subscribed', false)) { $this->subscriberFactory->create()->subscribeCustomerById($customerId); $this->messageManager->addSuccess(__('We saved the subscription.')); } else { $this->subscriberFactory->create()->unsubscribeCustomerById($customerId); $this->messageManager->addSuccess(__('We removed the subscription.')); } } catch (\Exception $e) { $this->messageManager->addError(__('Something went wrong while saving your subscription.')); } } $this->_redirect('customer/account/'); }
/** * Unlock customer on success login attempt. * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { /** @var \Magento\Customer\Model\Customer $model */ $customerModel = $observer->getEvent()->getData('model'); $customer = $this->customerRepository->getById($customerModel->getId()); $this->accountManagementHelper->processUnlockData($customer->getId()); $this->customerRepository->save($customer); return $this; }
/** * Customer locking implementation * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $username = $observer->getEvent()->getData('username'); $customer = $this->customerRepository->get($username); if ($customer && $customer->getId()) { $this->accountManagementHelper->processCustomerLockoutData($customer->getId()); $this->customerRepository->save($customer); } return $this; }
/** * Upgrade customer password hash when customer has logged in * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { $password = $observer->getEvent()->getData('password'); /** @var \Magento\Customer\Model\Customer $model */ $model = $observer->getEvent()->getData('model'); $customer = $this->customerRepository->getById($model->getId()); $customerSecure = $this->customerRegistry->retrieveSecureData($model->getId()); if (!$this->encryptor->validateHashVersion($customerSecure->getPasswordHash(), true)) { $customerSecure->setPasswordHash($this->encryptor->getHash($password, true)); $this->customerRepository->save($customer); } }
/** * @magentoAppArea adminhtml * @magentoDataFixture Magento/Newsletter/_files/subscribers.php */ public function testCustomerUpdatedEmail() { $objectManager = Bootstrap::getObjectManager(); /** @var \Magento\Newsletter\Model\Subscriber $subscriber */ $subscriber = $objectManager->create('Magento\\Newsletter\\Model\\Subscriber'); $subscriber->loadByEmail('*****@*****.**'); $this->assertTrue($subscriber->isSubscribed()); $this->assertEquals(1, (int) $subscriber->getCustomerId()); $customer = $this->customerRepository->getById(1); $customer->setEmail('*****@*****.**'); $this->customerRepository->save($customer); $subscriber->loadByEmail('*****@*****.**'); $this->assertTrue($subscriber->isSubscribed()); $this->assertEquals(1, (int) $subscriber->getCustomerId()); }
/** * Check Captcha On Forgot Password Page * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $captchaModel = $this->helper->getCaptcha(self::FORM_ID); if ($captchaModel->isRequired()) { /** @var \Magento\Framework\App\Action\Action $controller */ $controller = $observer->getControllerAction(); if (!$captchaModel->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), self::FORM_ID))) { try { $customer = $this->customerRepository->getById($this->customerSession->getCustomerId()); $this->accountManagementHelper->processCustomerLockoutData($customer->getId()); $this->customerRepository->save($customer); } catch (NoSuchEntityException $e) { //do nothing as customer existance is validated later in authenticate method } $this->workWithLock(); $this->messageManager->addError(__('Incorrect CAPTCHA')); $this->actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); $this->redirect->redirect($controller->getResponse(), '*/*/edit'); } } $customer = $this->customerSession->getCustomer(); $login = $customer->getEmail(); $captchaModel->logAttempt($login); return $this; }
/** * {@inheritdoc} */ public function unlock($customerId) { $customerSecure = $this->customerRegistry->retrieveSecureData($customerId); $customerSecure->setFailuresNum(0); $customerSecure->setFirstFailure(null); $customerSecure->setLockExpires(null); $this->customerRepository->save($this->customerRepository->getById($customerId)); }
/** * Populate customer model * * @param Quote $quote * @return void */ public function populateCustomerInfo(QuoteEntity $quote) { $customer = $quote->getCustomer(); if (!$customer->getId()) { $customer = $this->accountManagement->createAccountWithPasswordHash($customer, $quote->getPasswordHash()); $quote->setCustomer($customer); } else { $this->customerRepository->save($customer); } if (!$quote->getBillingAddress()->getId() && $customer->getDefaultBilling()) { $quote->getBillingAddress()->importCustomerAddressData($this->customerAddressRepository->getById($customer->getDefaultBilling())); $quote->getBillingAddress()->setCustomerAddressId($customer->getDefaultBilling()); } if (!$quote->getShippingAddress()->getSameAsBilling() && !$quote->getBillingAddress()->getId() && $customer->getDefaultShipping()) { $quote->getShippingAddress()->importCustomerAddressData($this->customerAddressRepository->getById($customer->getDefaultShipping())); $quote->getShippingAddress()->setCustomerAddressId($customer->getDefaultShipping()); } }
/** * @magentoDbIsolation enabled */ public function testIsConfirmedStatusConfirmationIsNotRequired() { $password = '******'; /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */ $customer = $this->_customerFactory->create()->setConfirmation(true)->setFirstname('firstname')->setLastname('lastname')->setEmail('*****@*****.**'); $customer = $this->_customerRepository->save($customer, $password); $this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customer->getId()); $this->assertEquals('Confirmation Not Required', $this->_block->getIsConfirmedStatus()); }
/** * Customer mass assign group action * * @param AbstractCollection $collection * @return \Magento\Backend\Model\View\Result\Redirect */ protected function massAction(AbstractCollection $collection) { $customersUpdated = 0; foreach ($collection->getAllIds() as $customerId) { // Verify customer exists $customer = $this->customerRepository->getById($customerId); $customer->setGroupId($this->getRequest()->getParam('group')); $this->customerRepository->save($customer); $customersUpdated++; } if ($customersUpdated) { $this->messageManager->addSuccess(__('A total of %1 record(s) were updated.', $customersUpdated)); } /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $resultRedirect->setPath($this->getComponentRefererUrl()); return $resultRedirect; }
/** * Change customer password action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->formKeyValidator->validate($this->getRequest())) { $resultRedirect->setPath('*/*/edit'); return $resultRedirect; } if ($this->getRequest()->isPost()) { $customerId = $this->_getSession()->getCustomerId(); $customer = $this->customerExtractor->extract('customer_account_edit', $this->_request); $customer->setId($customerId); if ($customer->getAddresses() == null) { $customer->setAddresses($this->customerRepository->getById($customerId)->getAddresses()); } if ($this->getRequest()->getParam('change_password')) { $currPass = $this->getRequest()->getPost('current_password'); $newPass = $this->getRequest()->getPost('password'); $confPass = $this->getRequest()->getPost('password_confirmation'); if (strlen($newPass)) { if ($newPass == $confPass) { try { $customerEmail = $this->customerRepository->getById($customerId)->getEmail(); $this->customerAccountManagement->changePassword($customerEmail, $currPass, $newPass); } catch (AuthenticationException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('Something went wrong while changing the password.')); } } else { $this->messageManager->addError(__('Confirm your new password.')); } } else { $this->messageManager->addError(__('Please enter new password.')); } } try { $this->customerRepository->save($customer); } catch (AuthenticationException $e) { $this->messageManager->addError($e->getMessage()); } catch (InputException $e) { $this->messageManager->addException($e, __('Invalid input')); } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t save the customer.') . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>'); } if ($this->messageManager->getMessages()->getCount() > 0) { $this->_getSession()->setCustomerFormData($this->getRequest()->getPostValue()); $resultRedirect->setPath('*/*/edit'); return $resultRedirect; } $this->messageManager->addSuccess(__('You saved the account information.')); $resultRedirect->setPath('customer/account'); return $resultRedirect; } $resultRedirect->setPath('*/*/edit'); return $resultRedirect; }
/** * Unlock specified customer * * @return \Magento\Backend\Model\View\Result\Redirect */ public function execute() { $customerId = $this->getRequest()->getParam('customer_id'); try { // unlock customer if ($customerId) { $customer = $this->customerRepository->getById($customerId); $this->accountManagementHelper->processUnlockData($customerId); $this->customerRepository->save($customer); $this->getMessageManager()->addSuccess(__('Customer has been unlocked successfully.')); } } catch (\Exception $e) { $this->messageManager->addError($e->getMessage()); } /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); return $resultRedirect->setPath('customer/index/edit', ['id' => $customerId]); }
/** * @magentoAppArea frontend * @magentoDataFixture Magento/Customer/_files/customer.php * @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php */ public function testUpdateCustomerDeleteAllAddressesWithEmptyArray() { $customerId = 1; $customer = $this->customerRepository->getById($customerId); $customerDetails = $customer->__toArray(); $newCustomerEntity = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($newCustomerEntity, $customerDetails, '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $newCustomerEntity->setId($customer->getId())->setAddresses([]); $this->customerRepository->save($newCustomerEntity); $newCustomerDetails = $this->customerRepository->getById($customerId); //Verify that old addresses are removed $this->assertEquals(0, count($newCustomerDetails->getAddresses())); }
/** * Change customer password action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function executeInternal() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/edit'); } if ($this->getRequest()->isPost()) { $customerId = $this->session->getCustomerId(); $currentCustomer = $this->customerRepository->getById($customerId); // Prepare new customer data $customer = $this->customerExtractor->extract('customer_account_edit', $this->_request); $customer->setId($customerId); if ($customer->getAddresses() == null) { $customer->setAddresses($currentCustomer->getAddresses()); } // Change customer password if ($this->getRequest()->getParam('change_password')) { $this->changeCustomerPassword($currentCustomer->getEmail()); } try { $this->customerRepository->save($customer); } catch (AuthenticationException $e) { $this->messageManager->addError($e->getMessage()); } catch (InputException $e) { $this->messageManager->addException($e, __('Invalid input')); } catch (\Exception $e) { $message = __('We can\'t save the customer.') . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>'; $this->messageManager->addException($e, $message); } if ($this->messageManager->getMessages()->getCount() > 0) { $this->session->setCustomerFormData($this->getRequest()->getPostValue()); return $resultRedirect->setPath('*/*/edit'); } $this->messageManager->addSuccess(__('You saved the account information.')); return $resultRedirect->setPath('customer/account'); } return $resultRedirect->setPath('*/*/edit'); }
/** * {@inheritdoc} */ protected function _afterDelete(\Magento\Framework\DataObject $address) { if ($address->getId()) { $customer = $this->customerRepository->getById($address->getCustomerId()); if ($customer->getDefaultBilling() == $address->getId()) { $customer->setDefaultBilling(null); } if ($customer->getDefaultShipping() == $address->getId()) { $customer->setDefaultShipping(null); } $this->customerRepository->save($customer); } return parent::_afterDelete($address); }
/** * Save customer with error catching * * @param CustomerInterface $customer * @return void */ protected function saveCustomer(CustomerInterface $customer) { try { $this->customerRepository->save($customer); } catch (\Magento\Framework\Exception\InputException $e) { $this->getMessageManager()->addError($this->getErrorWithCustomerId($e->getMessage())); $this->logger->critical($e); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->getMessageManager()->addError($this->getErrorWithCustomerId($e->getMessage())); $this->logger->critical($e); } catch (\Exception $e) { $this->getMessageManager()->addError($this->getErrorWithCustomerId('We can\'t save the customer.')); $this->logger->critical($e); } }
/** * @Given customer accounts: */ public function customerAccounts(TableNode $customerAccountTable) { foreach ($customerAccountTable as $row) { // Check if the customer already exists. If it does, no need to // re-create it. If it doesn't, catch the exception and create // the customer account. try { $customer = $this->customerRepository->get($row['email_address']); } catch (NoSuchEntityException $e) { $customer = $this->customerFactory->create(); $customer->setFirstname($row['firstname'])->setLastname($row['lastname'])->setEmail($row['email_address']); $this->customerRepository->save($customer); } } }
/** * Change customer email or password action * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/edit'); } if ($this->getRequest()->isPost()) { $currentCustomerDataObject = $this->getCurrentCustomerDataObject(); $customerCandidateDataObject = $this->populateNewCustomerDataObject($this->_request, $currentCustomerDataObject); try { // whether a customer enabled change email option $this->changeEmail($currentCustomerDataObject); // whether a customer enabled change password option $isPasswordChanged = $this->changePassword($currentCustomerDataObject); $this->customerRepository->save($customerCandidateDataObject); $this->getEmailNotification()->sendNotificationEmailsIfRequired($currentCustomerDataObject, $customerCandidateDataObject, $isPasswordChanged); $this->dispatchSuccessEvent($customerCandidateDataObject); $this->messageManager->addSuccess(__('You saved the account information.')); return $resultRedirect->setPath('customer/account'); } catch (InvalidEmailOrPasswordException $e) { $this->messageManager->addError($e->getMessage()); } catch (UserLockedException $e) { $this->session->logout(); $this->session->start(); $this->messageManager->addError($e->getMessage()); return $resultRedirect->setPath('customer/account/login'); } catch (InputException $e) { $this->messageManager->addError($e->getMessage()); foreach ($e->getErrors() as $error) { $this->messageManager->addError($error->getMessage()); } } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t save the customer.')); } $this->session->setCustomerFormData($this->getRequest()->getPostValue()); return $resultRedirect->setPath('*/*/edit'); } return $resultRedirect->setPath('*/*/edit'); }
/** * Change reset password link token * * Stores new reset password link token * * @param CustomerInterface $customer * @param string $passwordLinkToken * @return bool * @throws InputException */ public function changeResetPasswordLinkToken($customer, $passwordLinkToken) { if (!is_string($passwordLinkToken) || empty($passwordLinkToken)) { throw new InputException(__(InputException::INVALID_FIELD_VALUE, ['value' => $passwordLinkToken, 'fieldName' => 'password reset token'])); } if (is_string($passwordLinkToken) && !empty($passwordLinkToken)) { $customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId()); $customerSecure->setRpToken($passwordLinkToken); $customerSecure->setRpTokenCreatedAt((new \DateTime())->format(DateTime::DATETIME_PHP_FORMAT)); $this->customerRepository->save($customer); } return true; }
/** * Add address to the customer, created out of a Data Object * * TODO refactor in scope of MAGETWO-19930 * * @param \Magento\Customer\Api\Data\AddressInterface $address * @return $this */ public function addCustomerAddress(\Magento\Customer\Api\Data\AddressInterface $address) { $addresses = (array) $this->getCustomer()->getAddresses(); $addresses[] = $address; $this->getCustomer()->setAddresses($addresses); $this->updateCustomerData($this->customerRepository->save($this->getCustomer())); return $this; }