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

Add support for ALTCHA, an alternative to current Google Recaptcha #10456

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
115 changes: 115 additions & 0 deletions classes/form/validation/FormValidatorAltcha.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<?php

/**
* @file classes/form/validation/FormValidatorAltcha.php
*
* Copyright (c) 2014-2024 Simon Fraser University
* Copyright (c) 2000-2024 John Willinsky
* Distributed under the GNU GPL v3. For full terms see the file docs/COPYING.
*
* @class FormValidatorAltcha
*
* @ingroup form_validation
*
* @brief Form validation check Altcha values.
*/

namespace PKP\form\validation;

use AltchaOrg\Altcha\Altcha;
use AltchaOrg\Altcha\ChallengeOptions;
use APP\core\Application;
use APP\template\TemplateManager;
use Exception;
use InvalidArgumentException;
use PKP\config\Config;
use PKP\form\Form;

class FormValidatorAltcha extends FormValidator
{
/** @var string The response field containing the ALTCHA response */
private const ALTCHA_RESPONSE_FIELD = 'altcha';

/** @var string The initiating IP address of the user */
private $_userIp;

/**
* Constructor.
*
* @param string $userIp IP address of user request
* @param string $message Key of message to display on mismatch
*/
public function __construct(Form $form, string $userIp, string $message)
{
parent::__construct($form, self::ALTCHA_RESPONSE_FIELD, FormValidator::FORM_VALIDATOR_REQUIRED_VALUE, $message);
$this->_userIp = $userIp;
}

/**
* @see FormValidator::isValid()
* Determine whether or not the form meets this ALTCHA constraint.
*/
public function isValid(): bool
{
$form = $this->getForm();
try {
$this->validateResponse($form->getData(self::ALTCHA_RESPONSE_FIELD), $this->_userIp);
return true;
} catch (Exception $exception) {
$this->_message = 'common.captcha.error.missing-input-response';
return false;
}
}

/**
* Validates the ALTCHA response
*
* @param $response The ALTCHA response
* @param $ip The user IP address (defaults to null)
*
* @throws Exception Throws in case the validation fails
*/
public static function validateResponse(?string $response, ?string $ip = null): void
{
if (!empty($ip) && !filter_var($ip, FILTER_VALIDATE_IP)) {
throw new InvalidArgumentException('Invalid IP address.');
}

if (empty($response)) {
throw new InvalidArgumentException('The ALTCHA user response is required.');
}

$hmacKey = Config::getVar('captcha', 'altcha_hmackey');
if (empty($hmacKey)) {
throw new Exception('The ALTCHA is not configured correctly, the HMAC key is missing.');
}

$payload = (array) json_decode(base64_decode($response));

if (!Altcha::verifySolution($payload, $hmacKey)) {
throw new Exception('The ALTCHA validation failed.');
}
}

public static function addAltchaJavascript(TemplateManager &$templateMgr): void
{
$request = Application::get()->getRequest();
$altchaPath = $request->getBaseUrl() . '/node_modules/altcha/dist/altcha.js';

$altchaHeader = '<script async defer src="' . $altchaPath . '" type="module"></script>';
$templateMgr->addHeader('altcha', $altchaHeader);
}

public static function insertFormChallenge(TemplateManager &$templateMgr): void
{
$options = new ChallengeOptions([
'hmacKey' => Config::getVar('captcha', 'altcha_hmackey'),
'number' => Config::getVar('captcha', 'altcha_encrypt_number') ?: 10000, // Default value for a 3 to 5 seconds average solving time
]);

$challenge = (array) Altcha::createChallenge($options);

$templateMgr->assign('altchaEnabled', true);
$templateMgr->assign('altchaChallenge', $challenge);
}
}
28 changes: 22 additions & 6 deletions classes/user/form/RegistrationForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use PKP\db\DAORegistry;
use PKP\facades\Locale;
use PKP\form\Form;
use PKP\form\validation\FormValidatorAltcha;
use PKP\orcid\OrcidManager;
use PKP\security\Role;
use PKP\security\Validation;
Expand All @@ -46,12 +47,10 @@ class RegistrationForm extends Form
/** @var bool whether or not captcha is enabled for this form */
public $captchaEnabled;

/**
* Constructor.
*
* @param Site $site
*/
public function __construct($site)
/** @var bool whether or not captcha is enabled for this form */
public $altchaEnabled;

public function __construct(Site $site)
{
parent::__construct('frontend/pages/userRegister.tpl');

Expand All @@ -78,6 +77,12 @@ public function __construct($site)
$this->addCheck(new \PKP\form\validation\FormValidatorReCaptcha($this, $request->getRemoteAddr(), 'common.captcha.error.invalid-input-response', $request->getServerHost()));
}

$this->altchaEnabled = Config::getVar('captcha', 'altcha') && Config::getVar('captcha', 'altcha_on_register');
if ($this->altchaEnabled) {
$request = Application::get()->getRequest();
$this->addCheck(new \PKP\form\validation\FormValidatorAltcha($this, $request->getRemoteAddr(), 'common.captcha.error.invalid-input-response'));
}

$context = Application::get()->getRequest()->getContext();
if ($context && $context->getData('privacyStatement')) {
$this->addCheck(new \PKP\form\validation\FormValidator($this, 'privacyConsent', 'required', 'user.profile.form.privacyConsentRequired'));
Expand All @@ -101,6 +106,11 @@ public function fetch($request, $template = null, $display = false)
$templateMgr->assign('recaptchaPublicKey', Config::getVar('captcha', 'recaptcha_public_key'));
}

if ($this->altchaEnabled) {
FormValidatorAltcha::addAltchaJavascript($templateMgr);
FormValidatorAltcha::insertFormChallenge($templateMgr);
}

$countries = [];
foreach (Locale::getCountries() as $country) {
$countries[$country->getAlpha2()] = $country->getLocalName();
Expand Down Expand Up @@ -179,6 +189,12 @@ public function readInputData()
]);
}

if ($this->altchaEnabled) {
$this->readUserVars([
'altcha'
]);
}

// Collect the specified user group IDs into a single piece of data
$this->setData('userGroupIds', array_merge(
array_keys((array) $this->getData('readerGroup')),
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"require": {
"php": "^8.2",
"altcha-org/altcha": "^0.1.2",
"composer/semver": "^3.4",
"cweagans/composer-patches": "^1.7",
"dflydev/base32-crockford": "^1.0",
Expand Down
93 changes: 43 additions & 50 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading