Skip to content

Commit

Permalink
ReCaptcha compatability with Magento 2.4.x
Browse files Browse the repository at this point in the history
  • Loading branch information
ihorvansach committed Nov 9, 2020
1 parent a04ba1d commit 4c2613e
Show file tree
Hide file tree
Showing 12 changed files with 279 additions and 155 deletions.
63 changes: 63 additions & 0 deletions Model/CaptchaResponseResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magefan (support@magefan.com). All rights reserved.
* Please visit Magefan.com for license details (https://magefan.com/end-user-license-agreement).
*/
declare(strict_types=1);

namespace Magefan\BlogCommentsReCaptcha\Model;

use Magento\Framework\App\PlainTextRequestInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\ReCaptchaUi\Model\CaptchaResponseResolverInterface;

/**
* @inheritdoc
*/
class CaptchaResponseResolver implements CaptchaResponseResolverInterface
{
/**
* @var SerializerInterface
*/
private $serializer;

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

/**
* {@inheritdoc}
*
* @param RequestInterface|PlainTextRequestInterface $request
* @return string
* @throws InputException
*/
public function resolve(RequestInterface $request): string
{
$content = $request->getContent();

if (empty($content)) {
throw new InputException(__('Can not resolve reCAPTCHA response.'));
}

try {
//$params = $this->serializer->unserialize($content);
$params = [];
parse_str($content, $params);
} catch (\InvalidArgumentException $e) {
throw new InputException(__('Can not resolve reCAPTCHA response.'), $e);
}

if (empty($params[self::PARAM_RECAPTCHA])) {
throw new InputException(__('Can not resolve reCAPTCHA response.'));
}

return $params[self::PARAM_RECAPTCHA];
}
}
63 changes: 63 additions & 0 deletions Model/ErrorProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magefan (support@magefan.com). All rights reserved.
* Please visit Magefan.com for license details (https://magefan.com/end-user-license-agreement).
*/
declare(strict_types=1);

namespace Magefan\BlogCommentsReCaptcha\Model;

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(
[
'success' => false,
'message' => $message,
]
);
$response->representJson($jsonPayload);
}
}
63 changes: 0 additions & 63 deletions Model/Provider/Failure/AjaxResponseFailure.php

This file was deleted.

117 changes: 117 additions & 0 deletions Observer/CommentFormObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php
/**
* Copyright © Magefan (support@magefan.com). All rights reserved.
* Please visit Magefan.com for license details (https://magefan.com/end-user-license-agreement).
*/
declare(strict_types=1);

namespace Magefan\BlogCommentsReCaptcha\Observer;

use Magento\Framework\App\Action\Action;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magefan\BlogCommentsReCaptcha\Model\ErrorProcessor;
use Magento\ReCaptchaUi\Model\CaptchaResponseResolverInterface;
use Magento\ReCaptchaUi\Model\IsCaptchaEnabledInterface;
use Magento\ReCaptchaUi\Model\ValidationConfigResolverInterface;
use Magento\ReCaptchaValidationApi\Api\ValidatorInterface;
use Psr\Log\LoggerInterface;

/**
* ReviewFormObserver
*/
class CommentFormObserver implements ObserverInterface
{
/**
* @var CaptchaResponseResolverInterface
*/
private $captchaResponseResolver;

/**
* @var ValidationConfigResolverInterface
*/
private $validationConfigResolver;

/**
* @var ValidatorInterface
*/
private $captchaValidator;

/**
* @var IsCaptchaEnabledInterface
*/
private $isCaptchaEnabled;

/**
* @var LoggerInterface
*/
private $logger;

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

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

/**
* @param Observer $observer
* @return void
* @throws LocalizedException
*/
public function execute(Observer $observer): void
{
$key = 'mfblog_comment';
if ($this->isCaptchaEnabled->isCaptchaEnabledFor($key)) {
$controller = $observer->getControllerAction();
$request = $controller->getRequest();
$response = $controller->getResponse();

$validationConfig = $this->validationConfigResolver->get($key);

try {
$reCaptchaResponse = $this->captchaResponseResolver->resolve($request);
} catch (InputException $e) {
var_dump($e->getMessage());
$this->logger->error($e);
$this->errorProcessor->processError(
$response,
$validationConfig->getValidationFailureMessage()
);
return;
}

$validationResult = $this->captchaValidator->isValid($reCaptchaResponse, $validationConfig);
if (false === $validationResult->isValid()) {
$this->errorProcessor->processError(
$response,
$validationConfig->getValidationFailureMessage()
);
}
}
}
}
45 changes: 0 additions & 45 deletions Plugin/Model/LayoutSettingsPlugin.php

This file was deleted.

3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
"name": "magefan/module-blog-comments-recaptcha",
"description": "Add recaptcha to Magefan Blog Comments",
"require": {
"magento/module-re-captcha-validation-api" : ">=1.0.0",
"magefan/module-blog" : ">=2.9.7"
},
"type": "magento2-module",
"version": "2.0.6",
"version": "2.1.0",
"autoload": {
"files": [ "registration.php" ],
"psr-4": {
Expand Down
16 changes: 6 additions & 10 deletions etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,12 @@
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="msp_securitysuite_recaptcha">
<group id="frontend" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1"
showInStore="1">
<field id="enabled_mfblog_comments" translate="label" type="select" sortOrder="220" showInDefault="1"
showInWebsite="1" showInStore="0" >
<label>Use in Magefan Blog Comments</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<depends>
<field id="enabled">1</field>
</depends>
<section id="recaptcha_frontend">
<group id="type_for">
<field id="mfblog_comment" translate="label" type="select" sortOrder="220" showInDefault="1"
showInWebsite="1" showInStore="0" canRestore="1">
<label>Enable for Magefan Blog Comments</label>
<source_model>Magento\ReCaptchaAdminUi\Model\OptionSource\Type</source_model>
</field>
</group>
</section>
Expand Down
Loading

0 comments on commit 4c2613e

Please sign in to comment.