Initial commit
This commit is contained in:
122
application/Espo/Tools/UserSecurity/Password/Checker.php
Normal file
122
application/Espo/Tools/UserSecurity/Password/Checker.php
Normal file
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2025 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password;
|
||||
|
||||
use SensitiveParameter;
|
||||
|
||||
class Checker
|
||||
{
|
||||
private const SPECIAL_CHARACTERS = "'-!\"#$%&()*,./:;?@[]^_`{|}~+<=>";
|
||||
|
||||
public function __construct(
|
||||
private ConfigProvider $configProvider,
|
||||
) {}
|
||||
|
||||
public function checkStrength(#[SensitiveParameter] string $password): bool
|
||||
{
|
||||
$minLength = $this->configProvider->getStrengthLength();
|
||||
|
||||
if ($minLength) {
|
||||
if (mb_strlen($password) < $minLength) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$requiredLetterCount = $this->configProvider->getStrengthLetterCount();
|
||||
|
||||
if ($requiredLetterCount) {
|
||||
$letterCount = 0;
|
||||
|
||||
foreach (str_split($password) as $c) {
|
||||
if (ctype_alpha($c)) {
|
||||
$letterCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($letterCount < $requiredLetterCount) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$requiredNumberCount = $this->configProvider->getStrengthNumberCount();
|
||||
|
||||
if ($requiredNumberCount) {
|
||||
$numberCount = 0;
|
||||
|
||||
foreach (str_split($password) as $c) {
|
||||
if (is_numeric($c)) {
|
||||
$numberCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($numberCount < $requiredNumberCount) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$bothCases = $this->configProvider->getStrengthBothCases();
|
||||
|
||||
if ($bothCases) {
|
||||
$ucCount = 0;
|
||||
$lcCount = 0;
|
||||
|
||||
foreach (str_split($password) as $c) {
|
||||
if (ctype_alpha($c) && $c === mb_strtoupper($c)) {
|
||||
$ucCount++;
|
||||
}
|
||||
|
||||
if (ctype_alpha($c) && $c === mb_strtolower($c)) {
|
||||
$lcCount++;
|
||||
}
|
||||
}
|
||||
if (!$ucCount || !$lcCount) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$specialCharacterCount = $this->configProvider->getStrengthSpecialCharacterCount();
|
||||
|
||||
if ($specialCharacterCount) {
|
||||
$realSpecialCharacterCount = 0;
|
||||
|
||||
foreach (str_split($password) as $c) {
|
||||
if (str_contains(self::SPECIAL_CHARACTERS, $c)) {
|
||||
$realSpecialCharacterCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($realSpecialCharacterCount < $specialCharacterCount) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2025 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password;
|
||||
|
||||
use Espo\Core\Utils\Config;
|
||||
|
||||
class ConfigProvider
|
||||
{
|
||||
|
||||
public function __construct(
|
||||
private Config $config,
|
||||
) {}
|
||||
|
||||
public function getStrengthLength(): ?int
|
||||
{
|
||||
return $this->config->get('passwordStrengthLength');
|
||||
}
|
||||
|
||||
public function getStrengthLetterCount(): ?int
|
||||
{
|
||||
return $this->config->get('passwordStrengthLetterCount');
|
||||
}
|
||||
|
||||
public function getStrengthNumberCount(): ?int
|
||||
{
|
||||
return $this->config->get('passwordStrengthNumberCount');
|
||||
}
|
||||
|
||||
public function getStrengthSpecialCharacterCount(): ?int
|
||||
{
|
||||
return $this->config->get('passwordStrengthSpecialCharacterCount');
|
||||
}
|
||||
|
||||
public function getStrengthBothCases(): bool
|
||||
{
|
||||
return (bool) $this->config->get('passwordStrengthBothCases');
|
||||
}
|
||||
|
||||
public function getGenerateLength(): ?int
|
||||
{
|
||||
return $this->config->get('passwordGenerateLength');
|
||||
}
|
||||
public function getGenerateLetterCount(): ?int
|
||||
{
|
||||
return $this->config->get('passwordGenerateLetterCount');
|
||||
}
|
||||
|
||||
public function getGenerateNumberCount(): ?int
|
||||
{
|
||||
return $this->config->get('passwordGenerateNumberCount');
|
||||
}
|
||||
}
|
||||
77
application/Espo/Tools/UserSecurity/Password/Generator.php
Normal file
77
application/Espo/Tools/UserSecurity/Password/Generator.php
Normal file
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2025 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password;
|
||||
|
||||
use Espo\Core\Utils\Util;
|
||||
|
||||
/**
|
||||
* A password generator.
|
||||
*
|
||||
* @todo Use an interface with binding.
|
||||
*/
|
||||
class Generator
|
||||
{
|
||||
public function __construct(
|
||||
private ConfigProvider $configProvider,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Generate a password.
|
||||
*/
|
||||
public function generate(): string
|
||||
{
|
||||
$length = $this->configProvider->getStrengthLength();
|
||||
$letterCount = $this->configProvider->getStrengthLetterCount();
|
||||
$numberCount = $this->configProvider->getStrengthNumberCount();
|
||||
$specialCharacterCount = $this->configProvider->getStrengthSpecialCharacterCount() ?? 0;
|
||||
|
||||
$generateLength = $this->configProvider->getGenerateLength() ?? 10;
|
||||
$generateLetterCount = $this->configProvider->getGenerateLetterCount() ?? 4;
|
||||
$generateNumberCount = $this->configProvider->getGenerateNumberCount() ?? 2;
|
||||
|
||||
$length = is_null($length) ? $generateLength : $length;
|
||||
$letterCount = is_null($letterCount) ? $generateLetterCount : $letterCount;
|
||||
$numberCount = is_null($numberCount) ? $generateNumberCount : $numberCount;
|
||||
|
||||
if ($length < $generateLength) {
|
||||
$length = $generateLength;
|
||||
}
|
||||
|
||||
if ($letterCount < $generateLetterCount) {
|
||||
$letterCount = $generateLetterCount;
|
||||
}
|
||||
|
||||
if ($numberCount < $generateNumberCount) {
|
||||
$numberCount = $generateNumberCount;
|
||||
}
|
||||
|
||||
return Util::generatePassword($length, $letterCount, $numberCount, true, $specialCharacterCount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2025 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password\Jobs;
|
||||
|
||||
use Espo\Core\Job\Job;
|
||||
use Espo\Core\Job\Job\Data;
|
||||
use Espo\Entities\PasswordChangeRequest;
|
||||
use Espo\ORM\EntityManager;
|
||||
use RuntimeException;
|
||||
|
||||
class RemoveRecoveryRequest implements Job
|
||||
{
|
||||
private EntityManager $entityManager;
|
||||
|
||||
public function __construct(EntityManager $entityManager)
|
||||
{
|
||||
$this->entityManager = $entityManager;
|
||||
}
|
||||
|
||||
public function run(Data $data): void
|
||||
{
|
||||
$id = $data->get('id');
|
||||
|
||||
if (!$id) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
|
||||
$entity = $this->entityManager->getEntityById(PasswordChangeRequest::ENTITY_TYPE, $id);
|
||||
|
||||
if (!$entity) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->entityManager->removeEntity($entity);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2025 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password\Jobs;
|
||||
|
||||
use Espo\Core\Mail\Exceptions\SendingError;
|
||||
use Espo\Entities\User;
|
||||
use Espo\Core\Job\Job;
|
||||
use Espo\Core\Job\Job\Data;
|
||||
use Espo\Core\Exceptions\Error;
|
||||
use Espo\ORM\EntityManager;
|
||||
use Espo\Tools\UserSecurity\Password\Service as PasswordService;
|
||||
|
||||
class SendAccessInfo implements Job
|
||||
{
|
||||
private EntityManager $entityManager;
|
||||
private PasswordService $passwordService;
|
||||
|
||||
public function __construct(EntityManager $entityManager, PasswordService $passwordService)
|
||||
{
|
||||
$this->entityManager = $entityManager;
|
||||
$this->passwordService = $passwordService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws SendingError
|
||||
* @throws Error
|
||||
*/
|
||||
public function run(Data $data): void
|
||||
{
|
||||
$userId = $data->getTargetId();
|
||||
|
||||
if (!$userId) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
/** @var ?User $user */
|
||||
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $userId);
|
||||
|
||||
if (!$user) {
|
||||
throw new Error("User '{$userId}' not found.");
|
||||
}
|
||||
|
||||
$this->passwordService->sendAccessInfoForNewUser($user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2025 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password\Recovery;
|
||||
|
||||
use Espo\Core\Exceptions\Forbidden;
|
||||
use Espo\Core\Utils\Config;
|
||||
use Espo\Entities\Portal;
|
||||
use Espo\ORM\EntityManager;
|
||||
|
||||
class UrlValidator
|
||||
{
|
||||
public function __construct(
|
||||
private Config $config,
|
||||
private EntityManager $entityManager
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws Forbidden
|
||||
*/
|
||||
public function validate(string $url): void
|
||||
{
|
||||
$siteUrl = rtrim($this->config->get('siteUrl') ?? '', '/');
|
||||
|
||||
if (UrlValidatorUtil::validate($url, $siteUrl)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var iterable<Portal> $portals */
|
||||
$portals = $this->entityManager
|
||||
->getRDBRepositoryByClass(Portal::class)
|
||||
->find();
|
||||
|
||||
foreach ($portals as $portal) {
|
||||
$siteUrl = rtrim($portal->getUrl() ?? '', '/');
|
||||
|
||||
if (UrlValidatorUtil::validate($url, $siteUrl)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Forbidden("URL does not match Site URL.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2026 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password\Recovery;
|
||||
|
||||
use const FILTER_VALIDATE_URL;
|
||||
use const PHP_URL_HOST;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
class UrlValidatorUtil
|
||||
{
|
||||
public static function validate(string $url, string $siteUrl): bool
|
||||
{
|
||||
$host = parse_url($url, PHP_URL_HOST);
|
||||
$siteHost = parse_url($siteUrl, PHP_URL_HOST);
|
||||
|
||||
if ($host !== $siteHost) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!filter_var($url, FILTER_VALIDATE_URL)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!str_starts_with($url, $siteUrl)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
568
application/Espo/Tools/UserSecurity/Password/RecoveryService.php
Normal file
568
application/Espo/Tools/UserSecurity/Password/RecoveryService.php
Normal file
@@ -0,0 +1,568 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2025 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password;
|
||||
|
||||
use Espo\Core\Authentication\Ldap\LdapLogin;
|
||||
use Espo\Core\Exceptions\Forbidden;
|
||||
use Espo\Core\Exceptions\NotFound;
|
||||
use Espo\Core\Exceptions\Error;
|
||||
use Espo\Core\ApplicationState;
|
||||
use Espo\Core\Authentication\Util\MethodProvider as AuthenticationMethodProvider;
|
||||
use Espo\Core\Exceptions\ForbiddenSilent;
|
||||
use Espo\Core\Job\JobSchedulerFactory;
|
||||
use Espo\Core\Mail\Exceptions\NoSmtp;
|
||||
use Espo\Core\Mail\Exceptions\SendingError;
|
||||
use Espo\Core\Mail\SmtpParams;
|
||||
use Espo\Core\Utils\Config\ApplicationConfig;
|
||||
use Espo\Core\Utils\Util;
|
||||
use Espo\Entities\Email;
|
||||
use Espo\Entities\SystemData;
|
||||
use Espo\Entities\User;
|
||||
use Espo\Entities\PasswordChangeRequest;
|
||||
use Espo\Entities\Portal;
|
||||
use Espo\Repositories\Portal as PortalRepository;
|
||||
use Espo\Core\Field\DateTime;
|
||||
use Espo\Core\Authentication\Logins\Espo as EspoLogin;
|
||||
use Espo\Core\Htmlizer\HtmlizerFactory as HtmlizerFactory;
|
||||
use Espo\Core\Job\QueueName;
|
||||
use Espo\Core\Mail\EmailSender;
|
||||
use Espo\Core\ORM\EntityManager;
|
||||
use Espo\Core\Utils\Config;
|
||||
use Espo\Core\Utils\Log;
|
||||
use Espo\Core\Utils\TemplateFileManager;
|
||||
use Espo\Tools\UserSecurity\Password\Jobs\RemoveRecoveryRequest;
|
||||
use Espo\Tools\UserSecurity\Password\Recovery\UrlValidator;
|
||||
|
||||
class RecoveryService
|
||||
{
|
||||
/** Milliseconds. */
|
||||
private const REQUEST_DELAY = 3000;
|
||||
private const REQUEST_LIFETIME = '3 hours';
|
||||
private const NEW_USER_REQUEST_LIFETIME = '2 days';
|
||||
private const EXISTING_USER_REQUEST_LIFETIME = '2 days';
|
||||
private const INTERNAL_SMTP_INTERVAL_PERIOD = '1 hour';
|
||||
|
||||
public function __construct(
|
||||
private EntityManager $entityManager,
|
||||
private Config $config,
|
||||
private EmailSender $emailSender,
|
||||
private HtmlizerFactory $htmlizerFactory,
|
||||
private TemplateFileManager $templateFileManager,
|
||||
private Log $log,
|
||||
private JobSchedulerFactory $jobSchedulerFactory,
|
||||
private ApplicationState $applicationState,
|
||||
private AuthenticationMethodProvider $authenticationMethodProvider,
|
||||
private UrlValidator $urlValidator,
|
||||
private ApplicationConfig $applicationConfig,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws Forbidden
|
||||
* @throws Error
|
||||
* @throws NotFound
|
||||
*/
|
||||
public function getRequest(string $id): PasswordChangeRequest
|
||||
{
|
||||
$config = $this->config;
|
||||
|
||||
if ($config->get('passwordRecoveryDisabled')) {
|
||||
throw new Forbidden("Password recovery: Disabled.");
|
||||
}
|
||||
|
||||
$request = $this->entityManager
|
||||
->getRDBRepositoryByClass(PasswordChangeRequest::class)
|
||||
->where(['requestId' => $id])
|
||||
->findOne();
|
||||
|
||||
if (!$request) {
|
||||
throw new NotFound("Password recovery: Request not found by id.");
|
||||
}
|
||||
|
||||
$userId = $request->get('userId');
|
||||
|
||||
if (!$userId) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
public function removeRequest(string $id): void
|
||||
{
|
||||
$request = $this->entityManager
|
||||
->getRDBRepositoryByClass(PasswordChangeRequest::class)
|
||||
->where(['requestId' => $id])
|
||||
->findOne();
|
||||
|
||||
if ($request) {
|
||||
$this->entityManager->removeEntity($request);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Forbidden
|
||||
* @throws NotFound
|
||||
* @throws Error
|
||||
*/
|
||||
public function request(string $emailAddress, string $userName, ?string $url): bool
|
||||
{
|
||||
$config = $this->config;
|
||||
|
||||
$noExposure = $config->get('passwordRecoveryNoExposure') ?? false;
|
||||
|
||||
if ($config->get('passwordRecoveryDisabled')) {
|
||||
throw new Forbidden("Password recovery: Disabled.");
|
||||
}
|
||||
|
||||
if ($url) {
|
||||
$this->urlValidator->validate($url);
|
||||
}
|
||||
|
||||
$user = $this->entityManager
|
||||
->getRDBRepositoryByClass(User::class)
|
||||
->where([
|
||||
'userName' => $userName,
|
||||
'emailAddress' => $emailAddress,
|
||||
])
|
||||
->findOne();
|
||||
|
||||
if (!$user) {
|
||||
$this->fail("User $emailAddress not found.", 404);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$userId = $user->getId();
|
||||
|
||||
if (!$user->isActive()) {
|
||||
$this->fail("User $userId is not active.");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
!$user->isAdmin() &&
|
||||
$this->authenticationMethodProvider->get() !== EspoLogin::NAME &&
|
||||
!$this->isPortalLdapDisabled()
|
||||
) {
|
||||
$this->fail("User $userId is not allowed, authentication method is not 'Espo'.");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($user->isApi() || $user->isSystem() || $user->isSuperAdmin()) {
|
||||
$this->fail("User $userId is not allowed.");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($config->get('passwordRecoveryForInternalUsersDisabled')) {
|
||||
if ($user->isRegular() || $user->isAdmin()) {
|
||||
$this->fail("User $userId is not allowed, disabled for internal users.");
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if ($config->get('passwordRecoveryForAdminDisabled')) {
|
||||
if ($user->isAdmin()) {
|
||||
$this->fail("User $userId is not allowed, disabled for admin users.");
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->applicationState->isPortal()) {
|
||||
if (!$user->isPortal()) {
|
||||
$this->fail("User $userId is not allowed, as it's not portal user.");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$portalId = $this->applicationState->getPortalId();
|
||||
|
||||
if (!$user->getPortals()->hasId($portalId)) {
|
||||
$this->fail("User $userId is from another portal.");
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$existingRequest = $this->entityManager
|
||||
->getRDBRepositoryByClass(PasswordChangeRequest::class)
|
||||
->where(['userId' => $user->getId()])
|
||||
->findOne();
|
||||
|
||||
if ($existingRequest) {
|
||||
if (!$noExposure) {
|
||||
throw new ForbiddenSilent('Already-Sent');
|
||||
}
|
||||
|
||||
$this->fail("Denied for $userId, already sent.");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$request = $this->createRequestNoSave($user, $url);
|
||||
|
||||
$microtime = microtime(true);
|
||||
|
||||
try {
|
||||
$this->send($request->getRequestId(), $emailAddress, $user);
|
||||
} catch (SendingError $e) {
|
||||
$message = "Email sending error. " . $e->getMessage();
|
||||
|
||||
$this->log->error($message);
|
||||
|
||||
throw new Error("Email sending error.");
|
||||
}
|
||||
|
||||
$this->entityManager->saveEntity($request);
|
||||
|
||||
$lifetime = $config->get('passwordRecoveryRequestLifetime') ?? self::REQUEST_LIFETIME;
|
||||
|
||||
$this->createCleanupRequestJob($request->getId(), $lifetime);
|
||||
|
||||
$timeDiff = $this->getDelay() - floor((microtime(true) - $microtime) / 1000);
|
||||
|
||||
if ($noExposure && $timeDiff > 0) {
|
||||
$this->delay((int) $timeDiff);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Error
|
||||
*/
|
||||
private function createRequestNoSave(User $user, ?string $url = null): PasswordChangeRequest
|
||||
{
|
||||
$this->checkUser($user);
|
||||
|
||||
$entity = $this->entityManager->getRDBRepositoryByClass(PasswordChangeRequest::class)->getNew();
|
||||
|
||||
$entity->set([
|
||||
'userId' => $user->getId(),
|
||||
'requestId' => Util::generateCryptId(),
|
||||
'url' => $url,
|
||||
]);
|
||||
|
||||
return $entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Error
|
||||
*/
|
||||
public function createRequestForNewUser(User $user, ?string $url = null): PasswordChangeRequest
|
||||
{
|
||||
$this->checkUser($user);
|
||||
|
||||
$entity = $this->createRequestNoSave($user, $url);
|
||||
|
||||
$this->entityManager->saveEntity($entity);
|
||||
|
||||
$lifetime = $this->config->get('passwordChangeRequestNewUserLifetime') ?? self::NEW_USER_REQUEST_LIFETIME;
|
||||
|
||||
$this->createCleanupRequestJob($entity->getId(), $lifetime);
|
||||
|
||||
return $entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Error
|
||||
* @throws Forbidden
|
||||
*/
|
||||
public function createAndSendRequestForExistingUser(User $user, ?string $url = null): PasswordChangeRequest
|
||||
{
|
||||
$this->checkUser($user);
|
||||
|
||||
if (!$user->getEmailAddressGroup()->getPrimary()) {
|
||||
throw new Error("No email address.");
|
||||
}
|
||||
|
||||
$emailAddress = $user->getEmailAddressGroup()->getPrimary()->getAddress();
|
||||
|
||||
$entity = $this->createRequestNoSave($user, $url);
|
||||
|
||||
$this->entityManager->saveEntity($entity);
|
||||
|
||||
$lifetime = $this->config->get('passwordChangeRequestExistingUserLifetime') ??
|
||||
self::EXISTING_USER_REQUEST_LIFETIME;
|
||||
|
||||
$this->createCleanupRequestJob($entity->getId(), $lifetime);
|
||||
|
||||
try {
|
||||
$this->send($entity->getRequestId(), $emailAddress, $user);
|
||||
} catch (SendingError $e) {
|
||||
$this->log->error("Email sending error. " . $e->getMessage());
|
||||
|
||||
throw new Error("Email sending error.");
|
||||
}
|
||||
|
||||
return $entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Error
|
||||
*/
|
||||
private function checkUser(User $user): void
|
||||
{
|
||||
if (
|
||||
!$user->isActive() ||
|
||||
!(
|
||||
$user->isAdmin() ||
|
||||
$user->isRegular() ||
|
||||
$user->isPortal()
|
||||
)
|
||||
) {
|
||||
throw new Error("User is not allowed for password change request.");
|
||||
}
|
||||
}
|
||||
|
||||
private function createCleanupRequestJob(string $id, string $lifetime): void
|
||||
{
|
||||
$this->jobSchedulerFactory
|
||||
->create()
|
||||
->setClassName(RemoveRecoveryRequest::class)
|
||||
->setData(['id' => $id])
|
||||
->setTime(
|
||||
DateTime::createNow()
|
||||
->modify('+' . $lifetime)
|
||||
->toDateTime()
|
||||
)
|
||||
->setQueue(QueueName::Q1)
|
||||
->schedule();
|
||||
}
|
||||
|
||||
private function getDelay(): int
|
||||
{
|
||||
return $this->config->get('passwordRecoveryRequestDelay') ?? self::REQUEST_DELAY;
|
||||
}
|
||||
|
||||
private function delay(?int $delay = null): void
|
||||
{
|
||||
if ($delay === null) {
|
||||
$delay = $this->getDelay();
|
||||
}
|
||||
|
||||
usleep($delay * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Error
|
||||
* @throws SendingError
|
||||
* @throws Forbidden
|
||||
*/
|
||||
private function send(string $requestId, string $emailAddress, User $user): void
|
||||
{
|
||||
if (!$emailAddress) {
|
||||
return;
|
||||
}
|
||||
|
||||
$email = $this->entityManager->getRDBRepositoryByClass(Email::class)->getNew();
|
||||
|
||||
if (!$this->emailSender->hasSystemSmtp() && !$this->config->get('internalSmtpServer')) {
|
||||
throw new Error("Password recovery: SMTP credentials are not defined.");
|
||||
}
|
||||
|
||||
if (!$this->emailSender->hasSystemSmtp()) {
|
||||
$this->checkIntervalForInternalSmtp();
|
||||
}
|
||||
|
||||
$sender = $this->emailSender->create();
|
||||
|
||||
$subjectTpl = $this->templateFileManager->getTemplate('passwordChangeLink', 'subject', 'User');
|
||||
$bodyTpl = $this->templateFileManager->getTemplate('passwordChangeLink', 'body', 'User');
|
||||
|
||||
$siteUrl = $this->applicationConfig->getSiteUrl();
|
||||
|
||||
if ($user->isPortal()) {
|
||||
$portal = $this->entityManager
|
||||
->getRDBRepositoryByClass(Portal::class)
|
||||
->distinct()
|
||||
->join('users')
|
||||
->where([
|
||||
'isActive' => true,
|
||||
'users.id' => $user->getId(),
|
||||
])
|
||||
->findOne();
|
||||
|
||||
if (!$portal) {
|
||||
throw new Error("Portal user does not belong to any portal.");
|
||||
}
|
||||
|
||||
$this->getPortalRepository()->loadUrlField($portal);
|
||||
|
||||
$siteUrl = $portal->getUrl();
|
||||
|
||||
if (!$siteUrl) {
|
||||
throw new Error("Portal does not have URL.");
|
||||
}
|
||||
}
|
||||
|
||||
$data = [];
|
||||
|
||||
$link = $siteUrl . '?entryPoint=changePassword&id=' . $requestId;
|
||||
|
||||
$data['link'] = $link;
|
||||
|
||||
$htmlizer = $this->htmlizerFactory->create(true);
|
||||
|
||||
$subject = $htmlizer->render($user, $subjectTpl, null, $data, true);
|
||||
$body = $htmlizer->render($user, $bodyTpl, null, $data, true);
|
||||
|
||||
$email
|
||||
->setSubject($subject)
|
||||
->setBody($body)
|
||||
->addToAddress($emailAddress);
|
||||
|
||||
$email->set([
|
||||
'isSystem' => true,
|
||||
]);
|
||||
|
||||
if (!$this->emailSender->hasSystemSmtp()) {
|
||||
$server = $this->config->get('internalSmtpServer');
|
||||
$port = $this->config->get('internalSmtpPort');
|
||||
|
||||
if (!$server || $port === null) {
|
||||
throw new NoSmtp("No internal SMTP");
|
||||
}
|
||||
|
||||
$smtpParams = SmtpParams::create($server, $port)
|
||||
->withAuth($this->config->get('internalSmtpAuth'))
|
||||
->withUsername($this->config->get('internalSmtpUsername'))
|
||||
->withPassword($this->config->get('internalSmtpPassword'))
|
||||
->withSecurity($this->config->get('internalSmtpSecurity'))
|
||||
->withFromName(
|
||||
$this->config->get('outboundEmailFromName')
|
||||
);
|
||||
|
||||
$sender->withSmtpParams($smtpParams);
|
||||
}
|
||||
|
||||
$sender->send($email);
|
||||
|
||||
$this->lastPasswordRecoveryDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Forbidden
|
||||
* @throws Error
|
||||
* @throws NotFound
|
||||
*/
|
||||
private function fail(?string $msg = null, int $errorCode = 403): void
|
||||
{
|
||||
$noExposure = $this->config->get('passwordRecoveryNoExposure') ?? false;
|
||||
|
||||
if ($msg) {
|
||||
$msg = 'Password recovery: ' . $msg;
|
||||
|
||||
$this->log->warning($msg);
|
||||
}
|
||||
|
||||
if (!$noExposure) {
|
||||
if ($errorCode === 403) {
|
||||
throw new Forbidden();
|
||||
}
|
||||
|
||||
if ($errorCode === 404) {
|
||||
throw new NotFound();
|
||||
}
|
||||
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
$this->delay();
|
||||
}
|
||||
|
||||
private function getPortalRepository(): PortalRepository
|
||||
{
|
||||
/** @var PortalRepository */
|
||||
return $this->entityManager->getRDBRepository(Portal::ENTITY_TYPE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Forbidden
|
||||
*/
|
||||
private function checkIntervalForInternalSmtp(): void
|
||||
{
|
||||
/** @var string $period */
|
||||
$period = $this->config->get('passwordRecoveryInternalIntervalPeriod') ??
|
||||
self::INTERNAL_SMTP_INTERVAL_PERIOD;
|
||||
|
||||
$data = $this->entityManager->getEntityById(SystemData::ENTITY_TYPE, SystemData::ONLY_ID);
|
||||
|
||||
if (!$data) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var ?string $lastPasswordRecoveryDate */
|
||||
$lastPasswordRecoveryDate = $data->get('lastPasswordRecoveryDate');
|
||||
|
||||
if (!$lastPasswordRecoveryDate) {
|
||||
return;
|
||||
}
|
||||
|
||||
$notPassed = DateTime::fromString($lastPasswordRecoveryDate)
|
||||
->modify('+' . $period)
|
||||
->isGreaterThan(DateTime::createNow());
|
||||
|
||||
if (!$notPassed) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw Forbidden::createWithBody(
|
||||
'Internal password recovery attempt interval failure.',
|
||||
Error\Body::create()
|
||||
->withMessageTranslation('attemptIntervalFailure')
|
||||
->encode()
|
||||
);
|
||||
}
|
||||
|
||||
private function lastPasswordRecoveryDate(): void
|
||||
{
|
||||
$data = $this->entityManager->getEntityById(SystemData::ENTITY_TYPE, SystemData::ONLY_ID);
|
||||
|
||||
if (!$data) {
|
||||
return;
|
||||
}
|
||||
|
||||
$data->set('lastPasswordRecoveryDate', DateTime::createNow()->toString());
|
||||
|
||||
$this->entityManager->saveEntity($data);
|
||||
}
|
||||
|
||||
private function isPortalLdapDisabled(): bool
|
||||
{
|
||||
return $this->applicationState->isPortal() &&
|
||||
$this->authenticationMethodProvider->get() === LdapLogin::NAME &&
|
||||
!$this->config->get('ldapPortalUserLdapAuth');
|
||||
}
|
||||
}
|
||||
217
application/Espo/Tools/UserSecurity/Password/Sender.php
Normal file
217
application/Espo/Tools/UserSecurity/Password/Sender.php
Normal file
@@ -0,0 +1,217 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2025 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password;
|
||||
|
||||
use Espo\Core\Exceptions\Error;
|
||||
use Espo\Core\Htmlizer\HtmlizerFactory;
|
||||
use Espo\Core\Mail\EmailSender;
|
||||
use Espo\Core\Mail\Exceptions\NoSmtp;
|
||||
use Espo\Core\Mail\Exceptions\SendingError;
|
||||
use Espo\Core\Mail\Sender as EmailSenderSender;
|
||||
use Espo\Core\Utils\Config\ApplicationConfig;
|
||||
use Espo\Core\Utils\TemplateFileManager;
|
||||
use Espo\Entities\Email;
|
||||
use Espo\Entities\PasswordChangeRequest;
|
||||
use Espo\Entities\Portal;
|
||||
use Espo\Entities\User;
|
||||
use Espo\ORM\EntityManager;
|
||||
use Espo\Repositories\Portal as PortalRepository;
|
||||
|
||||
class Sender
|
||||
{
|
||||
public function __construct(
|
||||
private EmailSender $emailSender,
|
||||
private EntityManager $entityManager,
|
||||
private HtmlizerFactory $htmlizerFactory,
|
||||
private TemplateFileManager $templateFileManager,
|
||||
private ApplicationConfig $applicationConfig,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Send access info for a new user.
|
||||
*
|
||||
* @throws Error
|
||||
* @throws NoSmtp
|
||||
* @throws SendingError
|
||||
*/
|
||||
public function sendAccessInfo(User $user, PasswordChangeRequest $request): void
|
||||
{
|
||||
$emailAddress = $user->getEmailAddress();
|
||||
|
||||
if (!$emailAddress) {
|
||||
throw new Error("No email address.");
|
||||
}
|
||||
|
||||
[$subjectTpl, $bodyTpl, $data] = $this->getAccessInfoTemplateData($user, null, $request);
|
||||
|
||||
if ($data === null) {
|
||||
throw new Error("Could not send access info.");
|
||||
}
|
||||
|
||||
/** @var Email $email */
|
||||
$email = $this->entityManager->getNewEntity(Email::ENTITY_TYPE);
|
||||
|
||||
$htmlizer = $this->htmlizerFactory->createNoAcl();
|
||||
|
||||
$subject = $htmlizer->render($user, $subjectTpl ?? '', null, $data, true);
|
||||
$body = $htmlizer->render($user, $bodyTpl ?? '', null, $data, true);
|
||||
|
||||
$email
|
||||
->addToAddress($emailAddress)
|
||||
->setSubject($subject)
|
||||
->setBody($body);
|
||||
|
||||
$this->createSender()
|
||||
->withAddedHeader('Auto-Submitted', 'auto-generated')
|
||||
->send($email);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a plain password in email.
|
||||
*
|
||||
* @throws SendingError
|
||||
*/
|
||||
public function sendPassword(User $user, string $password): void
|
||||
{
|
||||
$emailAddress = $user->getEmailAddress();
|
||||
|
||||
if (empty($emailAddress)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var Email $email */
|
||||
$email = $this->entityManager->getNewEntity(Email::ENTITY_TYPE);
|
||||
|
||||
if (!$this->isSmtpConfigured()) {
|
||||
return;
|
||||
}
|
||||
|
||||
[$subjectTpl, $bodyTpl, $data] = $this->getAccessInfoTemplateData($user, $password);
|
||||
|
||||
if ($data === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$htmlizer = $this->htmlizerFactory->createNoAcl();
|
||||
|
||||
$subject = $htmlizer->render($user, $subjectTpl ?? '', null, $data, true);
|
||||
$body = $htmlizer->render($user, $bodyTpl ?? '', null, $data, true);
|
||||
|
||||
$email
|
||||
->setSubject($subject)
|
||||
->setBody($body)
|
||||
->addToAddress($emailAddress);
|
||||
|
||||
$this->createSender()
|
||||
->withAddedHeader('Auto-Submitted', 'auto-generated')
|
||||
->send($email);
|
||||
}
|
||||
|
||||
private function createSender(): EmailSenderSender
|
||||
{
|
||||
return $this->emailSender->create();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{?string, ?string, ?array<string, mixed>}
|
||||
*/
|
||||
private function getAccessInfoTemplateData(
|
||||
User $user,
|
||||
?string $password = null,
|
||||
?PasswordChangeRequest $passwordChangeRequest = null
|
||||
): array {
|
||||
|
||||
$data = [];
|
||||
|
||||
if ($password !== null) {
|
||||
$data['password'] = $password;
|
||||
}
|
||||
|
||||
$urlSuffix = '';
|
||||
|
||||
if ($passwordChangeRequest !== null) {
|
||||
$urlSuffix = '?entryPoint=changePassword&id=' . $passwordChangeRequest->getRequestId();
|
||||
}
|
||||
|
||||
$siteUrl = $this->applicationConfig->getSiteUrl() . '/' . $urlSuffix;
|
||||
|
||||
if ($user->isPortal()) {
|
||||
$subjectTpl = $this->templateFileManager
|
||||
->getTemplate('accessInfoPortal', 'subject', User::ENTITY_TYPE);
|
||||
$bodyTpl = $this->templateFileManager
|
||||
->getTemplate('accessInfoPortal', 'body', User::ENTITY_TYPE);
|
||||
|
||||
$urlList = [];
|
||||
|
||||
$portalList = $this->entityManager
|
||||
->getRDBRepositoryByClass(Portal::class)
|
||||
->distinct()
|
||||
->join('users')
|
||||
->where([
|
||||
'isActive' => true,
|
||||
'users.id' => $user->getId(),
|
||||
])
|
||||
->find();
|
||||
|
||||
foreach ($portalList as $portal) {
|
||||
/** @var Portal $portal */
|
||||
$this->getPortalRepository()->loadUrlField($portal);
|
||||
|
||||
$urlList[] = $portal->getUrl() . $urlSuffix;
|
||||
}
|
||||
|
||||
if (count($urlList) === 0) {
|
||||
return [null, null, null];
|
||||
}
|
||||
|
||||
$data['siteUrlList'] = $urlList;
|
||||
|
||||
return [$subjectTpl, $bodyTpl, $data];
|
||||
}
|
||||
|
||||
$subjectTpl = $this->templateFileManager->getTemplate('accessInfo', 'subject', User::ENTITY_TYPE);
|
||||
$bodyTpl = $this->templateFileManager->getTemplate('accessInfo', 'body', User::ENTITY_TYPE);
|
||||
|
||||
$data['siteUrl'] = $siteUrl;
|
||||
|
||||
return [$subjectTpl, $bodyTpl, $data];
|
||||
}
|
||||
|
||||
private function isSmtpConfigured(): bool
|
||||
{
|
||||
return $this->emailSender->hasSystemSmtp();
|
||||
}
|
||||
|
||||
private function getPortalRepository(): PortalRepository
|
||||
{
|
||||
/** @var PortalRepository */
|
||||
return $this->entityManager->getRDBRepository(Portal::ENTITY_TYPE);
|
||||
}
|
||||
}
|
||||
333
application/Espo/Tools/UserSecurity/Password/Service.php
Normal file
333
application/Espo/Tools/UserSecurity/Password/Service.php
Normal file
@@ -0,0 +1,333 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2025 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace Espo\Tools\UserSecurity\Password;
|
||||
|
||||
use Espo\Core\ApplicationState;
|
||||
use Espo\Core\Authentication\Ldap\LdapLogin;
|
||||
use Espo\Core\Authentication\Logins\Espo;
|
||||
use Espo\Core\Authentication\Util\MethodProvider as AuthenticationMethodProvider;
|
||||
use Espo\Core\Exceptions\Error;
|
||||
use Espo\Core\Exceptions\Forbidden;
|
||||
use Espo\Core\Exceptions\NotFound;
|
||||
use Espo\Core\FieldValidation\FieldValidationManager;
|
||||
use Espo\Core\Mail\EmailSender;
|
||||
use Espo\Core\Mail\Exceptions\SendingError;
|
||||
use Espo\Core\ORM\Repository\Option\SaveOption;
|
||||
use Espo\Core\Record\ServiceContainer;
|
||||
use Espo\Core\Utils\Config;
|
||||
use Espo\Core\Utils\PasswordHash;
|
||||
use Espo\Entities\User;
|
||||
use Espo\ORM\EntityManager;
|
||||
use SensitiveParameter;
|
||||
|
||||
class Service
|
||||
{
|
||||
public function __construct(
|
||||
private User $user,
|
||||
private ServiceContainer $serviceContainer,
|
||||
private EmailSender $emailSender,
|
||||
private Config $config,
|
||||
private Generator $generator,
|
||||
private Sender $sender,
|
||||
private PasswordHash $passwordHash,
|
||||
private EntityManager $entityManager,
|
||||
private RecoveryService $recovery,
|
||||
private FieldValidationManager $fieldValidationManager,
|
||||
private Checker $checker,
|
||||
private AuthenticationMethodProvider $authenticationMethodProvider,
|
||||
private ApplicationState $applicationState,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Create and send a password recovery link in an email. Only for admin.
|
||||
*
|
||||
* @throws Forbidden
|
||||
* @throws NotFound
|
||||
* @throws Error
|
||||
*/
|
||||
public function createAndSendPasswordRecovery(string $id): void
|
||||
{
|
||||
if (!$this->user->isAdmin()) {
|
||||
throw new Forbidden();
|
||||
}
|
||||
|
||||
/** @var ?User $user */
|
||||
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $id);
|
||||
|
||||
if (!$user) {
|
||||
throw new NotFound();
|
||||
}
|
||||
|
||||
if (!$user->isActive()) {
|
||||
throw new Forbidden("User is not active.");
|
||||
}
|
||||
|
||||
if (
|
||||
!$user->isRegular() &&
|
||||
!$user->isAdmin() &&
|
||||
!$user->isPortal()
|
||||
) {
|
||||
throw new Forbidden();
|
||||
}
|
||||
|
||||
$this->recovery->createAndSendRequestForExistingUser($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change a password by a recovery request.
|
||||
*
|
||||
* @param string $requestId A request ID.
|
||||
* @param string $password A new password.
|
||||
*
|
||||
* @return ?string A URL to suggest to a user.
|
||||
* @throws Error
|
||||
* @throws Forbidden
|
||||
* @throws NotFound
|
||||
*/
|
||||
public function changePasswordByRecovery(string $requestId, #[SensitiveParameter] string $password): ?string
|
||||
{
|
||||
$request = $this->recovery->getRequest($requestId);
|
||||
|
||||
$this->changePassword($request->getUserId(), $password);
|
||||
$this->recovery->removeRequest($requestId);
|
||||
|
||||
return $request->getUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
* Change a password with a current password check.
|
||||
*
|
||||
* @throws Forbidden
|
||||
* @throws NotFound
|
||||
* @throws Error
|
||||
*/
|
||||
public function changePasswordWithCheck(
|
||||
string $userId,
|
||||
#[SensitiveParameter] string $password,
|
||||
#[SensitiveParameter] string $currentPassword
|
||||
): void {
|
||||
|
||||
$this->changePasswordInternal($userId, $password, true, $currentPassword);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change a password.
|
||||
*
|
||||
* @throws Forbidden
|
||||
* @throws NotFound
|
||||
* @throws Error
|
||||
*/
|
||||
private function changePassword(string $userId, #[SensitiveParameter] string $password): void
|
||||
{
|
||||
$this->changePasswordInternal($userId, $password);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Forbidden
|
||||
* @throws Error
|
||||
* @throws NotFound
|
||||
*/
|
||||
private function changePasswordInternal(
|
||||
string $userId,
|
||||
#[SensitiveParameter] string $password,
|
||||
bool $checkCurrentPassword = false,
|
||||
#[SensitiveParameter] ?string $currentPassword = null
|
||||
): void {
|
||||
|
||||
/** @var ?User $user */
|
||||
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $userId);
|
||||
|
||||
if (!$user) {
|
||||
throw new NotFound();
|
||||
}
|
||||
|
||||
if (
|
||||
$user->isSuperAdmin() &&
|
||||
!$this->user->isSuperAdmin()
|
||||
) {
|
||||
throw new Forbidden();
|
||||
}
|
||||
|
||||
$authenticationMethod = $this->authenticationMethodProvider->get();
|
||||
|
||||
if (
|
||||
!$user->isAdmin() &&
|
||||
$authenticationMethod !== Espo::NAME &&
|
||||
!$this->isPortalLdapDisabled()
|
||||
) {
|
||||
throw new Forbidden("Authentication method is not `Espo`.");
|
||||
}
|
||||
|
||||
if (empty($password)) {
|
||||
throw new Error("Password can't be empty.");
|
||||
}
|
||||
|
||||
if ($checkCurrentPassword) {
|
||||
$userFound = $this->entityManager
|
||||
->getRDBRepositoryByClass(User::class)
|
||||
->getById($user->getId());
|
||||
|
||||
if (!$userFound) {
|
||||
throw new NotFound("User not found");
|
||||
}
|
||||
|
||||
if (!$this->passwordHash->verify($currentPassword ?? '', $userFound->getPassword())) {
|
||||
throw new Forbidden("Wrong password.");
|
||||
}
|
||||
}
|
||||
|
||||
if (!$this->checker->checkStrength($password)) {
|
||||
throw new Forbidden("Password is weak.");
|
||||
}
|
||||
|
||||
$validLength = $this->fieldValidationManager->check(
|
||||
$user,
|
||||
'password',
|
||||
'maxLength',
|
||||
(object) ['password' => $password]
|
||||
);
|
||||
|
||||
if (!$validLength) {
|
||||
throw new Forbidden("Password exceeds max length.");
|
||||
}
|
||||
|
||||
$user->set('password', $this->passwordHash->hash($password));
|
||||
|
||||
$this->entityManager->saveEntity($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send access info for a new user.
|
||||
*
|
||||
* @throws Error
|
||||
* @throws SendingError
|
||||
*/
|
||||
public function sendAccessInfoForNewUser(User $user): void
|
||||
{
|
||||
$emailAddress = $user->getEmailAddress();
|
||||
|
||||
if ($emailAddress === null) {
|
||||
throw new Error("Can't send access info for user '{$user->getId()}' w/o email address.");
|
||||
}
|
||||
|
||||
if (!$this->isSmtpConfigured()) {
|
||||
throw new Error("Can't send access info. SMTP is not configured.");
|
||||
}
|
||||
|
||||
$stubPassword = $this->generator->generate();
|
||||
|
||||
$this->savePasswordSilent($user, $stubPassword);
|
||||
|
||||
$request = $this->recovery->createRequestForNewUser($user);
|
||||
|
||||
$this->sender->sendAccessInfo($user, $request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new password and send it in an email. Only for admin.
|
||||
*
|
||||
* @throws Forbidden
|
||||
* @throws NotFound
|
||||
* @throws Error
|
||||
*/
|
||||
public function generateAndSendNewPasswordForUser(string $id): void
|
||||
{
|
||||
if (!$this->user->isAdmin()) {
|
||||
throw new Forbidden();
|
||||
}
|
||||
|
||||
/** @var ?User $user */
|
||||
$user = $this->serviceContainer
|
||||
->get(User::ENTITY_TYPE)
|
||||
->getEntity($id);
|
||||
|
||||
if (!$user) {
|
||||
throw new NotFound();
|
||||
}
|
||||
|
||||
if ($user->isApi()) {
|
||||
throw new Forbidden();
|
||||
}
|
||||
|
||||
if ($user->isSuperAdmin()) {
|
||||
throw new Forbidden();
|
||||
}
|
||||
|
||||
if ($user->isSystem()) {
|
||||
throw new Forbidden();
|
||||
}
|
||||
|
||||
if (!$user->getEmailAddress()) {
|
||||
throw new Forbidden("Generate new password: Can't process because user doesn't have email address.");
|
||||
}
|
||||
|
||||
if (!$this->isSmtpConfigured()) {
|
||||
throw new Forbidden("Generate new password: Can't process because SMTP is not configured.");
|
||||
}
|
||||
|
||||
$password = $this->generator->generate();
|
||||
|
||||
try {
|
||||
$this->sender->sendPassword($user, $password);
|
||||
} catch (SendingError) {
|
||||
throw new Error("Email sending error.");
|
||||
}
|
||||
|
||||
$this->savePassword($user, $password);
|
||||
}
|
||||
|
||||
private function savePassword(User $user, #[SensitiveParameter] string $password): void
|
||||
{
|
||||
$user->set('password', $this->passwordHash->hash($password));
|
||||
|
||||
$this->entityManager->saveEntity($user);
|
||||
}
|
||||
|
||||
private function savePasswordSilent(User $user, #[SensitiveParameter] string $password): void
|
||||
{
|
||||
$user->set('password', $this->passwordHash->hash($password));
|
||||
|
||||
$this->entityManager->saveEntity($user, [SaveOption::SILENT => true]);
|
||||
}
|
||||
|
||||
private function isSmtpConfigured(): bool
|
||||
{
|
||||
return
|
||||
$this->emailSender->hasSystemSmtp() ||
|
||||
$this->config->get('internalSmtpServer');
|
||||
}
|
||||
|
||||
private function isPortalLdapDisabled(): bool
|
||||
{
|
||||
return $this->applicationState->isPortal() &&
|
||||
$this->authenticationMethodProvider->get() === LdapLogin::NAME &&
|
||||
!$this->config->get('ldapPortalUserLdapAuth');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user