Skip to content

Commit

Permalink
[FEATURE] Add TCA field control „passwordGenerator“
Browse files Browse the repository at this point in the history
This patch adds a new TCA field control "passwordGenerator" for
TCA type "password", which can be used to generate a random
password, based on defined password rules.

The field control will be used in EXT:reactions the first time.

In the future the field control might be combined with the
existing password policies functionality. Therefore, most
of the new functions and classes are marked as internal
for now.

Another feature to be added in the future will be (according
to #69190) a modal / wizard, which will allow to change rules
for the password to be generated.

Resolves: #98540
Related: #98373
Releases: main
Change-Id: Iab21b8bd0b3c261a702234579f62ba841c54ea0d
Reviewed-on: https://review.typo3.org/c/Packages/TYPO3.CMS/+/76002
Tested-by: Benni Mack <benni@typo3.org>
Tested-by: core-ci <typo3@b13.com>
Tested-by: Georg Ringer <georg.ringer@gmail.com>
Reviewed-by: Benni Mack <benni@typo3.org>
Reviewed-by: Oliver Hader <oliver.hader@typo3.org>
Reviewed-by: Georg Ringer <georg.ringer@gmail.com>
  • Loading branch information
NeoBlack authored and georgringer committed Nov 7, 2022
1 parent cd901b4 commit 445912f
Show file tree
Hide file tree
Showing 11 changed files with 477 additions and 0 deletions.
@@ -0,0 +1,92 @@
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/

import DocumentService from '@typo3/core/document-service';
import SecurityUtility from '@typo3/core/security-utility';
import FormEngineValidation from '@typo3/backend/form-engine-validation';
import AjaxRequest from '@typo3/core/ajax/ajax-request';
import {AjaxResponse} from '@typo3/core/ajax/ajax-response';
import Notification from '@typo3/backend/notification';

interface PasswordRules {
length: number;
random: string;
digitCharacters: boolean;
lowerCaseCharacters: boolean;
upperCaseCharacters: boolean;
specialCharacters: boolean;
}

/**
* Handles the "Generate Password" field control
*/
class PasswordGenerator {
private securityUtility: SecurityUtility = null;
private controlElement: HTMLAnchorElement = null;
private humanReadableField: HTMLInputElement = null;
private hiddenField: HTMLInputElement = null;
private passwordRules: PasswordRules = null;

constructor(controlElementId: string) {
this.securityUtility = new SecurityUtility();

DocumentService.ready().then((): void => {
this.controlElement = <HTMLAnchorElement>document.getElementById(controlElementId);
this.humanReadableField = <HTMLInputElement>document.querySelector(
'input[data-formengine-input-name="' + this.controlElement.dataset.itemName + '"]',
);
this.hiddenField = <HTMLInputElement>document.querySelector(
'input[name="' + this.controlElement.dataset.itemName + '"]',
);
this.passwordRules = JSON.parse(this.controlElement.dataset.passwordRules || '{}');

this.controlElement.addEventListener('click', this.generatePassword.bind(this));
});
}

private generatePassword(e: Event): void {
e.preventDefault();

// Generate new password
(new AjaxRequest(TYPO3.settings.ajaxUrls.password_generate)).post({
passwordRules: this.passwordRules,
})
.then(async (response: AjaxResponse): Promise<void> => {
const resolvedBody = await response.resolve();
if (resolvedBody.success === true) {
// Set type=text to display the generated password (allow to copy) and update the field value
this.humanReadableField.type = 'text';
if (!this.controlElement.dataset.allowEdit) {
this.humanReadableField.disabled = true;
this.humanReadableField.readOnly = true;
}
this.humanReadableField.value = resolvedBody.password;
// Manually dispatch "change" to enable FormEngine handling (instead of manually calling "updateInputField()").
// This way custom modules are also triggered when listening on this event.
this.humanReadableField.dispatchEvent(new Event('change'));
// Due to formatting and processing done by FormEngine, we need to set the value again (allow to copy)
this.humanReadableField.value = this.hiddenField.value;
// Finally validate and mark the field as changed
FormEngineValidation.validateField(this.humanReadableField);
FormEngineValidation.markFieldAsChanged(this.humanReadableField);
} else {
Notification.warning(resolvedBody.message || 'No password was generated');
}
})
.catch(() => {
Notification.error('Password could not be generated');
})
}
}

export default PasswordGenerator;
@@ -0,0 +1,67 @@
<?php

declare(strict_types=1);

/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/

namespace TYPO3\CMS\Backend\Form\FieldControl;

use TYPO3\CMS\Backend\Form\AbstractNode;
use TYPO3\CMS\Core\Page\JavaScriptModuleInstruction;
use TYPO3\CMS\Core\Utility\StringUtility;

/**
* Renders a widget where a password can be generated, typically used with type=password
*
* @internal Only to be used by TYPO3. Might change in the future.
*/
class PasswordGenerator extends AbstractNode
{
public function render(): array
{
$parameterArray = $this->data['parameterArray'];
if (($parameterArray['fieldConf']['config']['type'] ?? '') !== 'password') {
return [];
}

$options = $this->data['renderData']['fieldControlOptions'];
$itemName = (string)$parameterArray['itemFormElName'];
$id = StringUtility::getUniqueId('t3js-formengine-fieldcontrol-');

// Handle options and fallback
$title = $options['title'] ?? 'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.generatePassword';

$linkAttributes = [
'id' => $id,
'data-item-name' => $itemName,
];

if ($options['allowEdit'] ?? true) {
$linkAttributes['data-allow-edit'] = true;
}

if (is_array($options['passwordRules'] ?? false) && $options['passwordRules'] !== []) {
$linkAttributes['data-password-rules'] = (string)json_encode($options['passwordRules'], JSON_THROW_ON_ERROR);
}

return [
'iconIdentifier' => 'actions-refresh',
'title' => $title,
'linkAttributes' => $linkAttributes,
'javaScriptModules' => [
JavaScriptModuleInstruction::create('@typo3/backend/form-engine/field-control/password-generator.js')->instance($id),
],
];
}
}
1 change: 1 addition & 0 deletions typo3/sysext/backend/Classes/Form/NodeFactory.php
Expand Up @@ -135,6 +135,7 @@ class NodeFactory
'linkPopup' => FieldControl\LinkPopup::class,
'listModule' => FieldControl\ListModule::class,
'resetSelection' => FieldControl\ResetSelection::class,
'passwordGenerator' => FieldControl\PasswordGenerator::class,
];

/**
Expand Down
6 changes: 6 additions & 0 deletions typo3/sysext/backend/Configuration/Backend/AjaxRoutes.php
Expand Up @@ -370,4 +370,10 @@
'path' => '/record/download/settings',
'target' => \TYPO3\CMS\Backend\Controller\RecordListDownloadController::class . '::downloadSettingsAction',
],

// Endpoint to generate a password
'password_generate' => [
'path' => '/password/generate',
'target' => \TYPO3\CMS\Core\Controller\PasswordGeneratorController::class . '::generate',
],
];

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

@@ -0,0 +1,72 @@
<?php

declare(strict_types=1);

/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/

namespace TYPO3\CMS\Core\Controller;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use TYPO3\CMS\Core\Crypto\Random;
use TYPO3\CMS\Core\Exception\InvalidPasswordRulesException;
use TYPO3\CMS\Core\Localization\LanguageService;

/**
* @internal Only to be used within TYPO3. Might change in the future.
*/
class PasswordGeneratorController
{
public function __construct(
private readonly Random $random,
private readonly ResponseFactoryInterface $responseFactory,
private readonly StreamFactoryInterface $streamFactory
) {
}

public function generate(ServerRequestInterface $request): ResponseInterface
{
$passwordRules = $request->getParsedBody()['passwordRules'] ?? [];

if (is_array($passwordRules)) {
try {
$password = $this->random->generateRandomPassword($passwordRules);
return $this->createResponse([
'success' => true,
'password' => $password,
]);
} catch (InvalidPasswordRulesException $e) {
}
}

return $this->createResponse([
'success' => false,
'message' => $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:error.misconfiguredPasswordRules'),
]);
}

protected function createResponse(array $data): ResponseInterface
{
return $this->responseFactory->createResponse()
->withHeader('Content-Type', 'application/json; charset=utf-8')
->withBody($this->streamFactory->createStream((string)json_encode($data)));
}

protected function getLanguageService(): LanguageService
{
return $GLOBALS['LANG'];
}
}
80 changes: 80 additions & 0 deletions typo3/sysext/core/Classes/Crypto/Random.php
Expand Up @@ -17,11 +17,20 @@

namespace TYPO3\CMS\Core\Crypto;

use TYPO3\CMS\Core\Exception\InvalidPasswordRulesException;
use TYPO3\CMS\Core\Utility\StringUtility;

/**
* Crypto safe pseudo-random value generation
*/
class Random
{
private const DEFAULT_PASSWORD_LEGNTH = 16;
private const LOWERCASE_CHARACTERS = 'abcdefghijklmnopqrstuvwxyz';
private const UPPERCASE_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
private const SPECIAL_CHARACTERS = '!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~';
private const DIGIT_CHARACTERS = '1234567890';

/**
* Generates cryptographic secure pseudo-random bytes
*
Expand Down Expand Up @@ -55,4 +64,75 @@ public function generateRandomHexString(int $length): string
{
return substr(bin2hex($this->generateRandomBytes((int)(($length + 1) / 2))), 0, $length);
}

/**
* Generates cryptographic secure pseudo-random password based on given password rules
*
* @param array $passwordRules
* @return string
* @internal Only to be used within TYPO3. Might change in the future.
*/
public function generateRandomPassword(array $passwordRules): string
{
$password = '';
$passwordLength = (int)($passwordRules['length'] ?? self::DEFAULT_PASSWORD_LEGNTH);

if ($passwordRules['random'] ?? false) {
$password = match ((string)$passwordRules['random']) {
'hex' => $this->generateRandomHexString($passwordLength),
'base64' => $this->generateRandomBase64String($passwordLength),
default => throw new InvalidPasswordRulesException('Invalid value for special option \'random\'. Valid options are: \'hex\' and \'base64\'', 1667557901),
};
} else {
$characters = [];
$characterSets = [];
if (filter_var($passwordRules['lowerCaseCharacters'] ?? true, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
$characters = array_merge($characters, str_split(self::LOWERCASE_CHARACTERS));
$characterSets[] = self::LOWERCASE_CHARACTERS;
}
if (filter_var($passwordRules['upperCaseCharacters'] ?? true, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
$characters = array_merge($characters, str_split(self::UPPERCASE_CHARACTERS));
$characterSets[] = self::UPPERCASE_CHARACTERS;
}
if (filter_var($passwordRules['digitCharacters'] ?? true, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
$characters = array_merge($characters, str_split(self::DIGIT_CHARACTERS));
$characterSets[] = self::DIGIT_CHARACTERS;
}
if (filter_var($passwordRules['specialCharacters'] ?? false, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
$characters = array_merge($characters, str_split(self::SPECIAL_CHARACTERS));
$characterSets[] = self::SPECIAL_CHARACTERS;
}

if ($passwordLength <= 0 || $characterSets === []) {
throw new InvalidPasswordRulesException(
'Password rules are invalid. Length must be grater 0 and at least one character set must be allowed.',
1667557900
);
}

foreach ($characterSets as $characterSet) {
$password .= $characterSet[random_int(0, strlen($characterSet))];
}

$charactersCount = count($characters);
for ($i = 0; $i < $passwordLength - count($characterSets); $i++) {
$password .= $characters[random_int(0, $charactersCount)];
}

str_shuffle($password);
}

return $password;
}

/**
* Generates cryptographic secure pseudo-random base64 string
*
* @param int $length
* @return string
*/
protected function generateRandomBase64String(int $length): string
{
return substr(StringUtility::base64urlEncode($this->generateRandomBytes((int)ceil(($length / 4) * 3))), 0, $length);
}
}
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/

namespace TYPO3\CMS\Core\Exception;

use TYPO3\CMS\Core\Exception;

/**
* Exception thrown if random password can not be generated due to invalid rules
*/
class InvalidPasswordRulesException extends Exception
{
}

0 comments on commit 445912f

Please sign in to comment.