/** * Retrieve assoc array of checkout configuration * * @return array */ public function getConfig() { $vaultPayments = []; $customerId = $this->session->getCustomerId(); if (!$customerId) { return $vaultPayments; } $storeId = $this->storeManager->getStore()->getId(); if (!$this->vaultPayment->isActive($storeId)) { return $vaultPayments; } $vaultProviderCode = $this->vaultPayment->getProviderCode($storeId); $componentProvider = $this->getComponentProvider($vaultProviderCode); if (null === $componentProvider) { return $vaultPayments; } $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::CUSTOMER_ID)->setValue($customerId)->create(); $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::IS_VISIBLE)->setValue(1)->create(); $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::PAYMENT_METHOD_CODE)->setValue($vaultProviderCode)->create(); $searchCriteria = $this->searchCriteriaBuilder->addFilters($filters)->create(); foreach ($this->paymentTokenRepository->getList($searchCriteria)->getItems() as $index => $token) { $component = $componentProvider->getComponentForToken($token); $vaultPayments[VaultPaymentInterface::CODE . '_item_' . $index] = ['config' => $component->getConfig(), 'component' => $component->getName()]; } return ['payment' => [VaultPaymentInterface::CODE => $vaultPayments]]; }
/** * @param \Magento\Customer\Controller\Ajax\Login $subject * @param \Closure $proceed * @return $this * @throws \Zend_Json_Exception * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function aroundExecute(\Magento\Customer\Controller\Ajax\Login $subject, \Closure $proceed) { $captchaFormIdField = 'captcha_form_id'; $captchaInputName = 'captcha_string'; /** @var \Magento\Framework\App\RequestInterface $request */ $request = $subject->getRequest(); $loginParams = []; $content = $request->getContent(); if ($content) { $loginParams = \Zend_Json::decode($content); } $username = isset($loginParams['username']) ? $loginParams['username'] : null; $captchaString = isset($loginParams[$captchaInputName]) ? $loginParams[$captchaInputName] : null; $loginFormId = isset($loginParams[$captchaFormIdField]) ? $loginParams[$captchaFormIdField] : null; foreach ($this->formIds as $formId) { $captchaModel = $this->helper->getCaptcha($formId); if ($captchaModel->isRequired($username) && !in_array($loginFormId, $this->formIds)) { $resultJson = $this->resultJsonFactory->create(); return $resultJson->setData(['errors' => true, 'message' => __('Provided form does not exist')]); } if ($formId == $loginFormId) { $captchaModel->logAttempt($username); if (!$captchaModel->isCorrect($captchaString)) { $this->sessionManager->setUsername($username); /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); return $resultJson->setData(['errors' => true, 'message' => __('Incorrect CAPTCHA')]); } } } return $proceed(); }
/** * Retrieve Session Form Key * * @return string A 16 bit unique key for forms */ public function getFormKey() { if (!$this->session->getData(self::FORM_KEY)) { $this->session->setData(self::FORM_KEY, $this->mathRandom->getRandomString(16)); } return $this->session->getData(self::FORM_KEY); }
/** * @param \Magento\Framework\App\Action\Action $subject * @param callable $proceed * @param \Magento\Framework\App\RequestInterface $request * @return mixed */ public function aroundDispatch(\Magento\Framework\App\Action\Action $subject, \Closure $proceed, \Magento\Framework\App\RequestInterface $request) { $defaultStore = $this->storeManager->getWebsite()->getDefaultStore(); $this->httpContext->setValue(\Magento\Core\Helper\Data::CONTEXT_CURRENCY, $this->session->getCurrencyCode(), $defaultStore->getDefaultCurrency()->getCode()); $this->httpContext->setValue(\Magento\Core\Helper\Data::CONTEXT_STORE, $this->httpRequest->getParam('___store', $defaultStore->getStoreCodeFromCookie()), $this->storeManager->getWebsite()->getDefaultStore()->getCode()); return $proceed($request); }
/** * @param \Magento\Framework\App\ActionInterface $subject * @param callable $proceed * @param \Magento\Framework\App\RequestInterface $request * @return mixed * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundDispatch(\Magento\Framework\App\ActionInterface $subject, \Closure $proceed, \Magento\Framework\App\RequestInterface $request) { /** @var \Magento\Store\Model\Store $defaultStore */ $defaultStore = $this->storeManager->getWebsite()->getDefaultStore(); $requestedStoreCode = $this->httpRequest->getParam(StoreResolverInterface::PARAM_NAME, $this->storeCookieManager->getStoreCodeFromCookie()); /** @var \Magento\Store\Model\Store $currentStore */ $currentStore = $requestedStoreCode ? $this->storeManager->getStore($requestedStoreCode) : $defaultStore; $this->httpContext->setValue(StoreManagerInterface::CONTEXT_STORE, $currentStore->getCode(), $this->storeManager->getDefaultStoreView()->getCode()); $this->httpContext->setValue(HttpContext::CONTEXT_CURRENCY, $this->session->getCurrencyCode() ?: $currentStore->getDefaultCurrencyCode(), $defaultStore->getDefaultCurrencyCode()); return $proceed($request); }
/** * Retrieve assoc array of checkout configuration * * @return array */ public function getConfig() { $availableMethods = []; $vaultPayments = $this->getVaultPaymentMethodList(); $customerId = $this->session->getCustomerId(); $storeId = $this->storeManager->getStore()->getId(); foreach ($vaultPayments as $method) { $availableMethods[$method->getCode()] = ['is_enabled' => $customerId !== null && $method->isActive($storeId)]; } return [self::$vaultCode => $availableMethods]; }
/** * Prepare rating edit form * * @return $this */ protected function _prepareForm() { /** @var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(); $this->setForm($form); $fieldset = $form->addFieldset('rating_form', array('legend' => __('Rating Title'))); $fieldset->addField('rating_code', 'text', array('name' => 'rating_code', 'label' => __('Default Value'), 'class' => 'required-entry', 'required' => true)); foreach ($this->_systemStore->getStoreCollection() as $store) { $fieldset->addField('rating_code_' . $store->getId(), 'text', array('label' => $store->getName(), 'name' => 'rating_codes[' . $store->getId() . ']')); } if ($this->_session->getRatingData()) { $form->setValues($this->_session->getRatingData()); $data = $this->_session->getRatingData(); if (isset($data['rating_codes'])) { $this->_setRatingCodes($data['rating_codes']); } $this->_session->setRatingData(null); } elseif ($this->_coreRegistry->registry('rating_data')) { $form->setValues($this->_coreRegistry->registry('rating_data')->getData()); if ($this->_coreRegistry->registry('rating_data')->getRatingCodes()) { $this->_setRatingCodes($this->_coreRegistry->registry('rating_data')->getRatingCodes()); } } if ($this->_coreRegistry->registry('rating_data')) { $collection = $this->_optionFactory->create()->getResourceCollection()->addRatingFilter($this->_coreRegistry->registry('rating_data')->getId())->load(); $i = 1; foreach ($collection->getItems() as $item) { $fieldset->addField('option_code_' . $item->getId(), 'hidden', array('required' => true, 'name' => 'option_title[' . $item->getId() . ']', 'value' => $item->getCode() ? $item->getCode() : $i)); $i++; } } else { for ($i = 1; $i <= 5; $i++) { $fieldset->addField('option_code_' . $i, 'hidden', array('required' => true, 'name' => 'option_title[add_' . $i . ']', 'value' => $i)); } } $fieldset = $form->addFieldset('visibility_form', array('legend' => __('Rating Visibility'))); if (!$this->_storeManager->isSingleStoreMode()) { $field = $fieldset->addField('stores', 'multiselect', array('label' => __('Visible In'), 'name' => 'stores[]', 'values' => $this->_systemStore->getStoreValuesForForm())); $renderer = $this->getLayout()->createBlock('Magento\\Backend\\Block\\Store\\Switcher\\Form\\Renderer\\Fieldset\\Element'); $field->setRenderer($renderer); if ($this->_coreRegistry->registry('rating_data')) { $form->getElement('stores')->setValue($this->_coreRegistry->registry('rating_data')->getStores()); } } $fieldset->addField('is_active', 'checkbox', array('label' => __('Is Active'), 'name' => 'is_active', 'value' => 1)); $fieldset->addField('position', 'text', array('label' => __('Sort Order'), 'name' => 'position')); if ($this->_coreRegistry->registry('rating_data')) { $form->getElement('position')->setValue($this->_coreRegistry->registry('rating_data')->getPosition()); $form->getElement('is_active')->setIsChecked($this->_coreRegistry->registry('rating_data')->getIsActive()); } return parent::_prepareForm(); }
/** * After generate Xml * * @param \Magento\Framework\View\LayoutInterface $subject * @param \Magento\Framework\View\LayoutInterface $result * @return \Magento\Framework\View\LayoutInterface */ public function afterGenerateXml(\Magento\Framework\View\LayoutInterface $subject, $result) { if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) { $this->visitor->setSkipRequestLogging(true); $this->visitor->unsetData(); $this->session->clearStorage(); $this->customerSession->clearStorage(); $this->session->setData(\Magento\Framework\Data\Form\FormKey::FORM_KEY, $this->formKey); $this->customerSession->setCustomerGroupId($this->customerGroupId); $this->customerSession->setCustomer($this->customerFactory->create()->setGroupId($this->customerGroupId)); } return $result; }
/** * Validate session * * @param SessionManagerInterface $session * @return void * @throws SessionException */ public function validate(SessionManagerInterface $session) { if (!isset($_SESSION[self::VALIDATOR_KEY])) { $_SESSION[self::VALIDATOR_KEY] = $this->_getSessionEnvironment(); } else { try { $this->_validate(); } catch (SessionException $e) { $session->destroy(['clear_storage' => false]); // throw core session exception throw $e; } } }
public function testDelete() { $cookiePath = '/'; $cookieDomain = 'example.com'; /** @var PublicCookieMetadata|\PHPUnit_Framework_MockObject_MockObject $metadata */ $metadata = $this->getMockBuilder('Magento\\Framework\\Stdlib\\Cookie\\PublicCookieMetadata')->disableOriginalConstructor()->getMock(); $this->cookieMetadataFactory->expects(static::once())->method('createCookieMetadata')->willReturn($metadata); $this->sessionManager->expects(static::once())->method('getCookiePath')->willReturn($cookiePath); $metadata->expects(static::once())->method('setPath')->with($cookiePath)->willReturnSelf(); $this->sessionManager->expects(static::once())->method('getCookieDomain')->willReturn($cookieDomain); $metadata->expects(static::once())->method('setDomain')->with($cookieDomain)->willReturnSelf(); $this->cookieManagerMock->expects(static::once())->method('deleteCookie')->with(FormKey::COOKIE_NAME, $metadata); $this->formKey->delete(); }
/** * @inheritdoc */ public function execute() { $response = $this->resultFactory->create(ResultFactory::TYPE_JSON); try { $publicHash = $this->getRequest()->getParam('public_hash'); $customerId = $this->session->getCustomerId(); $result = $this->command->execute(['public_hash' => $publicHash, 'customer_id' => $customerId])->get(); $response->setData(['paymentMethodNonce' => $result['paymentMethodNonce']]); } catch (\Exception $e) { $this->logger->critical($e); return $this->processBadRequest($response); } return $response; }
/** * Run test toHtml method * * @param bool $customerId * @return void * * @dataProvider dataProviderToHtml */ public function testToHtml($customerId) { $cacheData = false; $idQueryParam = 'id-query-param'; $sessionId = 'session-id'; $this->additional->setData('cache_lifetime', 789); $this->additional->setData('cache_key', 'cache-key'); $this->eventManagerMock->expects($this->once())->method('dispatch')->with('view_block_abstract_to_html_before', ['block' => $this->additional]); $this->scopeConfigMock->expects($this->once())->method('getValue')->with('advanced/modules_disable_output/Magento_Persistent', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)->willReturn(false); // get cache $this->cacheStateMock->expects($this->at(0))->method('isEnabled')->with(\Magento\Persistent\Block\Header\Additional::CACHE_GROUP)->willReturn(true); // save cache $this->cacheStateMock->expects($this->at(1))->method('isEnabled')->with(\Magento\Persistent\Block\Header\Additional::CACHE_GROUP)->willReturn(false); $this->cacheMock->expects($this->once())->method('load')->willReturn($cacheData); $this->sidResolverMock->expects($this->never())->method('getSessionIdQueryParam')->with($this->sessionMock)->willReturn($idQueryParam); $this->sessionMock->expects($this->never())->method('getSessionId')->willReturn($sessionId); // call protected _toHtml method $sessionMock = $this->getMock('Magento\\Persistent\\Model\\Session', ['getCustomerId'], [], '', false); $this->persistentSessionHelperMock->expects($this->atLeastOnce())->method('getSession')->willReturn($sessionMock); $sessionMock->expects($this->atLeastOnce())->method('getCustomerId')->willReturn($customerId); if ($customerId) { $this->assertEquals('<span><a >Not you?</a></span>', $this->additional->toHtml()); } else { $this->assertEquals('', $this->additional->toHtml()); } }
/** * Set redirect into response * * @param \Magento\Framework\App\ResponseInterface $response * @param string $path * @param array $arguments * @return void */ public function redirect(\Magento\Framework\App\ResponseInterface $response, $path, $arguments = array()) { if ($this->_session->getCookieShouldBeReceived() && $this->_urlBuilder->getUseSession() && $this->_canUseSessionIdInParam) { $arguments += array('_query' => array($this->_sidResolver->getSessionIdQueryParam($this->_session) => $this->_session->getSessionId())); } $response->setRedirect($this->_urlBuilder->getUrl($path, $arguments)); }
/** * {@inheritdoc} * * @param array $arguments * @return array */ public function updatePathParams(array $arguments) { if ($this->_session->getCookieShouldBeReceived() && $this->_sidResolver->getUseSessionInUrl() && $this->_canUseSessionIdInParam) { $arguments += ['_query' => [$this->_sidResolver->getSessionIdQueryParam($this->_session) => $this->_session->getSessionId()]]; } return $arguments; }
/** * Get a hash of the session id. * * @return string|null */ protected function getSafeSessionId() { if (!$this->safeSessionId) { // When there is no session id, safeSessionId will be set to null. // This will prevent the method call from getting cached (above // check will fail) and cause the session to be rechecked for a // session id on successive calls until a session id is retrieved. // Allowing this behavior in case a log call happens before the // session is started. Some calls may miss the session id but once // it is available, it will be retrieved, cached and attached to // later log calls. $sessionId = $this->session->getSessionId(); $this->safeSessionId = $sessionId ? hash('sha256', $this->session->getSessionId()) : null; } return $this->safeSessionId; }
public function testGetDataWithCustomerFormData() { $customerId = 11; $customerFormData = ['customer' => ['email' => '*****@*****.**', 'default_billing' => 3, 'default_shipping' => 3, 'entity_id' => $customerId], 'address' => [3 => ['firstname' => 'firstname1', 'lastname' => 'lastname1', 'street' => ['street1', 'street2'], 'default_billing' => 3, 'default_shipping' => 3]]]; $customer = $this->getMockBuilder('Magento\\Customer\\Model\\Customer')->disableOriginalConstructor()->getMock(); $address = $this->getMockBuilder('Magento\\Customer\\Model\\Address')->disableOriginalConstructor()->getMock(); $collectionMock = $this->getMockBuilder('Magento\\Customer\\Model\\ResourceModel\\Customer\\Collection')->disableOriginalConstructor()->getMock(); $collectionMock->expects($this->once())->method('addAttributeToSelect')->with('*'); $this->customerCollectionFactoryMock->expects($this->once())->method('create')->willReturn($collectionMock); $collectionMock->expects($this->once())->method('getItems')->willReturn([$customer]); $customer->expects($this->once())->method('getData')->willReturn(['email' => '*****@*****.**', 'default_billing' => 2, 'default_shipping' => 2]); $customer->expects($this->once())->method('getId')->willReturn($customerId); $customer->expects($this->once())->method('getAddresses')->willReturn([$address]); $address->expects($this->atLeastOnce())->method('getId')->willReturn(2); $address->expects($this->once())->method('load')->with(2)->willReturnSelf(); $address->expects($this->once())->method('getData')->willReturn(['firstname' => 'firstname', 'lastname' => 'lastname', 'street' => "street\nstreet"]); $helper = new ObjectManager($this); $dataProvider = $helper->getObject('\\Magento\\Customer\\Model\\Customer\\DataProvider', ['name' => 'test-name', 'primaryFieldName' => 'primary-field-name', 'requestFieldName' => 'request-field-name', 'eavValidationRules' => $this->eavValidationRulesMock, 'customerCollectionFactory' => $this->customerCollectionFactoryMock, 'eavConfig' => $this->getEavConfigMock()]); $reflection = new \ReflectionClass(get_class($dataProvider)); $reflectionProperty = $reflection->getProperty('session'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($dataProvider, $this->sessionMock); $this->sessionMock->expects($this->once())->method('getCustomerFormData')->willReturn($customerFormData); $this->sessionMock->expects($this->once())->method('unsCustomerFormData'); $this->assertEquals([$customerId => $customerFormData], $dataProvider->getData()); }
/** * Check captcha on user login page * * @param \Magento\Framework\Event\Observer $observer * @throws NoSuchEntityException * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $formId = 'user_login'; $captchaModel = $this->_helper->getCaptcha($formId); $controller = $observer->getControllerAction(); $loginParams = $controller->getRequest()->getPost('login'); $login = is_array($loginParams) && array_key_exists('username', $loginParams) ? $loginParams['username'] : null; if ($captchaModel->isRequired($login)) { $word = $this->captchaStringResolver->resolve($controller->getRequest(), $formId); if (!$captchaModel->isCorrect($word)) { try { $customer = $this->getCustomerRepository()->get($login); $this->getAuthentication()->processAuthenticationFailure($customer->getId()); } catch (NoSuchEntityException $e) { //do nothing as customer existance is validated later in authenticate method } $this->messageManager->addError(__('Incorrect CAPTCHA')); $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); $this->_session->setUsername($login); $beforeUrl = $this->_session->getBeforeAuthUrl(); $url = $beforeUrl ? $beforeUrl : $this->_customerUrl->getLoginUrl(); $controller->getResponse()->setRedirect($url); } } $captchaModel->logAttempt($login); return $this; }
/** * @param string $vaultPaymentCode * @return TokenUiComponentInterface[] */ public function getTokensComponents($vaultPaymentCode) { $result = []; $customerId = $this->session->getCustomerId(); if (!$customerId) { return $result; } $vaultPayment = $this->getVaultPayment($vaultPaymentCode); if ($vaultPayment === null) { return $result; } $vaultProviderCode = $vaultPayment->getProviderCode(); $componentProvider = $this->getComponentProvider($vaultProviderCode); if ($componentProvider === null) { return $result; } $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::CUSTOMER_ID)->setValue($customerId)->create(); $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::PAYMENT_METHOD_CODE)->setValue($vaultProviderCode)->create(); $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::IS_ACTIVE)->setValue(1)->create(); $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::EXPIRES_AT)->setConditionType('gt')->setValue($this->dateTimeFactory->create('now', new \DateTimeZone('UTC'))->format('Y-m-d 00:00:00'))->create(); $searchCriteria = $this->searchCriteriaBuilder->addFilters($filters)->create(); foreach ($this->paymentTokenRepository->getList($searchCriteria)->getItems() as $token) { $result[] = $componentProvider->getComponentForToken($token); } return $result; }
public function testAroundDispatchCurrencyFromSession() { $this->sessionMock->expects($this->any())->method('getCurrencyCode')->will($this->returnValue(self::CURRENCY_SESSION)); $this->httpContextMock->expects($this->at(0))->method('setValue')->with(StoreManagerInterface::CONTEXT_STORE, 'custom_store', 'default'); /** Make sure that current currency is taken from session if available */ $this->httpContextMock->expects($this->at(1))->method('setValue')->with(Context::CONTEXT_CURRENCY, self::CURRENCY_SESSION, self::CURRENCY_DEFAULT); $this->assertEquals('ExpectedValue', $this->plugin->aroundDispatch($this->subjectMock, $this->closureMock, $this->requestMock)); }
/** * Check Captcha On User Login Page * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $formId = 'user_create'; $captchaModel = $this->_helper->getCaptcha($formId); if ($captchaModel->isRequired()) { /** @var \Magento\Framework\App\Action\Action $controller */ $controller = $observer->getControllerAction(); if (!$captchaModel->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId))) { $this->messageManager->addError(__('Incorrect CAPTCHA')); $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); $this->_session->setCustomerFormData($controller->getRequest()->getPostValue()); $url = $this->_urlManager->getUrl('*/*/create', ['_nosecret' => true]); $controller->getResponse()->setRedirect($this->redirect->error($url)); } } return $this; }
/** * @param \Magento\Framework\App\ActionInterface $subject * @param callable $proceed * @param \Magento\Framework\App\RequestInterface $request * @return mixed * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundDispatch(\Magento\Framework\App\ActionInterface $subject, \Closure $proceed, \Magento\Framework\App\RequestInterface $request) { /** @var \Magento\Store\Model\Store $defaultStore */ $defaultStore = $this->storeManager->getWebsite()->getDefaultStore(); $storeCode = $this->httpRequest->getParam(StoreResolverInterface::PARAM_NAME, $this->storeCookieManager->getStoreCodeFromCookie()); if (is_array($storeCode)) { if (!isset($storeCode['_data']['code'])) { throw new \InvalidArgumentException(new Phrase('Invalid store parameter.')); } $storeCode = $storeCode['_data']['code']; } /** @var \Magento\Store\Model\Store $currentStore */ $currentStore = $storeCode ? $this->storeManager->getStore($storeCode) : $defaultStore; $this->httpContext->setValue(StoreManagerInterface::CONTEXT_STORE, $currentStore->getCode(), $this->storeManager->getDefaultStoreView()->getCode()); $this->httpContext->setValue(HttpContext::CONTEXT_CURRENCY, $this->session->getCurrencyCode() ?: $currentStore->getDefaultCurrencyCode(), $defaultStore->getDefaultCurrencyCode()); return $proceed($request); }
/** * Save block content to cache storage * * @param string $data * @return $this */ protected function _saveCache($data) { if ($this->getCacheLifetime() === null || !$this->_cacheState->isEnabled(self::CACHE_GROUP)) { return false; } $cacheKey = $this->getCacheKey(); $data = str_replace($this->_sidResolver->getSessionIdQueryParam($this->_session) . '=' . $this->_session->getSessionId(), $this->_getSidPlaceholder($cacheKey), $data); $this->_cache->save($data, $cacheKey, $this->getCacheTags(), $this->getCacheLifetime()); return $this; }
/** * Check Captcha On User Login Backend Page * * @param \Magento\Framework\Event\Observer $observer * @throws \Magento\Framework\Exception\Plugin\AuthenticationException * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $formId = 'backend_forgotpassword'; $captchaModel = $this->_helper->getCaptcha($formId); $controller = $observer->getControllerAction(); $email = (string) $observer->getControllerAction()->getRequest()->getParam('email'); $params = $observer->getControllerAction()->getRequest()->getParams(); if (!empty($email) && !empty($params)) { if ($captchaModel->isRequired()) { if (!$captchaModel->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId))) { $this->_session->setEmail((string) $controller->getRequest()->getPost('email')); $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); $this->messageManager->addError(__('Incorrect CAPTCHA')); $controller->getResponse()->setRedirect($controller->getUrl('*/*/forgotpassword', ['_nosecret' => true])); } } } return $this; }
public function testIsValidForHost() { $_SERVER['HTTP_HOST'] = 'localhost'; $this->_model->start('test'); $reflection = new \ReflectionMethod($this->_model, '_addHost'); $reflection->setAccessible(true); $reflection->invoke($this->_model); $this->assertFalse($this->_model->isValidForHost('test.com')); $this->assertTrue($this->_model->isValidForHost('localhost')); $this->_model->destroy(); }
/** * Check Captcha On User Login Page * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $formId = 'user_login'; $captchaModel = $this->_helper->getCaptcha($formId); $controller = $observer->getControllerAction(); $loginParams = $controller->getRequest()->getPost('login'); $login = array_key_exists('username', $loginParams) ? $loginParams['username'] : null; if ($captchaModel->isRequired($login)) { $word = $this->captchaStringResolver->resolve($controller->getRequest(), $formId); if (!$captchaModel->isCorrect($word)) { $this->messageManager->addError(__('Incorrect CAPTCHA')); $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); $this->_session->setUsername($login); $beforeUrl = $this->_session->getBeforeAuthUrl(); $url = $beforeUrl ? $beforeUrl : $this->_customerUrl->getLoginUrl(); $controller->getResponse()->setRedirect($url); } } $captchaModel->logAttempt($login); return $this; }
/** * Test aroundDispatch */ public function testAroundDispatch() { $this->storeManagerMock->expects($this->exactly(2))->method('getWebsite')->will($this->returnValue($this->websiteMock)); $this->websiteMock->expects($this->exactly(2))->method('getDefaultStore')->will($this->returnValue($this->storeMock)); $this->storeMock->expects($this->once())->method('getDefaultCurrency')->will($this->returnValue($this->currencyMock)); $this->storeMock->expects($this->once())->method('getStoreCodeFromCookie')->will($this->returnValue('storeCookie')); $this->currencyMock->expects($this->once())->method('getCode')->will($this->returnValue('UAH')); $this->sessionMock->expects($this->once())->method('getCurrencyCode')->will($this->returnValue('UAH')); $this->httpRequestMock->expects($this->once())->method('getParam')->with($this->equalTo('___store'))->will($this->returnValue('default')); $this->httpContextMock->expects($this->atLeastOnce())->method('setValue')->will($this->returnValueMap([[\Magento\Core\Helper\Data::CONTEXT_CURRENCY, 'UAH', 'UAH', $this->httpContextMock], [\Magento\Core\Helper\Data::CONTEXT_STORE, 'default', 'default', $this->httpContextMock]])); $this->assertEquals('ExpectedValue', $this->plugin->aroundDispatch($this->subjectMock, $this->closureMock, $this->requestMock)); }
/** * @param \Magento\Customer\Controller\Ajax\Login $subject * @param callable $proceed * @return \Magento\Framework\Controller\ResultInterface * @throws \Zend_Json_Exception */ public function aroundExecute(\Magento\Customer\Controller\Ajax\Login $subject, \Closure $proceed) { $loginFormId = 'user_login'; $captchaInputName = 'captcha_string'; /** @var \Magento\Framework\App\RequestInterface $request */ $request = $subject->getRequest(); /** @var \Magento\Captcha\Model\ModelInterface $captchaModel */ $captchaModel = $this->helper->getCaptcha($loginFormId); $loginParams = \Zend_Json::decode($request->getContent()); $username = isset($loginParams['username']) ? $loginParams['username'] : null; $captchaString = isset($loginParams[$captchaInputName]) ? $loginParams[$captchaInputName] : null; if ($captchaModel->isRequired($username)) { $captchaModel->logAttempt($username); if (!$captchaModel->isCorrect($captchaString)) { $this->sessionManager->setUsername($username); /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); return $resultJson->setData(['errors' => true, 'message' => __('Incorrect CAPTCHA')]); } } return $proceed(); }
/** * @magentoDataFixture Magento/Customer/_files/customer_group.php */ public function testSaveActionNewGroupWithoutGroupCode() { $groupId = $this->findGroupIdWithCode(self::CUSTOMER_GROUP_CODE); $originalCode = $this->groupRepository->getById($groupId)->getCode(); $this->getRequest()->setParam('tax_class', self::TAX_CLASS_ID); $this->dispatch('backend/customer/group/save'); $this->assertSessionMessages($this->equalTo(['code is a required field.']), MessageInterface::TYPE_ERROR); $this->assertSessionMessages($this->isEmpty(), MessageInterface::TYPE_SUCCESS); $this->assertEquals($originalCode, $this->groupRepository->getById($groupId)->getCode()); $this->assertRedirect($this->stringStartsWith(self::BASE_CONTROLLER_URL . 'edit/')); $this->assertEquals('', $this->session->getCustomerGroupData()['customer_group_code']); $this->assertEquals(self::TAX_CLASS_ID, $this->session->getCustomerGroupData()['tax_class_id']); }
/** * After generate Xml * * @param \Magento\Framework\View\LayoutInterface $subject * @param \Magento\Framework\View\LayoutInterface $result * @return \Magento\Framework\View\LayoutInterface */ public function afterGenerateXml(\Magento\Framework\View\LayoutInterface $subject, $result) { if ($this->moduleManager->isEnabled('Magento_PageCache') && $this->cacheConfig->isEnabled() && !$this->request->isAjax() && $subject->isCacheable()) { $this->visitor->setSkipRequestLogging(true); $this->visitor->unsetData(); $this->session->clearStorage(); $this->customerSession->clearStorage(); $this->session->setData(\Magento\Framework\Data\Form\FormKey::FORM_KEY, $this->formKey); $this->customerSession->setCustomerGroupId($this->customerGroupId); $this->customer->setGroupId($this->customerGroupId); $this->customerSession->setCustomer($this->customer); } return $result; }
/** * Save visitor by request * * Used in event "controller_action_postdispatch" * * @param \Magento\Framework\Event\Observer $observer * @return \Magento\Customer\Model\Visitor */ public function saveByRequest($observer) { if ($this->skipRequestLogging || $this->isModuleIgnored($observer)) { return $this; } try { $this->save(); $this->_eventManager->dispatch('visitor_activity_save', ['visitor' => $this]); $this->session->setVisitorData($this->getData()); } catch (\Exception $e) { $this->_logger->critical($e); } return $this; }