Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recaptcha initialization #191

Merged
merged 14 commits into from
Apr 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 0 additions & 13 deletions ReCaptchaAdminUi/view/adminhtml/layout/recaptcha.xml

This file was deleted.

61 changes: 61 additions & 0 deletions ReCaptchaCustomer/Model/AjaxLogin/ErrorProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\ReCaptchaCustomer\Model\AjaxLogin;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\ActionFlag;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Serialize\SerializerInterface;

/**
* Process error during ajax login
*
* Set "no dispatch" flag and error message to Response
*/
class ErrorProcessor
{
/**
* @var ActionFlag
*/
private $actionFlag;

/**
* @var SerializerInterface
*/
private $serializer;

/**
* @param ActionFlag $actionFlag
* @param SerializerInterface $serializer
*/
public function __construct(
ActionFlag $actionFlag,
SerializerInterface $serializer
) {
$this->actionFlag = $actionFlag;
$this->serializer = $serializer;
}

/**
* Set "no dispatch" flag and error message to Response
*
* @param ResponseInterface $response
* @param string $message
* @return void
*/
public function processError(ResponseInterface $response, string $message): void
{
$this->actionFlag->set('', Action::FLAG_NO_DISPATCH, true);

$jsonPayload = $this->serializer->serialize([
'errors' => true,
'message' => $message,
]);
$response->representJson($jsonPayload);
}
}
56 changes: 18 additions & 38 deletions ReCaptchaCustomer/Observer/AjaxLoginObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@
namespace Magento\ReCaptchaCustomer\Observer;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\ActionFlag;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\ReCaptchaCustomer\Model\AjaxLogin\ErrorProcessor;
use Magento\ReCaptchaUi\Model\CaptchaResponseResolverInterface;
use Magento\ReCaptchaUi\Model\IsCaptchaEnabledInterface;
use Magento\ReCaptchaUi\Model\ValidationConfigResolverInterface;
Expand All @@ -41,16 +39,6 @@ class AjaxLoginObserver implements ObserverInterface
*/
private $captchaValidator;

/**
* @var ActionFlag
*/
private $actionFlag;

/**
* @var SerializerInterface
*/
private $serializer;

/**
* @var IsCaptchaEnabledInterface
*/
Expand All @@ -61,31 +49,33 @@ class AjaxLoginObserver implements ObserverInterface
*/
private $logger;

/**
* @var ErrorProcessor
*/
private $errorProcessor;

/**
* @param CaptchaResponseResolverInterface $captchaResponseResolver
* @param ValidationConfigResolverInterface $validationConfigResolver
* @param ValidatorInterface $captchaValidator
* @param ActionFlag $actionFlag
* @param SerializerInterface $serializer
* @param IsCaptchaEnabledInterface $isCaptchaEnabled
* @param LoggerInterface $logger
* @param ErrorProcessor $errorProcessor
*/
public function __construct(
CaptchaResponseResolverInterface $captchaResponseResolver,
ValidationConfigResolverInterface $validationConfigResolver,
ValidatorInterface $captchaValidator,
ActionFlag $actionFlag,
SerializerInterface $serializer,
IsCaptchaEnabledInterface $isCaptchaEnabled,
LoggerInterface $logger
LoggerInterface $logger,
ErrorProcessor $errorProcessor
) {
$this->captchaResponseResolver = $captchaResponseResolver;
$this->validationConfigResolver = $validationConfigResolver;
$this->captchaValidator = $captchaValidator;
$this->actionFlag = $actionFlag;
$this->serializer = $serializer;
$this->isCaptchaEnabled = $isCaptchaEnabled;
$this->logger = $logger;
$this->errorProcessor = $errorProcessor;
}

/**
Expand All @@ -108,30 +98,20 @@ public function execute(Observer $observer): void
$reCaptchaResponse = $this->captchaResponseResolver->resolve($request);
} catch (InputException $e) {
$this->logger->error($e);
$this->processError($response, $validationConfig->getValidationFailureMessage());
$this->errorProcessor->processError(
$response,
$validationConfig->getValidationFailureMessage()
);
return;
}

$validationResult = $this->captchaValidator->isValid($reCaptchaResponse, $validationConfig);
if (false === $validationResult->isValid()) {
$this->processError($response, $validationConfig->getValidationFailureMessage());
$this->errorProcessor->processError(
$response,
$validationConfig->getValidationFailureMessage()
);
}
}
}

/**
* @param ResponseInterface $response
* @param string $message
* @return void
*/
private function processError(ResponseInterface $response, string $message): void
{
$this->actionFlag->set('', Action::FLAG_NO_DISPATCH, true);

$jsonPayload = $this->serializer->serialize([
'errors' => true,
'message' => $message,
]);
$response->representJson($jsonPayload);
}
}
16 changes: 4 additions & 12 deletions ReCaptchaFrontendUi/view/frontend/web/js/reCaptcha.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ define(
'uiComponent',
'jquery',
'ko',
'Magento_ReCaptchaFrontendUi/js/registry'
'Magento_ReCaptchaFrontendUi/js/registry',
'Magento_ReCaptchaFrontendUi/js/reCaptchaScriptLoader'
],
function (Component, $, ko, registry, undefined) {
function (Component, $, ko, registry, reCaptchaLoader, undefined) {
'use strict';

return Component.extend({
Expand Down Expand Up @@ -50,16 +51,7 @@ define(
$(window).trigger('recaptchaapiready');
}.bind(this);

element = document.createElement('script');
scriptTag = document.getElementsByTagName('script')[0];

element.async = true;
element.src = 'https://www.google.com/recaptcha/api.js' +
'?onload=globalOnRecaptchaOnLoadCallback&render=explicit' +
(this.settings.rendering.lang ? '&hl=' + this.settings.rendering.lang : '');

scriptTag.parentNode.insertBefore(element, scriptTag);

reCaptchaLoader.addReCaptchaScriptTag();
},

/**
Expand Down
33 changes: 33 additions & 0 deletions ReCaptchaFrontendUi/view/frontend/web/js/reCaptchaScriptLoader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

define([], function () {
'use strict';

var scriptTagAdded = false;

return {
/**
* Add script tag. Script tag should be added once
*/
addReCaptchaScriptTag: function () {
var element,
scriptTag;

if (!scriptTagAdded) {
element = document.createElement('script');
scriptTag = document.getElementsByTagName('script')[0];

element.async = true;
element.src = 'https://www.google.com/recaptcha/api.js' +
'?onload=globalOnRecaptchaOnLoadCallback&render=explicit';

scriptTag.parentNode.insertBefore(element, scriptTag);
scriptTagAdded = true;
}
}
}
}
);
13 changes: 6 additions & 7 deletions ReCaptchaUser/view/adminhtml/templates/recaptcha.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
$config = $block->getCaptchaUiConfig();
$renderingOptions = $config['rendering'] ?? [];
$isInvisible = !empty($config['invisible']);
$languageCode = $config['rendering']['lang'] ?? null;
?>
<div class="admin__field <?= /* @noEscape */ $isInvisible ? 'field-invisible-recaptcha' : 'field-recaptcha' ?>">
<div id="admin-recaptcha"
class="admin-recaptcha-content<?= /* @noEscape */ !empty($renderingOptions['size']) ? ' size-' . $renderingOptions['size'] : '' ?>"></div>
class="admin-recaptcha-content<?=
/* @noEscape */ !empty($renderingOptions['size']) ? ' size-' . $renderingOptions['size'] : '' ?>"></div>
</div>

<script>
Expand All @@ -25,25 +25,24 @@ $languageCode = $config['rendering']['lang'] ?? null;

element.async = true;
element.src = 'https://www.google.com/recaptcha/api.js'
+ '?onload=globalOnRecaptchaOnLoadCallback&render=explicit'
<?php if (null !== $languageCode): ?><?="+'&hl={$languageCode}'" ?><?php endif; ?>;
+ '?onload=globalOnRecaptchaOnLoadCallback&render=explicit';

window.globalOnRecaptchaOnLoadCallback = function () {
let token = '';

this.widgetId = grecaptcha.render('admin-recaptcha', {
<?php foreach($renderingOptions as $key => $value):?>
<?php foreach ($renderingOptions as $key => $value): ?>
'<?= $block->escapeJs($key) ?>': '<?= $block->escapeJs($value) ?>',
<?php endforeach; ?>
'callback': function (token) { // jscs:ignore jsDoc
<?php if ($isInvisible) : ?>
<?php if ($isInvisible): ?>
this.token = token;
$('#login-form').submit();
<?php endif; ?>
}.bind(this)
});

<?php if ($isInvisible) : ?>
<?php if ($isInvisible): ?>
$('#login-form').submit(function (event) {
if (!this.token) {
event.preventDefault(event);
Expand Down
34 changes: 17 additions & 17 deletions ReCaptchaVersion2Checkbox/Model/Adminhtml/UiConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,6 @@ public function __construct(
$this->scopeConfig = $scopeConfig;
}

/**
* @inheritdoc
*/
public function get(): array
{
$config = [
'rendering' => [
'sitekey' => $this->getPublicKey(),
'size' => $this->getSize(),
'theme' => $this->getTheme(),
'lang' => $this->getLanguageCode(),
],
'invisible' => false,
];
return $config;
}

/**
* Get Google API Website Key
*
Expand Down Expand Up @@ -96,4 +79,21 @@ private function getLanguageCode(): string
self::XML_PATH_LANGUAGE_CODE
);
}

/**
* @inheritdoc
*/
public function get(): array
{
$config = [
'rendering' => [
'sitekey' => $this->getPublicKey(),
'size' => $this->getSize(),
'theme' => $this->getTheme(),
'hl' => $this->getLanguageCode(),
],
'invisible' => false,
];
return $config;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,23 +51,6 @@ public function __construct(
$this->validationConfigFactory = $validationConfigFactory;
}

/**
* @inheritdoc
*/
public function get(): ValidationConfigInterface
{
/** @var ValidationConfigInterface $validationConfig */
$validationConfig = $this->validationConfigFactory->create(
[
'privateKey' => $this->getPrivateKey(),
'remoteIp' => $this->remoteAddress->getRemoteAddress(),
'validationFailureMessage' => $this->getValidationFailureMessage(),
'extensionAttributes' => null,
]
);
return $validationConfig;
}

/**
* Get Google API Secret Key
*
Expand All @@ -89,4 +72,21 @@ private function getValidationFailureMessage(): string
(string)$this->scopeConfig->getValue(self::XML_PATH_VALIDATION_FAILURE)
);
}

/**
* @inheritdoc
*/
public function get(): ValidationConfigInterface
{
/** @var ValidationConfigInterface $validationConfig */
$validationConfig = $this->validationConfigFactory->create(
[
'privateKey' => $this->getPrivateKey(),
'remoteIp' => $this->remoteAddress->getRemoteAddress(),
'validationFailureMessage' => $this->getValidationFailureMessage(),
'extensionAttributes' => null,
]
);
return $validationConfig;
}
}
Loading