Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
feat: Allow to generate passwords for different password contexts
Signed-off-by: Ferdinand Thiessen <[email protected]>
  • Loading branch information
susnux committed Jan 30, 2025
commit 41ea4e8ea7fec18a47a276612ae4087a8fbc1ed1
15 changes: 9 additions & 6 deletions lib/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use OCP\HintException;
use OCP\Security\ISecureRandom;
use OCP\Security\PasswordContext;

class Generator {

Expand All @@ -24,29 +25,31 @@ public function __construct(

/**
* @throws HintException
* @since 3.0.0 support password context
*/
public function generate(): string {
$minLength = max($this->config->getMinLength(), 8);
public function generate(?PasswordContext $context = null): string {
$context = $context ?? PasswordContext::ACCOUNT;
$minLength = max($this->config->getMinLength($context), 8);
$length = $minLength;

$password = '';
$chars = '';

for ($i = 0; $i < self::PASSWORD_GENERATION_MAX_ROUNDS; $i++) {
if ($this->config->getEnforceUpperLowerCase()) {
if ($this->config->getEnforceUpperLowerCase($context)) {
$password .= $this->random->generate(1, ISecureRandom::CHAR_UPPER);
$password .= $this->random->generate(1, ISecureRandom::CHAR_LOWER);
$length -= 2;
$chars .= ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER;
}

if ($this->config->getEnforceNumericCharacters()) {
if ($this->config->getEnforceNumericCharacters($context)) {
$password .= $this->random->generate(1, ISecureRandom::CHAR_DIGITS);
$length -= 1;
$chars .= ISecureRandom::CHAR_DIGITS;
}

if ($this->config->getEnforceSpecialCharacters()) {
if ($this->config->getEnforceSpecialCharacters($context)) {
$password .= $this->random->generate(1, ISecureRandom::CHAR_SYMBOLS);
$length -= 1;
$chars .= ISecureRandom::CHAR_SYMBOLS;
Expand All @@ -66,7 +69,7 @@ public function generate(): string {
}

try {
$this->validator->validate($password);
$this->validator->validate($password, $context);
// Validation succeeded
return $password;
} catch (HintException $e) {
Expand Down
4 changes: 3 additions & 1 deletion lib/Listener/GenerateSecurePasswordEventListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ public function handle(Event $event): void {
return;
}

$event->setPassword($this->generator->generate());
$event->setPassword(
$this->generator->generate($event->getContext()),
);
}
}