/** * Login registered users and initiate a session. Send back the session id. * * Expects a POST. ex for JSON {"username":"******", "password":"******"} * * @return void */ public function execute() { $contentTypeHeaderValue = $this->getRequest()->getHeader('Content-Type'); $contentType = $this->getContentType($contentTypeHeaderValue); $loginData = null; try { $loginData = $this->deserializerFactory->get($contentType)->deserialize($this->getRequest()->getRawBody()); } catch (Exception $e) { $this->getResponse()->setHttpResponseCode($e->getCode()); return; } if (!$loginData || $this->getRequest()->getMethod() !== \Magento\Webapi\Model\Rest\Config::HTTP_METHOD_POST) { $this->getResponse()->setHttpResponseCode(HttpException::HTTP_BAD_REQUEST); return; } $customerData = null; try { $customerData = $this->customerAccountService->authenticate($loginData['username'], $loginData['password']); } catch (AuthenticationException $e) { $this->getResponse()->setHttpResponseCode(HttpException::HTTP_UNAUTHORIZED); return; } $this->session->start('frontend'); $this->session->setUserId($customerData->getId()); $this->session->setUserType(UserIdentifier::USER_TYPE_CUSTOMER); $this->session->regenerateId(true); }
/** * Make sure customer is valid, if logged in * * By default will add error messages and redirect to customer edit form * * @param bool $redirect - stop dispatch and redirect? * @param bool $addErrors - add error messages? * @return bool */ protected function _preDispatchValidateCustomer($redirect = true, $addErrors = true) { try { $customerId = $this->_customerSession->getCustomerId(); $customer = $this->_customerAccountService->getCustomer($customerId); } catch (NoSuchEntityException $e) { return true; } if (isset($customer)) { $validationResult = $this->_customerAccountService->validateCustomerData($customer, $this->_customerMetadataService->getAllCustomerAttributeMetadata()); if (!$validationResult->isValid()) { if ($addErrors) { foreach ($validationResult->getMessages() as $error) { $this->messageManager->addError($error); } } if ($redirect) { $this->_redirect('customer/account/edit'); $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); } return false; } } return true; }
/** * Retrieve Shared Wishlist Customer instance * * @return \Magento\Customer\Service\V1\Data\Customer */ public function getWishlistCustomer() { if (is_null($this->_customer)) { $this->_customer = $this->_customerAccountService->getCustomer($this->_getWishlist()->getCustomerId()); } return $this->_customer; }
/** * @magentoDataFixture Magento/Customer/_files/customer.php */ public function testGetCustomerAttributeMetadata() { // Expect these attributes to exist but do not check the value $expectAttrsWOutVals = array('created_at'); // Expect these attributes to exist and check the value - values come from _files/customer.php $expectAttrsWithVals = array('id' => '1', 'website_id' => '1', 'store_id' => '1', 'group_id' => '1', 'firstname' => 'Firstname', 'lastname' => 'Lastname', 'email' => '*****@*****.**', 'default_billing' => '1', 'default_shipping' => '1', 'disable_auto_group_change' => '0'); $customer = $this->_customerAccountService->getCustomer(1); $this->assertNotNull($customer); $attributes = \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer); $this->assertNotEmpty($attributes); foreach ($attributes as $attributeCode => $attributeValue) { $this->assertNotNull($attributeCode); $this->assertNotNull($attributeValue); $attributeMetadata = $this->_service->getAttributeMetadata($attributeCode); $attrMetadataCode = $attributeMetadata->getAttributeCode(); $this->assertSame($attributeCode, $attrMetadataCode); if (($key = array_search($attrMetadataCode, $expectAttrsWOutVals)) !== false) { unset($expectAttrsWOutVals[$key]); } else { $this->assertArrayHasKey($attrMetadataCode, $expectAttrsWithVals); $this->assertSame($expectAttrsWithVals[$attrMetadataCode], $attributeValue, "Failed for {$attrMetadataCode}"); unset($expectAttrsWithVals[$attrMetadataCode]); } } $this->assertEmpty($expectAttrsWOutVals); $this->assertEmpty($expectAttrsWithVals); }
/** * Return the full name of the customer currently logged in * * @return string|null */ public function getCustomerName() { try { $customer = $this->_customerAccountService->getCustomer($this->currentCustomer->getCustomerId()); return $this->escapeHtml($this->_viewHelper->getCustomerName($customer)); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { return null; } }
public function testConstruct() { $this->customerAccount = $this->getMockForAbstractClass('Magento\\Customer\\Service\\V1\\CustomerAccountServiceInterface'); $this->customerAccount->expects($this->once())->method('getCustomer')->with('customer id')->will($this->returnValue(new \Magento\Framework\Object())); $this->request = $this->getMockForAbstractClass('Magento\\Framework\\App\\RequestInterface'); $this->request->expects($this->at(0))->method('getParam')->with('customerId', false)->will($this->returnValue('customer id')); $this->request->expects($this->at(1))->method('getParam')->with('productId', false)->will($this->returnValue(false)); $objectManagerHelper = new ObjectManagerHelper($this); $this->model = $objectManagerHelper->getObject('Magento\\Review\\Block\\Adminhtml\\Main', ['request' => $this->request, 'customerAccount' => $this->customerAccount]); }
/** * Set persistent data to customer session * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute($observer) { if (!$this->_persistentData->canProcess($observer) || !$this->_persistentData->isShoppingCartPersist()) { return $this; } if ($this->_persistentSession->isPersistent() && !$this->_customerSession->isLoggedIn()) { $customer = $this->_customerAccountService->getCustomer($this->_persistentSession->getSession()->getCustomerId()); $this->_customerSession->setCustomerId($customer->getId())->setCustomerGroupId($customer->getGroupId()); } return $this; }
/** * @magentoAppArea frontend * @magentoConfigFixture current_store persistent/options/shopping_cart 1 * @magentoConfigFixture current_store persistent/options/logout_clear 0 * @magentoConfigFixture current_store persistent/options/enabled 1 */ public function testEmulateCustomer() { $observer = new \Magento\Framework\Event\Observer(); $this->_customerSession->loginById(1); $this->_customerSession->logout(); $this->assertNull($this->_customerSession->getCustomerId()); $this->assertEquals(\Magento\Customer\Service\V1\CustomerGroupServiceInterface::NOT_LOGGED_IN_ID, $this->_customerSession->getCustomerGroupId()); $this->_observer->execute($observer); $customer = $this->_customerAccountService->getCustomer($this->_persistentSessionHelper->getSession()->getCustomerId()); $this->assertEquals($customer->getId(), $this->_customerSession->getCustomerId()); $this->assertEquals($customer->getGroupId(), $this->_customerSession->getCustomerGroupId()); }
/** * @magentoDataFixture Magento/Customer/_files/customer.php */ public function testGetHtml() { $customer = $this->_customerAccountService->getCustomer(1); $data = array('account' => $customer->__toArray()); $this->_context->getBackendSession()->setCustomerData($data); $this->_block = $this->_objectManager->get('Magento\\Framework\\View\\LayoutInterface')->createBlock('Magento\\Customer\\Block\\Adminhtml\\Edit\\Tab\\Carts', '', array('context' => $this->_context)); $html = $this->_block->toHtml(); $this->assertContains("<div id=\"customer_cart_grid1\">", $html); $this->assertContains("<div class=\"grid-actions\">", $html); $this->assertContains("customer_cart_grid1JsObject = new varienGrid('customer_cart_grid1',", $html); $this->assertContains("backend/customer/cart_product_composite_cart/configure/website_id/1", $html); }
/** * Update customer id and customer group id if user is in persistent session * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { if (!$this->_persistentSession->isPersistent()) { return; } $customerCookies = $observer->getEvent()->getCustomerCookies(); if ($customerCookies instanceof \Magento\Framework\Object) { $persistentCustomer = $this->_customerAccountService->getCustomer($this->_persistentSession->getSession()->getCustomerId()); $customerCookies->setCustomerId($persistentCustomer->getId()); $customerCookies->setCustomerGroupId($persistentCustomer->getGroupId()); } }
/** * @magentoDataFixture Magento/Customer/_files/customer.php * @magentoDataFixture Magento/Core/_files/second_third_store.php * @magentoConfigFixture current_store customer/account_share/scope 0 */ public function testToHtmlEmptyGlobalShareAndSessionData() { $this->registry->register(RegistryConstants::CURRENT_CUSTOMER_ID, 1); $customer = $this->customerAccountService->getCustomer(1); $this->backendSession->setCustomerData(array('account' => $customer->__toArray())); $block = $this->layout->createBlock('Magento\\Customer\\Block\\Adminhtml\\Edit\\Tab\\View\\Accordion'); $html = $block->toHtml(); $this->assertContains('Wishlist - 0 item(s)', $html); $this->assertContains('Shopping Cart of Main Website - 0 item(s)', $html); $this->assertContains('Shopping Cart of Second Website - 0 item(s)', $html); $this->assertContains('Shopping Cart of Third Website - 0 item(s)', $html); }
/** * @magentoConfigFixture current_store persistent/options/enabled 1 * @magentoConfigFixture current_store persistent/options/remember_enabled 1 * @magentoConfigFixture current_store persistent/options/remember_default 1 * @magentoAppArea frontend * @magentoConfigFixture current_store persistent/options/shopping_cart 1 * @magentoConfigFixture current_store persistent/options/logout_clear 0 */ public function testEmulateQuote() { $requestMock = $this->getMockBuilder('Magento\\Framework\\App\\Request\\Http')->disableOriginalConstructor()->setMethods([])->getMock(); $requestMock->expects($this->once())->method('getFullActionName')->will($this->returnValue('valid_action')); $event = new \Magento\Framework\Event(['request' => $requestMock]); $observer = new \Magento\Framework\Event\Observer(); $observer->setEvent($event); $this->_customerSession->loginById(1); $customer = $this->_customerAccountService->getCustomer($this->_persistentSessionHelper->getSession()->getCustomerId()); $this->_checkoutSession->expects($this->once())->method('setCustomerData')->with($customer); $this->_customerSession->logout(); $this->_observer->execute($observer); }
/** * Prepare the form. * * @return $this */ protected function _prepareForm() { /** @var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(array('data' => array('id' => 'edit_form', 'action' => $this->getUrl('customer/*/save'), 'method' => 'post', 'enctype' => 'multipart/form-data'))); $customerId = $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID); if ($customerId) { $form->addField('id', 'hidden', array('name' => 'customer_id')); $customer = $this->_customerAccountService->getCustomer($customerId); $form->setValues(\Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer))->addValues(array('customer_id' => $customerId)); } $form->setUseContainer(true); $this->setForm($form); return parent::_prepareForm(); }
/** * {@inheritdoc} */ public function loadData($printQuery = false, $logQuery = false) { if (!$this->isLoaded()) { $searchCriteria = $this->getSearchCriteria(); $searchResults = $this->accountService->searchCustomers($searchCriteria); $this->_totalRecords = $searchResults->getTotalCount(); /** @var CustomerDetails[] $customers */ $customers = $searchResults->getItems(); foreach ($customers as $customer) { $this->_addItem($this->createCustomerDetailItem($customer)); } $this->_setIsLoaded(); } return $this; }
/** * test get customer method, method returns customer from service */ public function testGetCustomerLoadCustomerFromService() { $this->moduleManagerMock->expects($this->once())->method('isEnabled')->with($this->equalTo('Magento_PageCache'))->will($this->returnValue(false)); $this->customerSessionMock->expects($this->once())->method('getId')->will($this->returnValue($this->customerId)); $this->customerServiceMock->expects($this->once())->method('getCustomer')->with($this->equalTo($this->customerId))->will($this->returnValue($this->customerDataMock)); $this->assertEquals($this->customerDataMock, $this->currentCustomer->getCustomer()); }
/** * Get logged in customer * * @return \Magento\Customer\Service\V1\Data\Customer */ protected function _getCustomerData() { if (empty($this->_customer)) { $this->_customer = $this->_customerAccountService->getCustomer($this->_customerSession->getCustomerId()); } return $this->_customer; }
/** * 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->_customerAccountService->canModify($customerData->getId())) { return array(); } // Prepare customer confirmation control (only for existing customers) $confirmationStatus = $this->_customerAccountService->getConfirmationStatus($customerData->getId()); $confirmationKey = $customerData->getConfirmation(); if ($confirmationStatus != CustomerAccountServiceInterface::ACCOUNT_CONFIRMED) { $confirmationAttr = $this->_customerMetadataService->getCustomerAttributeMetadata('confirmation'); if (!$confirmationKey) { $confirmationKey = $this->_getRandomConfirmationKey(); } $element = $fieldset->addField('confirmation', 'select', array('name' => 'confirmation', 'label' => __($confirmationAttr->getFrontendLabel()))); $element->setEntityAttribute($confirmationAttr); $element->setValues(array('' => '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', array('name' => 'sendemail', 'label' => __('Send Welcome Email after Confirmation'))); return array('sendemail' => '1'); } } return array(); }
/** * @magentoAppArea adminhtml * @magentoDataFixture Magento/Customer/_files/customer.php * @magentoAppIsolation enabled */ public function testDeleteCustomerByEmail() { // _files/customer.php sets the customer email to customer@example.com $this->_customerAccountService->deleteCustomerByEmail('*****@*****.**'); //Verify if the customer is deleted $this->setExpectedException('Magento\\Framework\\Exception\\NoSuchEntityException', 'No such entity with email = customer@example.com'); $this->_customerAccountService->getCustomerByEmail('*****@*****.**'); }
/** * Prepare the layout. * * @return $this */ protected function _prepareLayout() { $customerId = $this->getCustomerId(); if (!$customerId || $this->_customerAccountService->canModify($customerId)) { $this->buttonList->add('save_and_continue', array('label' => __('Save and Continue Edit'), 'class' => 'save', 'data_attribute' => array('mage-init' => array('button' => array('event' => 'saveAndContinueEdit', 'target' => '#edit_form')))), 10); } return parent::_prepareLayout(); }
/** * Emulate 'welcome' block with persistent data * * @param \Magento\Framework\View\Element\AbstractBlock $block * @return $this */ public function emulateWelcomeBlock($block) { $escapedName = $this->_escaper->escapeHtml($this->_customerViewHelper->getCustomerName($this->_customerAccountService->getCustomer($this->_persistentSession->getSession()->getCustomerId())), null); $this->_applyAccountLinksPersistentData(); $welcomeMessage = __('Welcome, %1!', $escapedName) . ' ' . $this->_layout->getBlock('header.additional')->toHtml(); $block->setWelcome($welcomeMessage); return $this; }
/** * @return Customer */ private function _loadCustomer() { $customer = $this->_customerAccountService->getCustomer(1); $data = array('account' => $customer->__toArray()); $this->_context->getBackendSession()->setCustomerData($data); $this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customer->getId()); return $customer; }
/** * @magentoDataFixture Magento/Customer/_files/customer.php */ public function testNotReadOnly() { $this->backendSession->setCustomerData(array('customer_id' => 1, 'account' => $this->customerAccountService->getCustomer(1)->__toArray())); $this->accountBlock->initForm()->toHtml(); $element = $this->accountBlock->getForm()->getElement('firstname'); // Make sure readonly has not been set (is null) or set to false $this->assertTrue(is_null($element->getReadonly()) || !$element->getReadonly()); }
/** * @magentoAppArea adminhtml * @magentoDataFixture Magento/Newsletter/_files/subscribers.php */ public function testCustomerDeletedAdminArea() { $objectManager = Bootstrap::getObjectManager(); /** @var \Magento\Newsletter\Model\Subscriber $subscriber */ $subscriber = $objectManager->create('Magento\\Newsletter\\Model\\Subscriber'); $subscriber->loadByEmail('*****@*****.**'); $this->assertTrue($subscriber->isSubscribed()); $this->accountService->deleteCustomer(1); $this->verifySubscriptionNotExist('*****@*****.**'); }
public function testSaveActionWithException() { $this->formKeyValidatorMock->expects($this->once())->method('validate')->will($this->returnValue(true)); $this->customerSessionMock->expects($this->any())->method('getCustomerId')->will($this->returnValue(1)); $this->customerAccountServiceMock->expects($this->any())->method('getCustomer')->will($this->throwException(new NoSuchEntityException(NoSuchEntityException::MESSAGE_SINGLE_FIELD, ['fieldName' => 'customerId', 'value' => 'value']))); $this->redirectMock->expects($this->once())->method('redirect')->with($this->responseMock, 'customer/account/', []); $this->messageManagerMock->expects($this->never())->method('addSuccess'); $this->messageManagerMock->expects($this->once())->method('addError')->with('Something went wrong while saving your subscription.'); $this->action->execute(); }
/** * Authorization customer by identifier * * @param int $customerId * @return bool */ public function loginById($customerId) { try { $customer = $this->_customerAccountService->getCustomer($customerId); $this->setCustomerDataAsLoggedIn($customer); return true; } catch (\Exception $e) { return false; } }
/** * Verify that the specified customer has the same default billing and shipping address. * * @magentoDataFixture Magento/Customer/_files/customer.php * @magentoDataFixture Magento/Customer/_files/customer_address.php */ public function testGetPrimaryAddressesBillingShippingSame() { $customer = $this->customerAccountService->getCustomer(1); $this->customerSession->setCustomerId(1); $addresses = $this->block->getPrimaryAddresses(); $this->assertCount(1, $addresses); $address = $addresses[0]; $this->assertInstanceOf('Magento\\Customer\\Service\\V1\\Data\\Address', $address); $this->assertEquals($customer->getDefaultBilling(), $address->getId()); $this->assertEquals($customer->getDefaultShipping(), $address->getId()); }
/** * Get customer data from session or service. * * @param int|null $customerId possible customer ID from DB * @return Customer * @throws NoSuchEntityException */ protected function getCustomer($customerId) { $customerData = $this->_backendSession->getCustomerData(); if (!empty($customerData['account'])) { return $this->_customerBuilder->populateWithArray($customerData['account'])->create(); } elseif ($customerId) { return $this->_customerAccountService->getCustomer($customerId); } else { return $this->_customerBuilder->create(); } }
/** * @magentoDataFixture Magento/Customer/_files/two_customers.php */ public function testMassAssignGroupActionPartialUpdate() { $this->assertEquals(1, $this->customerAccountService->getCustomer(1)->getGroupId()); $this->assertEquals(1, $this->customerAccountService->getCustomer(2)->getGroupId()); $this->getRequest()->setParam('group', 0)->setPost('customer', array(1, 4200, 2)); $this->dispatch('backend/customer/index/massAssignGroup'); $this->assertSessionMessages($this->equalTo(array('A total of 2 record(s) were updated.')), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS); $this->assertSessionMessages($this->equalTo(array('No such entity with customerId = 4200')), \Magento\Framework\Message\MessageInterface::TYPE_ERROR); $this->assertEquals(0, $this->customerAccountService->getCustomer(1)->getGroupId()); $this->assertEquals(0, $this->customerAccountService->getCustomer(2)->getGroupId()); }
/** * @magentoDataFixture Magento/Customer/_files/customer.php * @magentoDataFixture Magento/Catalog/_files/product_simple.php */ public function testSend() { $this->_objectManager->configure(['Magento\\ProductAlert\\Model\\Email' => ['arguments' => ['transportBuilder' => ['instance' => 'Magento\\TestFramework\\Mail\\Template\\TransportBuilderMock']]], 'preferences' => ['Magento\\Framework\\Mail\\TransportInterface' => 'Magento\\TestFramework\\Mail\\TransportInterfaceMock']]); \Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea(\Magento\Framework\App\Area::AREA_FRONTEND); $this->_emailModel = $this->_objectManager->create('Magento\\ProductAlert\\Model\\Email'); /** @var \Magento\Store\Model\Website $website */ $website = $this->_objectManager->create('Magento\\Store\\Model\\Website'); $website->load(1); $this->_emailModel->setWebsite($website); /** @var \Magento\Customer\Service\V1\Data\Customer $customer */ $customer = $this->_customerAccountService->getCustomer(1); $this->_emailModel->setCustomerData($customer); /** @var \Magento\Catalog\Model\Product $product */ $product = $this->_objectManager->create('Magento\\Catalog\\Model\\Product'); $product->load(1); $this->_emailModel->addPriceProduct($product); $this->_emailModel->send(); /** @var \Magento\TestFramework\Mail\Template\TransportBuilderMock $transportBuilder */ $transportBuilder = $this->_objectManager->get('Magento\\TestFramework\\Mail\\Template\\TransportBuilderMock'); $this->assertStringMatchesFormat('%AHello ' . $this->_customerViewHelper->getCustomerName($customer) . '%A', $transportBuilder->getSentMessage()->getBodyHtml()->getContent()); }
/** * Plugin after delete customer that updates any newsletter subscription that may have existed. * * @param CustomerAccountServiceInterface $subject * @param callable $deleteCustomer Function we are wrapping around * @param int $customerId Input to the function * @return bool */ public function aroundDeleteCustomer(CustomerAccountServiceInterface $subject, callable $deleteCustomer, $customerId) { $customer = $subject->getCustomer($customerId); $result = $deleteCustomer($customerId); /** @var \Magento\Newsletter\Model\Subscriber $subscriber */ $subscriber = $this->subscriberFactory->create(); $subscriber->loadByEmail($customer->getEmail()); if ($subscriber->getId()) { $subscriber->delete(); } return $result; }