Initial commit

This commit is contained in:
root
2026-01-19 17:44:46 +01:00
commit 823af8b11d
8721 changed files with 1130846 additions and 0 deletions

View File

@@ -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\Api;
use Espo\Core\AclManager;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Entities\User;
use Espo\ORM\EntityManager;
/**
* User ACL data.
*/
class GetUserAcl implements Action
{
public function __construct(
private EntityManager $entityManager,
private AclManager $aclManager,
private User $user
) {}
public function process(Request $request): Response
{
$userId = $request->getRouteParam('id');
if (!$userId) {
throw new BadRequest();
}
if (
!$this->user->isAdmin() &&
$this->user->getId() !== $userId
) {
throw new Forbidden();
}
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $userId);
if (!$user) {
throw new NotFound();
}
$data = $this->aclManager->getMapData($user);
return ResponseComposer::json($data);
}
}

View File

@@ -0,0 +1,69 @@
<?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\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Entities\User;
use Espo\Tools\UserSecurity\ApiService;
/**
* Generates new API keys for API users.
*/
class PostApiKeyGenerate implements Action
{
public function __construct(
private ApiService $service,
private User $user
) {}
public function process(Request $request): Response
{
if (!$this->user->isAdmin()) {
throw new Forbidden();
}
$data = $request->getParsedBody();
$id = $data->id;
if (!$id) {
throw new BadRequest();
}
$entity = $this->service->generateNewApiKey($id);
return ResponseComposer::json($entity->getValueMap());
}
}

View File

@@ -0,0 +1,61 @@
<?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\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\UserSecurity\Password\Service;
/**
* Changes a password in a recovery process.
*/
class PostChangePasswordByRequest implements Action
{
public function __construct(private Service $service) {}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
$requestId = $data->requestId ?? null;
$password = $data->password ?? null;
if (!$requestId || $password === null) {
throw new BadRequest();
}
$url = $this->service->changePasswordByRecovery($requestId, $password);
return ResponseComposer::json(['url' => $url]);
}
}

View File

@@ -0,0 +1,66 @@
<?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\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\UserSecurity\Password\RecoveryService;
/**
* Initiates a password recovery process.
*/
class PostPasswordChangeRequest implements Action
{
public function __construct(private RecoveryService $service) {}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
$userName = $data->userName ?? null;
$emailAddress = $data->emailAddress ?? null;
$url = $data->url ?? null;
if (!$userName || !$emailAddress) {
throw new BadRequest();
}
if (!is_string($userName) || !is_string($emailAddress)) {
throw new BadRequest();
}
$this->service->request($emailAddress, $userName, $url);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,67 @@
<?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\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Entities\User;
use Espo\Tools\UserSecurity\Password\Service;
/**
* Generates and sends a password for a specific user.
*/
class PostPasswordGenerate implements Action
{
public function __construct(
private Service $service,
private User $user
) {}
public function process(Request $request): Response
{
if (!$this->user->isAdmin()) {
throw new Forbidden();
}
$id = $request->getParsedBody()->id ?? null;
if (!$id) {
throw new BadRequest();
}
$this->service->generateAndSendNewPasswordForUser($id);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,67 @@
<?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\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Entities\User;
use Espo\Tools\UserSecurity\Password\Service;
/**
* Sends password-change link to a specific user.
*/
class PostPasswordRecovery implements Action
{
public function __construct(
private Service $service,
private User $user
) {}
public function process(Request $request): Response
{
if (!$this->user->isAdmin()) {
throw new Forbidden();
}
$id = $request->getParsedBody()->id ?? null;
if (!$id) {
throw new BadRequest();
}
$this->service->createAndSendPasswordRecovery($id);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,69 @@
<?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\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Entities\User;
use Espo\Tools\UserSecurity\Password\Service;
use SensitiveParameter;
/**
* Changes own user password.
*/
class PutPassword implements Action
{
public function __construct(
private Service $service,
private User $user
) {}
public function process(#[SensitiveParameter] Request $request): Response
{
$data = $request->getParsedBody();
$password = $data->password ?? null;
$currentPassword = $data->currentPassword ?? null;
if (
!is_string($password) ||
!is_string($currentPassword)
) {
throw new BadRequest("No `password` or `currentPassword`.");
}
$this->service->changePasswordWithCheck($this->user->getId(), $password, $currentPassword);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,95 @@
<?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;
use Espo\Core\Authentication\Logins\Hmac;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Record\ServiceContainer;
use Espo\Core\Utils\Util;
use Espo\Entities\User;
use Espo\ORM\EntityManager;
class ApiService
{
private ServiceContainer $serviceContainer;
private User $user;
private EntityManager $entityManager;
public function __construct(
ServiceContainer $serviceContainer,
User $user,
EntityManager $entityManager
) {
$this->serviceContainer = $serviceContainer;
$this->user = $user;
$this->entityManager = $entityManager;
}
/**
* @throws Forbidden
* @throws NotFound
*/
public function generateNewApiKey(string $id): User
{
if (!$this->user->isAdmin()) {
throw new Forbidden();
}
$service = $this->serviceContainer->get(User::ENTITY_TYPE);
/** @var ?User $entity */
$entity = $service->getEntity($id);
if (!$entity) {
throw new NotFound();
}
if (!$entity->isApi()) {
throw new Forbidden();
}
$apiKey = Util::generateApiKey();
$entity->set('apiKey', $apiKey);
if ($entity->getAuthMethod() === Hmac::NAME) {
$secretKey = Util::generateSecretKey();
$entity->set('secretKey', $secretKey);
}
$this->entityManager->saveEntity($entity);
$service->prepareEntityForOutput($entity);
return $entity;
}
}

View 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;
}
}

View File

@@ -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');
}
}

View 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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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.");
}
}

View File

@@ -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;
}
}

View 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');
}
}

View 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);
}
}

View 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');
}
}

View File

@@ -0,0 +1,313 @@
<?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;
use Espo\Core\Authentication\TwoFactor\Exceptions\NotConfigured;
use Espo\Core\Exceptions\Error\Body;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Utils\Log;
use Espo\ORM\EntityManager;
use Espo\Entities\User;
use Espo\Entities\UserData;
use Espo\Repositories\UserData as UserDataRepository;
use Espo\Core\Api\RequestNull;
use Espo\Core\Authentication\Login\Data as LoginData;
use Espo\Core\Authentication\LoginFactory;
use Espo\Core\Authentication\TwoFactor\UserSetupFactory as TwoFactorUserSetupFactory;
use Espo\Core\Utils\Config;
use stdClass;
class Service
{
public function __construct(
private EntityManager $entityManager,
private User $user,
private Config $config,
private LoginFactory $authLoginFactory,
private TwoFactorUserSetupFactory $twoFactorUserSetupFactory,
private Log $log
) {}
/**
* @throws Forbidden
* @throws NotFound
*/
public function read(string $id): stdClass
{
if (!$this->user->isAdmin() && $id !== $this->user->getId()) {
throw new Forbidden();
}
/** @var ?User $user */
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $id);
if (!$user) {
throw new NotFound();
}
$allow =
$user->isAdmin() ||
$user->isRegular() ||
$user->isPortal() && $this->config->get('auth2FAInPortal');
if (!$allow) {
throw new Forbidden();
}
$userData = $this->getUserDataRepository()->getByUserId($id);
if (!$userData) {
throw new NotFound();
}
return (object) [
'auth2FA' => $userData->get('auth2FA'),
'auth2FAMethod' => $userData->get('auth2FAMethod'),
];
}
/**
* @throws BadRequest
* @throws Forbidden
* @throws NotFound
*/
public function getTwoFactorUserSetupData(string $id, stdClass $data): stdClass
{
if (
!$this->user->isAdmin() &&
$id !== $this->user->getId()
) {
throw new Forbidden();
}
$isReset = $data->reset ?? false;
/** @var ?User $user */
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $id);
if (!$user) {
throw new NotFound();
}
$allow =
$this->config->get('auth2FA') &&
(
$user->isAdmin() ||
$user->isRegular() ||
$user->isPortal() && $this->config->get('auth2FAInPortal')
);
if (!$allow) {
throw new Forbidden();
}
$password = $data->password ?? null;
if (!$password) {
throw new Forbidden('Passport required.');
}
if (!$this->user->isAdmin()) {
$this->checkPassword($id, $password);
}
if ($this->user->isAdmin()) {
$this->checkPassword($this->user->getId(), $password);
}
$auth2FAMethod = $data->auth2FAMethod ?? null;
if (!$auth2FAMethod) {
throw new BadRequest();
}
try {
$clientData = $this->twoFactorUserSetupFactory
->create($auth2FAMethod)
->getData($user);
} catch (NotConfigured $e) {
$this->log->error($e->getMessage());
throw Forbidden::createWithBody(
"2FA method '$auth2FAMethod' is not fully configured.",
Body::create()->withMessageTranslation('2faMethodNotConfigured', 'User')
);
}
if ($isReset) {
$userData = $this->getUserDataRepository()->getByUserId($id);
if (!$userData) {
throw new NotFound();
}
$userData->set('auth2FA', false);
/** @noinspection PhpRedundantOptionalArgumentInspection */
$userData->set('auth2FAMethod', null);
$this->entityManager->saveEntity($userData);
}
return $clientData;
}
/**
* @throws Forbidden
* @throws NotFound
* @throws BadRequest
*/
public function update(string $id, stdClass $data): stdClass
{
if (!$this->user->isAdmin() && $id !== $this->user->getId()) {
throw new Forbidden();
}
/** @var ?User $user */
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $id);
if (!$user) {
throw new NotFound();
}
$allow =
$user->isAdmin() ||
$user->isRegular() ||
$user->isPortal() && $this->config->get('auth2FAInPortal');
if (!$allow) {
throw new Forbidden();
}
$userData = $this->getUserDataRepository()->getByUserId($id);
if (!$userData) {
throw new NotFound();
}
$password = $data->password ?? null;
if (!$password) {
throw new Forbidden('Password required.');
}
if (!$this->user->isAdmin() || $this->user->getId() === $id) {
$this->checkPassword($id, $password);
}
if (property_exists($data, 'auth2FA')) {
$userData->set('auth2FA', $data->auth2FA);
}
if (property_exists($data, 'auth2FAMethod')) {
$userData->set('auth2FAMethod', $data->auth2FAMethod);
}
if (!$userData->get('auth2FA')) {
/** @noinspection PhpRedundantOptionalArgumentInspection */
$userData->set('auth2FAMethod', null);
}
if ($userData->get('auth2FA') && $userData->isAttributeChanged('auth2FA')) {
if (!$this->config->get('auth2FA')) {
throw new Forbidden('2FA is not enabled.');
}
}
if (
$userData->get('auth2FA') &&
$userData->get('auth2FAMethod') &&
($userData->isAttributeChanged('auth2FA') || $userData->isAttributeChanged('auth2FAMethod')) &&
(
!$user->isPortal() ||
$this->config->get('auth2FAInPortal')
)
) {
$auth2FAMethod = $userData->get('auth2FAMethod');
if (!in_array($auth2FAMethod, $this->config->get('auth2FAMethodList', []))) {
throw new Forbidden('Not allowed 2FA auth method.');
}
$verifyResult = $this->twoFactorUserSetupFactory
->create($auth2FAMethod)
->verifyData($user, $data);
if (!$verifyResult) {
throw new Forbidden('Not verified.');
}
}
$this->entityManager->saveEntity($userData);
return (object) [
'auth2FA' => $userData->get('auth2FA'),
'auth2FAMethod' => $userData->get('auth2FAMethod'),
];
}
/**
* @throws Forbidden
*/
private function checkPassword(string $id, string $password): void
{
$user = $this->entityManager
->getRDBRepository(User::ENTITY_TYPE)
->where([
'id' => $id,
])
->findOne();
if (!$user) {
throw new Forbidden('User is not found.');
}
$loginData = LoginData::createBuilder()
->setUsername($user->get('userName'))
->setPassword($password)
->build();
$login = $this->authLoginFactory->createDefault();
$result = $login->login($loginData, new RequestNull());
if ($result->isFail()) {
throw new Forbidden('Password is incorrect.');
}
}
private function getUserDataRepository(): UserDataRepository
{
/** @var UserDataRepository */
return $this->entityManager->getRepository(UserData::ENTITY_TYPE);
}
}

View File

@@ -0,0 +1,93 @@
<?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\TwoFactor;
use Espo\Core\Authentication\TwoFactor\Email\EmailLogin;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Mail\Exceptions\SendingError;
use Espo\Core\Utils\Config;
use Espo\Core\Authentication\TwoFactor\Email\Util;
use Espo\ORM\EntityManager;
use Espo\Entities\User;
class EmailService
{
public function __construct(
private Util $util,
private User $user,
private EntityManager $entityManager,
private Config $config
) {}
/**
* @throws Forbidden
* @throws NotFound
* @throws SendingError
*/
public function sendCode(string $userId, string $emailAddress): void
{
if (!$this->user->isAdmin() && $userId !== $this->user->getId()) {
throw new Forbidden();
}
$this->checkAllowed();
/** @var ?User $user */
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $userId);
if (!$user) {
throw new NotFound();
}
$this->util->sendCode($user, $emailAddress);
$this->util->storeEmailAddress($user, $emailAddress);
}
/**
* @throws Forbidden
*/
private function checkAllowed(): void
{
if (!$this->config->get('auth2FA')) {
throw new Forbidden("2FA is not enabled.");
}
if ($this->user->isPortal() && !$this->config->get('auth2FAInPortal')) {
throw new Forbidden("2FA is not enabled in portals.");
}
$methodList = $this->config->get('auth2FAMethodList') ?? [];
if (!in_array(EmailLogin::NAME, $methodList)) {
throw new Forbidden("Email 2FA is not allowed.");
}
}
}

View File

@@ -0,0 +1,93 @@
<?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\TwoFactor;
use Espo\Core\Authentication\TwoFactor\Sms\SmsLogin;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Utils\Config;
use Espo\Core\Authentication\TwoFactor\Sms\Util;
use Espo\ORM\EntityManager;
use Espo\Entities\User;
class SmsService
{
public function __construct(
private Util $util,
private User $user,
private EntityManager $entityManager,
private Config $config
) {}
/**
* @throws Forbidden
* @throws NotFound
* @throws Error
*/
public function sendCode(string $userId, string $phoneNumber): void
{
if (!$this->user->isAdmin() && $userId !== $this->user->getId()) {
throw new Forbidden();
}
$this->checkAllowed();
/** @var ?User $user */
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $userId);
if (!$user) {
throw new NotFound();
}
$this->util->sendCode($user, $phoneNumber);
$this->util->storePhoneNumber($user, $phoneNumber);
}
/**
* @throws Forbidden
*/
private function checkAllowed(): void
{
if (!$this->config->get('auth2FA')) {
throw new Forbidden("2FA is not enabled.");
}
if ($this->user->isPortal() && !$this->config->get('auth2FAInPortal')) {
throw new Forbidden("2FA is not enabled in portals.");
}
$methodList = $this->config->get('auth2FAMethodList') ?? [];
if (!in_array(SmsLogin::NAME, $methodList)) {
throw new Forbidden("Sms 2FA is not allowed.");
}
}
}