Skip to content

Commit

Permalink
Magento Fork initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Yegor Shytikov committed Oct 13, 2021
1 parent e61cf9d commit c25f070
Show file tree
Hide file tree
Showing 18 changed files with 204 additions and 74 deletions.
38 changes: 9 additions & 29 deletions CustomerData/Captcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,50 +9,36 @@
namespace Magento\Captcha\CustomerData;

use Magento\Customer\CustomerData\SectionSourceInterface;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Captcha\Model\DefaultModel;
use Magento\Captcha\Helper\Data as CaptchaHelper;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;

/**
* Captcha section.
*
* @SuppressWarnings(PHPMD.CookieAndSessionMisuse)
* Captcha section
*/
class Captcha extends DataObject implements SectionSourceInterface
class Captcha extends \Magento\Framework\DataObject implements SectionSourceInterface
{
/**
* @var array
*/
private $formIds;

/**
* @var CaptchaHelper
* @var \Magento\Captcha\Helper\Data
*/
private $helper;

/**
* @var CustomerSession
*/
private $customerSession;

/**
* @param CaptchaHelper $helper
* @param \Magento\Captcha\Helper\Data $helper
* @param array $formIds
* @param array $data
* @param CustomerSession|null $customerSession
* @codeCoverageIgnore
*/
public function __construct(
CaptchaHelper $helper,
\Magento\Captcha\Helper\Data $helper,
array $formIds,
array $data = [],
?CustomerSession $customerSession = null
array $data = []
) {
parent::__construct($data);
$this->helper = $helper;
$this->formIds = $formIds;
parent::__construct($data);
$this->customerSession = $customerSession ?? ObjectManager::getInstance()->get(CustomerSession::class);
}

/**
Expand All @@ -63,15 +49,9 @@ public function getSectionData() :array
$data = [];

foreach ($this->formIds as $formId) {
/** @var DefaultModel $captchaModel */
$captchaModel = $this->helper->getCaptcha($formId);
$login = '';
if ($this->customerSession->isLoggedIn()) {
$login = $this->customerSession->getCustomerData()->getEmail();
}
$required = $captchaModel->isRequired($login);
$data[$formId] = [
'isRequired' => $required,
'isRequired' => $captchaModel->isRequired(),
'timestamp' => time()
];
}
Expand Down
8 changes: 6 additions & 2 deletions Model/Checkout/ConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
*/
namespace Magento\Captcha\Model\Checkout;

/**
* Configuration provider for Captcha rendering.
*/
class ConfigProvider implements \Magento\Checkout\Model\ConfigProviderInterface
{
/**
Expand Down Expand Up @@ -38,7 +41,7 @@ public function __construct(
}

/**
* {@inheritdoc}
* @inheritdoc
*/
public function getConfig()
{
Expand All @@ -49,7 +52,8 @@ public function getConfig()
'imageHeight' => $this->getImageHeight($formId),
'imageSrc' => $this->getImageSrc($formId),
'refreshUrl' => $this->getRefreshUrl(),
'isRequired' => $this->isRequired($formId)
'isRequired' => $this->isRequired($formId),
'timestamp' => time()
];
}
return $config;
Expand Down
9 changes: 8 additions & 1 deletion Model/Customer/Plugin/AjaxLogin.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\Controller\Result\JsonFactory;

/**
* Around plugin for login action.
*/
class AjaxLogin
{
/**
Expand Down Expand Up @@ -61,6 +64,8 @@ public function __construct(
}

/**
* Check captcha data on login action.
*
* @param \Magento\Customer\Controller\Ajax\Login $subject
* @param \Closure $proceed
* @return $this
Expand Down Expand Up @@ -94,18 +99,20 @@ public function aroundExecute(
if ($formId === $loginFormId) {
$captchaModel = $this->helper->getCaptcha($formId);
if ($captchaModel->isRequired($username)) {
$captchaModel->logAttempt($username);
if (!$captchaModel->isCorrect($captchaString)) {
$this->sessionManager->setUsername($username);
$captchaModel->logAttempt($username);
return $this->returnJsonError(__('Incorrect CAPTCHA'));
}
}
$captchaModel->logAttempt($username);
}
}
return $proceed();
}

/**
* Format JSON response.
*
* @param \Magento\Framework\Phrase $phrase
* @return \Magento\Framework\Controller\Result\Json
Expand Down
29 changes: 23 additions & 6 deletions Model/DefaultModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ class DefaultModel extends \Zend\Captcha\Image implements \Magento\Captcha\Model
*/
protected $session;

/**
* @var string
*/
private $words;

/**
* @param \Magento\Framework\Session\SessionManagerInterface $session
* @param \Magento\Captcha\Helper\Data $captchaData
Expand Down Expand Up @@ -311,18 +316,18 @@ public function getImgUrl()
*/
public function isCorrect($word)
{
$storedWord = $this->getWord();
$storedWords = $this->getWords();
$this->clearWord();

if (!$word || !$storedWord) {
if (!$word || !$storedWords) {
return false;
}

if (!$this->isCaseSensitive()) {
$storedWord = strtolower($storedWord);
$storedWords = strtolower($storedWords);
$word = strtolower($word);
}
return $word === $storedWord;
return in_array($word, explode(',', $storedWords));
}

/**
Expand Down Expand Up @@ -481,14 +486,25 @@ private function getTargetForms()
/**
* Get captcha word
*
* @return string
* @return string|null
*/
public function getWord()
{
$sessionData = $this->session->getData($this->getFormIdKey(self::SESSION_WORD));
return time() < $sessionData['expires'] ? $sessionData['data'] : null;
}

/**
* Get captcha words
*
* @return string|null
*/
private function getWords()
{
$sessionData = $this->session->getData($this->getFormIdKey(self::SESSION_WORD));
return time() < $sessionData['expires'] ? $sessionData['words'] : null;
}

/**
* Set captcha word
*
Expand All @@ -498,9 +514,10 @@ public function getWord()
*/
protected function setWord($word)
{
$this->words = $this->words ? $this->words . ',' . $word : $word;
$this->session->setData(
$this->getFormIdKey(self::SESSION_WORD),
['data' => $word, 'expires' => time() + $this->getTimeout()]
['data' => $word, 'words' => $this->words, 'expires' => time() + $this->getTimeout()]
);
$this->word = $word;
return $this;
Expand Down
2 changes: 1 addition & 1 deletion Test/Mftf/Section/StorefrontCustomerSignInFormSection.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd">
<section name="StorefrontCustomerSignInFormSection">
<section name="StorefrontCustomerSignInPopupFormSection">
<element name="captchaField" type="input" selector="#captcha_user_login"/>
<element name="captchaImg" type="block" selector=".captcha-img"/>
<element name="captchaReload" type="block" selector=".captcha-reload"/>
Expand Down
50 changes: 48 additions & 2 deletions Test/Mftf/Test/CaptchaFormsDisplayingTest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
-->

<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/magento2-functional-testing-framework/src/Magento/FunctionalTestingFramework/Test/etc/testSchema.xsd">
xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd">
<test name="CaptchaFormsDisplayingTest">
<annotations>
<features value="Captcha"/>
Expand Down Expand Up @@ -64,6 +64,52 @@
<!--Roll back configuration-->
<scrollToTopOfPage stepKey="ScrollToTop"/>
<click selector="{{CaptchaFormsDisplayingSection.captcha}}" stepKey="ClickToCloseCaptcha"/>

</test>
<test name="CaptchaWithDisabledGuestCheckout">
<annotations>
<features value="Captcha"/>
<stories value="MC-5602 - CAPTCHA doesn't appear in login popup after refreshing page."/>
<title value="Captcha is displaying on login form with disabled guest checkout"/>
<description value="Captcha is displaying on login form with disabled guest checkout"/>
<severity value="MAJOR"/>
<testCaseId value="MAGETWO-96691"/>
<group value="captcha"/>
</annotations>
<before>
<magentoCLI command="config:set checkout/options/guest_checkout 0" stepKey="disableGuestCheckout"/>
<magentoCLI command="config:set customer/captcha/failed_attempts_login 1" stepKey="decreaseLoginAttempt"/>
<createData entity="ApiCategory" stepKey="createCategory"/>
<createData entity="ApiSimpleProduct" stepKey="createSimpleProduct">
<requiredEntity createDataKey="createCategory"/>
</createData>
</before>
<after>
<magentoCLI command="config:set checkout/options/guest_checkout 1" stepKey="enableGuestCheckout"/>
<magentoCLI command="config:set customer/captcha/failed_attempts_login 3" stepKey="increaseLoginAttempt"/>
<deleteData createDataKey="createCategory" stepKey="deleteCategory"/>
<deleteData createDataKey="createSimpleProduct" stepKey="deleteSimpleProduct1"/>
</after>
<amOnPage url="{{StorefrontProductPage.url($$createSimpleProduct.sku$$)}}" stepKey="openProductPage"/>
<waitForPageLoad stepKey="waitForPageLoad"/>
<click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addToCart" />
<waitForText userInput="You added $$createSimpleProduct.name$$ to your shopping cart." stepKey="waitForText"/>
<click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickCart"/>
<click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="goToCheckout"/>
<waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.email}}" stepKey="waitEmailFieldVisible"/>
<fillField selector="{{StorefrontCustomerSignInPopupFormSection.email}}" userInput="{{Simple_US_Customer.email}}" stepKey="fillCustomerEmail"/>
<fillField selector="{{StorefrontCustomerSignInPopupFormSection.password}}" userInput="incorrectPassword" stepKey="fillIncorrectCustomerPassword"/>
<click selector="{{StorefrontCustomerSignInPopupFormSection.signIn}}" stepKey="clickSignIn"/>
<waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.errorMessage}}" stepKey="seeErrorMessage"/>
<waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaField}}" stepKey="seeCaptchaField"/>
<waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaImg}}" stepKey="seeCaptchaImage"/>
<waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaReload}}" stepKey="seeCaptchaReloadButton"/>
<reloadPage stepKey="refreshPage"/>
<waitForPageLoad stepKey="waitForPageLoad2"/>
<click selector="{{StorefrontMinicartSection.showCart}}" stepKey="clickCart2"/>
<click selector="{{StorefrontMinicartSection.goToCheckout}}" stepKey="goToCheckout2"/>
<waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.email}}" stepKey="waitEmailFieldVisible2"/>
<waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaField}}" stepKey="seeCaptchaField2"/>
<waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaImg}}" stepKey="seeCaptchaImage2"/>
<waitForElementVisible selector="{{StorefrontCustomerSignInPopupFormSection.captchaReload}}" stepKey="seeCaptchaReloadButton2"/>
</test>
</tests>
1 change: 1 addition & 0 deletions Test/Unit/Model/Checkout/ConfigProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public function testGetConfig($isRequired, $captchaGenerations, $expectedConfig)
->will($this->returnValue('https://magento.com/captcha'));

$config = $this->model->getConfig();
unset($config['captcha'][$this->formId]['timestamp']);
$this->assertEquals($config, $expectedConfig);
}

Expand Down
18 changes: 15 additions & 3 deletions Test/Unit/Model/DefaultTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,13 @@ public function testIsCorrect()
{
self::$_defaultConfig['case_sensitive'] = '1';
$this->assertFalse($this->_object->isCorrect('abcdef5'));
$sessionData = ['user_create_word' => ['data' => 'AbCdEf5', 'expires' => time() + self::EXPIRE_FRAME]];
$sessionData = [
'user_create_word' => [
'data' => 'AbCdEf5',
'words' => 'AbCdEf5',
'expires' => time() + self::EXPIRE_FRAME
]
];
$this->_object->getSession()->setData($sessionData);
self::$_defaultConfig['case_sensitive'] = '0';
$this->assertTrue($this->_object->isCorrect('abcdef5'));
Expand Down Expand Up @@ -224,7 +230,7 @@ public function testGetWord()
{
$this->assertEquals($this->_object->getWord(), 'AbCdEf5');
$this->_object->getSession()->setData(
['user_create_word' => ['data' => 'AbCdEf5', 'expires' => time() - 360]]
['user_create_word' => ['data' => 'AbCdEf5', 'words' => 'AbCdEf5','expires' => time() - 360]]
);
$this->assertNull($this->_object->getWord());
}
Expand All @@ -247,7 +253,13 @@ protected function _getSessionStub()
->getMock();
$session->expects($this->any())->method('isLoggedIn')->will($this->returnValue(false));

$session->setData(['user_create_word' => ['data' => 'AbCdEf5', 'expires' => time() + self::EXPIRE_FRAME]]);
$session->setData([
'user_create_word' => [
'data' => 'AbCdEf5',
'words' => 'AbCdEf5',
'expires' => time() + self::EXPIRE_FRAME
]
]);
return $session;
}

Expand Down
Loading

0 comments on commit c25f070

Please sign in to comment.