/** * Send confirmation link to specified email * * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page */ public function execute() { if ($this->session->isLoggedIn()) { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/*/'); return $resultRedirect; } // try to confirm by email $email = $this->getRequest()->getPost('email'); if ($email) { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); try { $this->customerAccountManagement->resendConfirmation($email, $this->storeManager->getStore()->getWebsiteId()); $this->messageManager->addSuccess(__('Please check your email for confirmation key.')); } catch (InvalidTransitionException $e) { $this->messageManager->addSuccess(__('This email does not require confirmation.')); } catch (\Exception $e) { $this->messageManager->addException($e, __('Wrong email.')); $resultRedirect->setPath('*/*/*', ['email' => $email, '_secure' => true]); return $resultRedirect; } $this->session->setUsername($email); $resultRedirect->setPath('*/*/index', ['_secure' => true]); return $resultRedirect; } /** @var \Magento\Framework\View\Result\Page $resultPage */ $resultPage = $this->resultPageFactory->create(); $resultPage->getLayout()->getBlock('accountConfirmation')->setEmail($this->getRequest()->getParam('email', $email)); return $resultPage; }
/** * Resetting password handler * * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page */ public function executeInternal() { $resetPasswordToken = (string) $this->getRequest()->getParam('token'); $customerId = (int) $this->getRequest()->getParam('id'); $isDirectLink = $resetPasswordToken != '' && $customerId != 0; if (!$isDirectLink) { $resetPasswordToken = (string) $this->session->getRpToken(); $customerId = (int) $this->session->getRpCustomerId(); } try { $this->accountManagement->validateResetPasswordLinkToken($customerId, $resetPasswordToken); if ($isDirectLink) { $this->session->setRpToken($resetPasswordToken); $this->session->setRpCustomerId($customerId); $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/*/createpassword'); return $resultRedirect; } else { /** @var \Magento\Framework\View\Result\Page $resultPage */ $resultPage = $this->resultPageFactory->create(); $resultPage->getLayout()->getBlock('resetPassword')->setCustomerId($customerId)->setResetPasswordLinkToken($resetPasswordToken); return $resultPage; } } catch (\Exception $exception) { $this->messageManager->addError(__('Your password reset link has expired.')); /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/*/forgotpassword'); return $resultRedirect; } }
/** * Forgot customer password action * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $email = (string) $this->getRequest()->getPost('email'); if ($email) { if (!\Zend_Validate::is($email, 'EmailAddress')) { $this->session->setForgottenEmail($email); $this->messageManager->addErrorMessage(__('Please correct the email address.')); return $resultRedirect->setPath('*/*/forgotpassword'); } try { $this->customerAccountManagement->initiatePasswordReset($email, AccountManagement::EMAIL_RESET); } catch (NoSuchEntityException $exception) { // Do nothing, we don't want anyone to use this action to determine which email accounts are registered. } catch (SecurityViolationException $exception) { $this->messageManager->addErrorMessage($exception->getMessage()); return $resultRedirect->setPath('*/*/forgotpassword'); } catch (\Exception $exception) { $this->messageManager->addExceptionMessage($exception, __('We\'re unable to send the password reset email.')); return $resultRedirect->setPath('*/*/forgotpassword'); } $this->messageManager->addSuccessMessage($this->getSuccessMessage($email)); return $resultRedirect->setPath('*/*/'); } else { $this->messageManager->addErrorMessage(__('Please enter your email.')); return $resultRedirect->setPath('*/*/forgotpassword'); } }
/** * 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(); }
/** * Validates that the email address isn't being used by a different account. * * @param string $email * @throws \Magento\Framework\Exception\LocalizedException * @return void */ protected function validateEmailAvailable($email) { $websiteId = $this->_storeManager->getStore()->getWebsiteId(); if ($this->_customerSession->getCustomerDataObject()->getEmail() !== $email && !$this->customerAccountManagement->isEmailAvailable($email, $websiteId)) { throw new \Magento\Framework\Exception\LocalizedException(__('This email address is already assigned to another user.')); } }
/** * 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); }
/** * Forgot customer password action * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $email = (string) $this->getRequest()->getPost('email'); if ($email) { if (!\Zend_Validate::is($email, 'EmailAddress')) { $this->_getSession()->setForgottenEmail($email); $this->messageManager->addError(__('Please correct the email address.')); $resultRedirect->setPath('*/*/forgotpassword'); return $resultRedirect; } try { $this->customerAccountManagement->initiatePasswordReset($email, AccountManagement::EMAIL_RESET); } catch (NoSuchEntityException $e) { // Do nothing, we don't want anyone to use this action to determine which email accounts are registered. } catch (\Exception $exception) { $this->messageManager->addException($exception, __('Unable to send password reset email.')); $resultRedirect->setPath('*/*/forgotpassword'); return $resultRedirect; } $email = $this->escaper->escapeHtml($email); // @codingStandardsIgnoreStart $this->messageManager->addSuccess(__('If there is an account associated with %1 you will receive an email with a link to reset your password.', $email)); // @codingStandardsIgnoreEnd $resultRedirect->setPath('*/*/'); return $resultRedirect; } else { $this->messageManager->addError(__('Please enter your email.')); $resultRedirect->setPath('*/*/forgotpassword'); return $resultRedirect; } }
/** * {@inheritdoc} */ public function create($orderId) { $order = $this->orderRepository->get($orderId); if ($order->getCustomerId()) { throw new AlreadyExistsException(__("This order already has associated customer account")); } $customerData = $this->objectCopyService->copyFieldsetToTarget('order_address', 'to_customer', $order->getBillingAddress(), []); $addresses = $order->getAddresses(); foreach ($addresses as $address) { $addressData = $this->objectCopyService->copyFieldsetToTarget('order_address', 'to_customer_address', $address, []); /** @var \Magento\Customer\Api\Data\AddressInterface $customerAddress */ $customerAddress = $this->addressFactory->create(['data' => $addressData]); if (is_string($address->getRegion())) { /** @var \Magento\Customer\Api\Data\RegionInterface $region */ $region = $this->regionFactory->create(); $region->setRegion($address->getRegion()); $region->setRegionCode($address->getRegionCode()); $region->setRegionId($address->getRegionId()); $customerAddress->setRegion($region); } $customerData['addresses'][] = $customerAddress; } /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */ $customer = $this->customerFactory->create(['data' => $customerData]); $account = $this->accountManagement->createAccount($customer); $order->setCustomerId($account->getId()); $this->orderRepository->save($order); return $account; }
/** * Confirm customer account by id and confirmation key * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if ($this->_getSession()->isLoggedIn()) { $resultRedirect->setPath('*/*/'); return $resultRedirect; } try { $customerId = $this->getRequest()->getParam('id', false); $key = $this->getRequest()->getParam('key', false); if (empty($customerId) || empty($key)) { throw new \Exception(__('Bad request.')); } // log in and send greeting email $customerEmail = $this->customerRepository->getById($customerId)->getEmail(); $customer = $this->customerAccountManagement->activate($customerEmail, $key); $this->_getSession()->setCustomerDataAsLoggedIn($customer); $this->messageManager->addSuccess($this->getSuccessMessage()); $resultRedirect->setUrl($this->getSuccessRedirect()); return $resultRedirect; } catch (StateException $e) { $this->messageManager->addException($e, __('This confirmation key is invalid or has expired.')); } catch (\Exception $e) { $this->messageManager->addException($e, __('There was an error confirming the account')); } $url = $this->urlModel->getUrl('*/*/index', ['_secure' => true]); return $resultRedirect->setUrl($this->_redirect->error($url)); }
/** * Reset forgotten password * * Used to handle data received from reset forgotten password form * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resetPasswordToken = (string) $this->getRequest()->getQuery('token'); $customerId = (int) $this->getRequest()->getQuery('id'); $password = (string) $this->getRequest()->getPost('password'); $passwordConfirmation = (string) $this->getRequest()->getPost('password_confirmation'); if ($password !== $passwordConfirmation) { $this->messageManager->addError(__("New Password and Confirm New Password values didn't match.")); $resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]); return $resultRedirect; } if (iconv_strlen($password) <= 0) { $this->messageManager->addError(__('New password field cannot be empty.')); $resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]); return $resultRedirect; } try { $customerEmail = $this->customerRepository->getById($customerId)->getEmail(); $this->accountManagement->resetPassword($customerEmail, $resetPasswordToken, $password); $this->messageManager->addSuccess(__('Your password has been updated.')); $resultRedirect->setPath('*/*/login'); return $resultRedirect; } catch (\Exception $exception) { $this->messageManager->addError(__('There was an error saving the new password.')); $resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]); return $resultRedirect; } }
/** * {@inheritdoc} */ public function toHtml() { if ($this->customerSession->isLoggedIn() || !$this->registration->isAllowed() || !$this->accountManagement->isEmailAvailable($this->getEmailAddress()) || !$this->validateAddresses()) { return ''; } return parent::toHtml(); }
/** * 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; }
/** * @magentoAppArea adminhtml * @magentoDbIsolation enabled */ public function testCustomerCreatedNotSubscribed() { $this->verifySubscriptionNotExist('*****@*****.**'); $objectManager = Bootstrap::getObjectManager(); /** @var \Magento\Customer\Api\Data\CustomerInterfaceFactory $customerFactory */ $customerFactory = $objectManager->get('Magento\\Customer\\Api\\Data\\CustomerInterfaceFactory'); $customerDataObject = $customerFactory->create()->setFirstname('Firstname')->setLastname('Lastname')->setEmail('*****@*****.**'); $this->accountManagement->createAccount($customerDataObject); $this->verifySubscriptionNotExist('*****@*****.**'); }
/** * @return array */ public function getButtonData() { $customerId = $this->getCustomerId(); $canModify = $customerId && !$this->customerAccountManagement->isReadonly($this->getCustomerId()); $data = []; if ($customerId && $canModify) { $data = ['label' => __('Delete Customer'), 'class' => 'delete', 'id' => 'customer-edit-delete-button', 'data_attribute' => ['url' => $this->getDeleteUrl()], 'on_click' => '', 'sort_order' => 20]; } return $data; }
/** * @return array */ public function getButtonData() { $customerId = $this->getCustomerId(); $canModify = !$customerId || !$this->customerAccountManagement->isReadonly($this->getCustomerId()); $data = []; if ($canModify) { $data = ['label' => __('Save and Continue Edit'), 'class' => 'save', 'data_attribute' => ['mage-init' => ['button' => ['event' => 'saveAndContinueEdit']]], 'sort_order' => 80]; } return $data; }
/** * @return array */ public function getButtonData() { $customerId = $this->getCustomerId(); $canModify = $customerId && !$this->customerAccountManagement->isReadonly($this->getCustomerId()); $data = []; if ($customerId && $canModify) { $data = ['label' => __('Delete Customer'), 'class' => 'delete', 'on_click' => 'deleteConfirm(\'' . __('Are you sure you want to do this?') . '\', \'' . $this->getDeleteUrl() . '\')', 'sort_order' => 20]; } return $data; }
/** * @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(); }
/** * @magentoDataFixture Magento/Customer/_files/customer.php * @magentoDataFixture Magento/Customer/_files/customer_two_addresses.php */ public function testFormPostAction() { $this->getRequest()->setParam('id', 2)->setMethod('POST')->setPostValue(['form_key' => $this->_objectManager->get('Magento\\Framework\\Data\\Form\\FormKey')->getFormKey(), 'firstname' => 'James', 'lastname' => 'Bond', 'company' => 'Magento Commerce Inc.', 'telephone' => '1112223333', 'fax' => '2223334444', 'street' => ['1234 Monterey Rd', 'Apt 13'], 'city' => 'Kyiv', 'region' => 'Kiev', 'postcode' => '55555', 'country_id' => 'UA', 'success_url' => '', 'error_url' => '', 'default_billing' => true, 'default_shipping' => true]); // we are overwriting the address coming from the fixture $this->dispatch('customer/address/formPost'); $this->assertRedirect($this->stringContains('customer/address/index')); $this->assertSessionMessages($this->equalTo(['You saved the address.']), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS); $address = $this->accountManagement->getDefaultBillingAddress(1); $this->assertEquals('UA', $address->getCountryId()); $this->assertEquals('Kyiv', $address->getCity()); $this->assertEquals('Kiev', $address->getRegion()->getRegion()); $this->assertTrue($address->isDefaultBilling()); $this->assertTrue($address->isDefaultShipping()); }
public function testPopulateCustomerInfo() { $this->quoteMock->expects($this->once())->method('getCustomer')->willReturn($this->customerMock); $this->customerMock->expects($this->atLeastOnce())->method('getId')->willReturn(null); $this->customerMock->expects($this->atLeastOnce())->method('getDefaultBilling')->willReturn(100500); $this->quoteMock->expects($this->atLeastOnce())->method('getBillingAddress')->willReturn($this->quoteAddressMock); $this->quoteMock->expects($this->atLeastOnce())->method('getShippingAddress')->willReturn($this->quoteAddressMock); $this->quoteMock->expects($this->atLeastOnce())->method('setCustomer')->with($this->customerMock)->willReturnSelf(); $this->quoteMock->expects($this->once())->method('getPasswordHash')->willReturn('password hash'); $this->quoteAddressMock->expects($this->atLeastOnce())->method('getId')->willReturn(null); $this->customerAddressRepositoryMock->expects($this->atLeastOnce())->method('getById')->with(100500)->willReturn($this->customerAddressMock); $this->quoteAddressMock->expects($this->atLeastOnce())->method('importCustomerAddressData')->willReturnSelf(); $this->accountManagementMock->expects($this->once())->method('createAccountWithPasswordHash')->with($this->customerMock, 'password hash')->willReturn($this->customerMock); $this->customerManagement->populateCustomerInfo($this->quoteMock); }
public function testExecuteWithException() { $token = 'token'; $customerId = '11'; $this->requestMock->expects($this->exactly(2))->method('getParam')->willReturnMap([['token', null, $token], ['id', null, null]]); $this->sessionMock->expects($this->once())->method('getRpToken')->willReturn($token); $this->sessionMock->expects($this->once())->method('getRpCustomerId')->willReturn($customerId); $this->accountManagementMock->expects($this->once())->method('validateResetPasswordLinkToken')->with($customerId, $token)->willThrowException(new \Exception('Exception.')); $this->messageManagerMock->expects($this->once())->method('addError')->with(__('Your password reset link has expired.'))->willReturnSelf(); /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $redirectMock */ $redirectMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Redirect')->disableOriginalConstructor()->getMock(); $this->redirectFactoryMock->expects($this->once())->method('create')->with([])->willReturn($redirectMock); $redirectMock->expects($this->once())->method('setPath')->with('*/*/forgotpassword', [])->willReturnSelf(); $this->assertEquals($redirectMock, $this->model->executeInternal()); }
/** * Edit/View Existing Customer form fields * * @param \Magento\Framework\Data\Form\Element\Fieldset $fieldset * @return string[] Values to set on the form */ protected function _addEditCustomerFormFields($fieldset) { $fieldset->getForm()->getElement('created_in')->setDisabled('disabled'); $fieldset->getForm()->getElement('website_id')->setDisabled('disabled'); $customerData = $this->_getCustomerDataObject(); if ($customerData->getId() && $this->_accountManagement->isReadonly($customerData->getId())) { return []; } // Prepare customer confirmation control (only for existing customers) $confirmationStatus = $this->_accountManagement->getConfirmationStatus($customerData->getId()); $confirmationKey = $customerData->getConfirmation(); if ($confirmationStatus != AccountManagementInterface::ACCOUNT_CONFIRMED) { $confirmationAttr = $this->_customerMetadata->getAttributeMetadata('confirmation'); if (!$confirmationKey) { $confirmationKey = $this->_getRandomConfirmationKey(); } $element = $fieldset->addField('confirmation', 'select', ['name' => 'confirmation', 'label' => __($confirmationAttr->getFrontendLabel())]); $element->setEntityAttribute($confirmationAttr); $element->setValues(['' => 'Confirmed', $confirmationKey => 'Not confirmed']); // Prepare send welcome email checkbox if customer is not confirmed // no need to add it, if website ID is empty if ($customerData->getConfirmation() && $customerData->getWebsiteId()) { $fieldset->addField('sendemail', 'checkbox', ['name' => 'sendemail', 'label' => __('Send Welcome Email after Confirmation')]); return ['sendemail' => '1']; } } return []; }
/** * @magentoDataFixture Magento/Customer/_files/customer_sample.php */ public function testSaveActionExistingCustomerAndExistingAddressData() { $post = ['customer' => ['entity_id' => '1', 'middlename' => 'test middlename', 'group_id' => 1, 'website_id' => 1, 'firstname' => 'test firstname', 'lastname' => 'test lastname', 'email' => '*****@*****.**', 'new_password' => 'auto', 'sendemail_store_id' => '1', 'sendemail' => '1', 'created_at' => '2000-01-01 00:00:00', 'default_shipping' => '_item1', 'default_billing' => 1], 'address' => ['1' => ['firstname' => 'update firstname', 'lastname' => 'update lastname', 'street' => ['update street'], 'city' => 'update city', 'region_id' => 10, 'country_id' => 'US', 'postcode' => '01001', 'telephone' => '+7000000001', 'default_billing' => 'true'], '_item1' => ['firstname' => 'new firstname', 'lastname' => 'new lastname', 'street' => ['new street'], 'city' => 'new city', 'region_id' => 10, 'country_id' => 'US', 'postcode' => '01001', 'telephone' => '+7000000001', 'default_shipping' => 'true'], '_template_' => ['firstname' => '', 'lastname' => '', 'street' => [], 'city' => '', 'region_id' => 10, 'country_id' => 'US', 'postcode' => '', 'telephone' => '']], 'subscription' => '']; $this->getRequest()->setPostValue($post); $this->getRequest()->setParam('id', 1); $this->dispatch('backend/customer/index/save'); /** Check that success message is set */ $this->assertSessionMessages($this->equalTo(['You saved the customer.']), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS); /** Check that customer id set and addresses saved */ $registry = $this->objectManager->get('Magento\\Framework\\Registry'); $customerId = $registry->registry(RegistryConstants::CURRENT_CUSTOMER_ID); $customer = $this->customerRepository->getById($customerId); $this->assertEquals('test firstname', $customer->getFirstname()); /** * Addresses should be removed by * \Magento\Customer\Model\ResourceModel\Customer::_saveAddresses during _afterSave * addressOne - updated * addressTwo - removed * addressThree - removed * _item1 - new address */ $addresses = $customer->getAddresses(); $this->assertEquals(2, count($addresses)); $updatedAddress = $this->addressRepository->getById(1); $this->assertEquals('update firstname', $updatedAddress->getFirstname()); $newAddress = $this->accountManagement->getDefaultShippingAddress($customerId); $this->assertEquals('new firstname', $newAddress->getFirstname()); /** @var \Magento\Newsletter\Model\Subscriber $subscriber */ $subscriber = $this->objectManager->get('Magento\\Newsletter\\Model\\SubscriberFactory')->create(); $this->assertEmpty($subscriber->getId()); $subscriber->loadByCustomerId($customerId); $this->assertNotEmpty($subscriber->getId()); $this->assertEquals(1, $subscriber->getStatus()); $this->assertRedirect($this->stringStartsWith($this->_baseControllerUrl . 'index/key/')); }
/** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function testEditPostActionWithoutErrors() { $customerId = 24; $address = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\AddressInterface', [], '', false); $loadedCustomer = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\CustomerInterface', [], 'loadedCustomer', false); $loadedCustomer->expects($this->once())->method('getAddresses')->willReturn([$address, $address]); $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->redirectResultMock); $this->formKeyValidator->expects($this->once())->method('validate')->willReturn(true); $this->request->expects($this->once())->method('isPost')->willReturn(true); $this->customerSession->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->customerExtractor->expects($this->once())->method('extract')->willReturn($this->customer); $this->customer->expects($this->once())->method('setId')->with($customerId); $this->customer->expects($this->once())->method('getAddresses')->willReturn(null); $this->customerRepository->expects($this->exactly(2))->method('getById')->with($customerId)->willReturn($loadedCustomer); $this->customer->expects($this->once())->method('setAddresses')->with([$address, $address]); $this->request->expects($this->once())->method('getParam')->with('change_password')->willReturn(true); $this->request->expects($this->at(2))->method('getPost')->with('current_password', null)->willReturn(123); $this->request->expects($this->at(3))->method('getPost')->with('password', null)->willReturn(321); $this->request->expects($this->at(4))->method('getPost')->with('password_confirmation', null)->willReturn(321); $this->customerAccountManagement->expects($this->once())->method('changePassword'); $this->customerRepository->expects($this->once())->method('save'); $messageCollection = $this->getMock('Magento\\Framework\\Message\\Collection', [], [], '', false); $messageCollection->expects($this->once())->method('getCount')->willReturn(0); $this->messageManager->expects($this->once())->method('getMessages')->willReturn($messageCollection); $this->messageManager->expects($this->once())->method('addSuccess')->with('You saved the account information.'); $this->redirectResultMock->expects($this->once())->method('setPath')->with('customer/account')->willReturn('http://test.com/customer/account/edit'); $this->assertSame($this->redirectResultMock, $this->getController()->execute()); }
/** * {@inheritdoc} */ public function install($fixtures) { foreach ($fixtures as $fixture) { $filePath = $this->fixtureManager->getFixture($fixture); $rows = $this->csvReader->getData($filePath); $header = array_shift($rows); foreach ($rows as $row) { $data = []; foreach ($row as $key => $value) { $data[$header[$key]] = $value; } $row = $data; // Collect customer profile and addresses data $customerData['profile'] = $this->convertRowData($row, $this->getDefaultCustomerProfile()); if (!$this->accountManagement->isEmailAvailable($customerData['profile']['email'])) { continue; } $customerData['address'] = $this->convertRowData($row, $this->getDefaultCustomerAddress()); $customerData['address']['region_id'] = $this->getRegionId($customerData['address']); $address = $customerData['address']; $regionData = [RegionInterface::REGION_ID => $address['region_id'], RegionInterface::REGION => !empty($address['region']) ? $address['region'] : null, RegionInterface::REGION_CODE => !empty($address['region_code']) ? $address['region_code'] : null]; $region = $this->regionFactory->create(); $this->dataObjectHelper->populateWithArray($region, $regionData, '\\Magento\\Customer\\Api\\Data\\RegionInterface'); $addresses = $this->addressFactory->create(); unset($customerData['address']['region']); $this->dataObjectHelper->populateWithArray($addresses, $customerData['address'], '\\Magento\\Customer\\Api\\Data\\AddressInterface'); $addresses->setRegion($region)->setIsDefaultBilling(true)->setIsDefaultShipping(true); $customer = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($customer, $customerData['profile'], '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $customer->setAddresses([$addresses]); $this->appState->emulateAreaCode('frontend', [$this->accountManagement, 'createAccount'], [$customer, $row['password']]); } } }
/** * 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); }
/** * Initialize the form. * * @return $this */ public function initForm() { if (!$this->canShowTab()) { return $this; } /**@var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(); $form->setHtmlIdPrefix('_newsletter'); $customerId = $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID); $subscriber = $this->_subscriberFactory->create()->loadByCustomerId($customerId); $this->_coreRegistry->register('subscriber', $subscriber); $fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Newsletter Information')]); $fieldset->addField('subscription', 'checkbox', ['label' => __('Subscribed to Newsletter'), 'name' => 'subscription', 'data-form-part' => $this->getData('target_form'), 'onchange' => 'this.value = this.checked;']); if ($this->customerAccountManagement->isReadOnly($customerId)) { $form->getElement('subscription')->setReadonly(true, true); } $isSubscribed = $subscriber->isSubscribed(); $form->setValues(['subscription' => $isSubscribed ? 'true' : 'false']); $form->getElement('subscription')->setIsChecked($isSubscribed); $changedDate = $this->getStatusChangedDate(); if ($changedDate) { $fieldset->addField('change_status_date', 'label', ['label' => $isSubscribed ? __('Last Date Subscribed') : __('Last Date Unsubscribed'), 'value' => $changedDate, 'bold' => true]); } $this->setForm($form); return $this; }
/** * {@inheritdoc} */ public function run() { $this->logger->log('Installing customers:'); foreach ($this->fixtures as $file) { /** @var \Magento\SampleData\Helper\Csv\Reader $csvReader */ $fileName = $this->fixtureHelper->getPath($file); $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']); foreach ($csvReader as $row) { // Collect customer profile and addresses data $customerData['profile'] = $this->convertRowData($row, $this->getDefaultCustomerProfile()); if (!$this->accountManagement->isEmailAvailable($customerData['profile']['email'])) { continue; } $customerData['address'] = $this->convertRowData($row, $this->getDefaultCustomerAddress()); $customerData['address']['region_id'] = $this->getRegionId($customerData['address']); $address = $customerData['address']; $regionData = [RegionInterface::REGION_ID => $address['region_id'], RegionInterface::REGION => !empty($address['region']) ? $address['region'] : null, RegionInterface::REGION_CODE => !empty($address['region_code']) ? $address['region_code'] : null]; $region = $this->regionFactory->create(); $this->dataObjectHelper->populateWithArray($region, $regionData, '\\Magento\\Customer\\Api\\Data\\RegionInterface'); $addresses = $this->addressFactory->create(); unset($customerData['address']['region']); $this->dataObjectHelper->populateWithArray($addresses, $customerData['address'], '\\Magento\\Customer\\Api\\Data\\AddressInterface'); $addresses->setRegion($region)->setIsDefaultBilling(true)->setIsDefaultShipping(true); $customer = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($customer, $customerData['profile'], '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $customer->setAddresses([$addresses]); $this->accountManagement->createAccount($customer, $row['password']); $this->logger->logInline('.'); } } }
/** * Prepare the layout. * * @return $this */ protected function _prepareLayout() { $customerId = $this->getCustomerId(); if (!$customerId || !$this->customerAccountManagement->isReadonly($customerId)) { $this->buttonList->add('save_and_continue', ['label' => __('Save and Continue Edit'), 'class' => 'save', 'data_attribute' => ['mage-init' => ['button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form']]]], 10); } return parent::_prepareLayout(); }