EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
Authentication refactor and changes
Yurii111f9111c405
diff --git a/application/Espo/Core/Api/Auth.php b/application/Espo/Core/Api/Auth.phpindex 6458d8a7c1..a5892474a5 100644--- a/application/Espo/Core/Api/Auth.php+++ b/application/Espo/Core/Api/Auth.php@@ -211,7 +211,6 @@ class Auth'status' => $result->getStatus(),'message' => $result->getMessage(),'view' => $result->getView(),- 'token' => $result->getToken(),'data' => $result->getData(),];diff --git a/application/Espo/Core/Authentication/AuthToken/EspoManager.php b/application/Espo/Core/Authentication/AuthToken/EspoManager.phpindex c1f0971517..6736019624 100644--- a/application/Espo/Core/Authentication/AuthToken/EspoManager.php+++ b/application/Espo/Core/Authentication/AuthToken/EspoManager.php@@ -30,11 +30,12 @@namespace Espo\Core\Authentication\AuthToken;use Espo\Core\Name\Field;+use Espo\ORM\EntityCollection;use Espo\ORM\EntityManager;use Espo\ORM\Name\Attribute;use Espo\ORM\Repository\RDBRepository;use Espo\Entities\AuthToken as AuthTokenEntity;-+use Random\RandomException;use RuntimeException;/**@@ -44,7 +45,7 @@ use RuntimeException;* multiple Espo replicas (for scalability purposes).* Defined at metadata > app > containerServices > authTokenManager.*- * @noinspection PhpUnused+ * @implements Manager<AuthTokenEntity>*/class EspoManager implements Manager{@@ -101,13 +102,11 @@ class EspoManager implements Managerreturn $authToken;}+ /**+ * @param AuthTokenEntity $authToken+ */public function inactivate(AuthToken $authToken): void{- /** @noinspection PhpConditionAlreadyCheckedInspection */- if (!$authToken instanceof AuthTokenEntity) {- throw new RuntimeException();- }-$this->validateNotChanged($authToken);$authToken->setIsActive(false);@@ -117,11 +116,6 @@ class EspoManager implements Managerpublic function renew(AuthToken $authToken): void{- /** @noinspection PhpConditionAlreadyCheckedInspection */- if (!$authToken instanceof AuthTokenEntity) {- throw new RuntimeException();- }-$this->validateNotChanged($authToken);if ($authToken->isNew()) {@@ -133,6 +127,13 @@ class EspoManager implements Manager$this->repository->save($authToken);}+ public function inactiveOther(AuthToken $authToken): void+ {+ foreach ($this->findConcurrent($authToken) as $other) {+ $this->inactivate($other);+ }+ }+private function validate(AuthToken $authToken): void{if (!$authToken->getToken()) {@@ -161,6 +162,25 @@ class EspoManager implements Manager{$length = self::TOKEN_RANDOM_LENGTH;- return bin2hex(random_bytes($length));+ try {+ return bin2hex(random_bytes($length));+ } catch (RandomException $e) {+ throw new RuntimeException(previous: $e);+ }+ }++ /**+ * @return EntityCollection<AuthTokenEntity>+ */+ private function findConcurrent(AuthTokenEntity $authToken): EntityCollection+ {+ return $this->repository+ ->select([Attribute::ID])+ ->where([+ AuthTokenEntity::ATTR_USER_ID => $authToken->getUserId(),+ AuthTokenEntity::FIELD_IS_ACTIVE => true,+ Attribute::ID . '!=' => $authToken->getId(),+ ])+ ->find();}}diff --git a/application/Espo/Core/Authentication/AuthToken/Manager.php b/application/Espo/Core/Authentication/AuthToken/Manager.phpindex 97d13b8f7d..74c99b1d6f 100644--- a/application/Espo/Core/Authentication/AuthToken/Manager.php+++ b/application/Espo/Core/Authentication/AuthToken/Manager.php@@ -31,26 +31,44 @@ namespace Espo\Core\Authentication\AuthToken;/*** Fetches and stores auth tokens.+ *+ * @template TAuthToken of AuthToken = AuthToken*/interface Manager{/*** Get an auth token. If it does not exist, then returns NULL.+ *+ * @return ?TAuthToken*/public function get(string $token): ?AuthToken;/*** Create an auth token and store it.+ *+ * @return TAuthToken*/public function create(Data $data): AuthToken;/*** Make an auth token inactive (invalid).+ *+ * @param TAuthToken $authToken*/public function inactivate(AuthToken $authToken): void;/*** Update a last access date. An implementation can be omitted to avoid a writing operation.+ *+ * @param TAuthToken $authToken*/public function renew(AuthToken $authToken): void;++ /**+ * Inactivate concurrent auth tokens for the same user.+ *+ * @param TAuthToken $authToken+ * @since 10.1.0+ */+ public function inactiveOther(AuthToken $authToken): void;}diff --git a/application/Espo/Core/Authentication/Authentication.php b/application/Espo/Core/Authentication/Authentication.phpindex 3bef797424..e70ddbf3a0 100644--- a/application/Espo/Core/Authentication/Authentication.php+++ b/application/Espo/Core/Authentication/Authentication.php@@ -29,17 +29,16 @@namespace Espo\Core\Authentication;+use Espo\Core\Authentication\Repository\UserRepository;use Espo\Core\Exceptions\Forbidden;use Espo\Core\Exceptions\NotFound;use Espo\Core\Name\Field;use Espo\Core\Utils\Language\LanguageProxy;use Espo\ORM\Name\Attribute;-use Espo\Repositories\UserData as UserDataRepository;use Espo\Entities\Portal;use Espo\Entities\User;use Espo\Entities\AuthLogRecord;use Espo\Entities\AuthToken as AuthTokenEntity;-use Espo\Entities\UserData;use Espo\Core\Exceptions\Error\Body;use Espo\Core\Authentication\Logout\Params as LogoutParams;use Espo\Core\Authentication\Util\MethodProvider;@@ -58,7 +57,8 @@ use Espo\Core\Api\Util;use Espo\Core\Utils\Log;use Espo\Core\ORM\EntityManagerProxy;use Espo\Core\Exceptions\ServiceUnavailable;-+use Espo\Core\Authentication\Repository\AuthLogRecordRepository;+use Espo\Tools\User\UserDataProvider;use LogicException;use RuntimeException;@@ -69,7 +69,6 @@ class Authentication{private const string LOGOUT_USERNAME = '**logout';- private const string HEADER_CREATE_TOKEN_SECRET = 'Espo-Authorization-Create-Token-Secret';private const string HEADER_ANOTHER_USER = 'X-Another-User';private const string HEADER_LOGOUT_REDIRECT_URL = 'X-Logout-Redirect-Url';@@ -89,6 +88,9 @@ class Authenticationprivate MethodProvider $methodProvider,private Util $util,private LanguageProxy $language,+ private UserDataProvider $userDataProvider,+ private UserRepository $userRepository,+ private AuthLogRecordRepository $authLogRecordRepository,) {}/**@@ -101,78 +103,36 @@ class Authentication{$username = $data->getUsername();$password = $data->getPassword();- $method = $data->getMethod();$byTokenOnly = $data->byTokenOnly();- if (- $method &&- !$this->configDataProvider->authenticationMethodIsApi($method)- ) {- $this->log->warning("Auth: Trying to use not allowed authentication method '{method}'.", [- 'method' => $method,- ]);-- return $this->processFail(Result::fail(FailReason::METHOD_NOT_ALLOWED), $data, $request);+ if ($failResult = $this->processMethodCheck($data, $request)) {+ return $failResult;}- try {- $this->hookManager->processBeforeLogin($data, $request);- } catch (Forbidden $e) {- $this->processForbidden($e);- }-- if (!$method && $password === null) {- $this->log->error("Auth: Trying to login w/o password.");+ $this->processBeforeLoginHook($data, $request);- return Result::fail(FailReason::NO_PASSWORD);+ if ($failResult = $this->processHasPasswordCheck($data)) {+ return $failResult;}- $authToken = null;+ [$authToken, $authTokenIsFound] = $this->getAuthToken($data->getMethod(), $password, $request);- if (!$method) {- $authToken = $this->authTokenManager->get($password);+ if ($authToken && !$this->processAuthTokenCheck($authToken)) {+ return Result::fail(FailReason::DENIED);}- if ($authToken && $authToken->getSecret()) {- $sentSecret = $request->getCookieParam(self::COOKIE_AUTH_TOKEN_SECRET);-- if ($sentSecret !== $authToken->getSecret()) {- $authToken = null;- }- }-- $authTokenIsFound = $authToken !== null;-- if ($authToken && !$authToken->isActive()) {- $authToken = null;- }-- if ($authToken) {- $authTokenCheckResult = $this->processAuthTokenCheck($authToken);-- if (!$authTokenCheckResult) {- return Result::fail(FailReason::DENIED);- }- }-- $byTokenAndUsername = $request->getHeader(HeaderKey::AUTHORIZATION_BY_TOKEN) === 'true';-- if ($method && $byTokenAndUsername) {+ if ($data->getMethod() && $this->isByTokenAndUsername($request)) {return Result::fail(FailReason::DISCREPANT_DATA);}- if (($byTokenAndUsername || $byTokenOnly) && !$authToken) {- if ($username) {- $this->log->info("Auth: Trying to login as user '{username}' by token but token is not found.", [- 'username' => $username,- ]);- }-- return $this->processFail(Result::fail(FailReason::TOKEN_NOT_FOUND), $data, $request);+ if ($failResult = $this->processAuthTokenNotFoundCheck($data, $request, $authToken)) {+ return $failResult;}if ($byTokenOnly) {- assert($authToken !== null);+ if ($authToken === null) {+ throw new LogicException();+ }$username = $this->getUsernameByAuthToken($authToken);@@ -181,24 +141,20 @@ class Authentication}}- $method ??= $this->methodProvider->get();+ $method = $data->getMethod() ?? $this->methodProvider->get();- $login = $this->loginFactory->create($method, $this->isPortal());-- $loginData = LoginData- ::createBuilder()- ->setUsername($username)- ->setPassword($password)- ->setAuthToken($authToken)- ->build();-- $result = $login->login($loginData, $request);+ $result = $this->processLogin(+ method: $method,+ username: $username,+ password: $password,+ authToken: $authToken,+ request: $request,+ );$user = $result->getUser();$authLogRecord = !$authTokenIsFound ?- $this->createAuthLogRecord($username, $user, $request, $method) :- null;+ $this->createAuthLogRecord($username, $user, $request, $method) : null;if ($result->isFail()) {return $this->processFail($result, $data, $request);@@ -210,11 +166,7 @@ class Authentication}if (!$user->isAdmin() && $this->configDataProvider->isMaintenanceMode()) {- throw ServiceUnavailable::createWithBody(- "Application is in maintenance mode.",- Body::create()- ->withMessage($this->language->translateLabel('maintenanceModeError', 'messages'))- );+ $this->throwMaintenanceModeException();}if (!$this->processUserCheck($user, $authLogRecord)) {@@ -235,12 +187,7 @@ class Authentication$this->applicationUser->setUser($loggedUser);}- if (- !$result->bypassSecondStep() &&- !$result->isSecondStepRequired() &&- !$authToken &&- $this->getTwoFactorEnabled()- ) {+ if ($this->toProcessTwoFactor($result, $authToken)) {$result = $this->processTwoFactor($result, $request);if ($result->isFail()) {@@ -254,17 +201,14 @@ class Authentication$this->processForbidden($e, $authLogRecord);}- if (- !$result->isSecondStepRequired() &&- $request->getHeader(HeaderKey::AUTHORIZATION)- ) {+ if (!$result->isSecondStepRequired() && $request->getHeader(HeaderKey::AUTHORIZATION)) {$authToken = $this->processAuthTokenFinal(- $authToken,- $authLogRecord,- $user,- $loggedUser,- $request,- $response+ authToken: $authToken,+ authLogRecord: $authLogRecord,+ user: $user,+ loggedUser: $loggedUser,+ request: $request,+ response: $response,);}@@ -287,7 +231,7 @@ class AuthenticationUser $user,User $loggedUser,Request $request,- Response $response+ Response $response,): AuthToken {if ($authToken) {@@ -304,8 +248,8 @@ class Authentication$authTokenId = $authToken->hasId() ? $authToken->getId() : null;}- $loggedUser->set('token', $authToken->getToken());- $loggedUser->set('authTokenId', $authTokenId);+ $loggedUser->set(User::FIELD_TOKEN, $authToken->getToken());+ $loggedUser->set(User::ATTR_AUTH_TOKEN_ID, $authTokenId);$authLogRecord?->setAuthTokenId($authTokenId);@@ -315,7 +259,7 @@ class Authenticationprivate function processAuthLogRecord(?AuthLogRecord $authLogRecord,?AuthToken $authToken,- User $loggedUser+ User $loggedUser,): void {if ($authLogRecord) {@@ -327,16 +271,11 @@ class Authentication$authToken instanceof AuthTokenEntity &&$authToken->hasId()) {- $authLogRecord = $this->entityManager- ->getRDBRepository(AuthLogRecord::ENTITY_TYPE)- ->select([Attribute::ID])- ->where(['authTokenId' => $authToken->getId()])- ->order('requestTime', true)- ->findOne();+ $authLogRecord = $this->authLogRecordRepository->findOneByAuthTokenId($authToken->getId(), [Attribute::ID]);}if ($authLogRecord) {- $loggedUser->set('authLogRecordId', $authLogRecord->getId());+ $loggedUser->set(User::ATTR_AUTH_LOG_RECORD_ID, $authLogRecord->getId());}}@@ -353,13 +292,13 @@ class Authenticationprivate function processAuthTokenCheck(AuthToken $authToken): bool{if ($this->isPortal() && $authToken->getPortalId() !== $this->getPortal()->getId()) {- $this->log->info("Auth: Trying to login to portal with a token not related to portal.");+ $this->log->info("Auth: Trying to log in to portal with a token not related to portal.");return false;}if (!$this->isPortal() && $authToken->getPortalId()) {- $this->log->info("Auth: Trying to login to crm with a token related to portal.");+ $this->log->info("Auth: Trying to log in to crm with a token related to portal.");return false;}@@ -370,7 +309,7 @@ class Authenticationprivate function processUserCheck(User $user, ?AuthLogRecord $authLogRecord): bool{if (!$user->isActive()) {- $this->log->info("Auth: Trying to login as user '{username}' which is not active.", [+ $this->log->info("Auth: Trying to log in as user '{username}' which is not active.", ['username' => $user->getUserName(),]);@@ -380,7 +319,7 @@ class Authentication}if ($user->isSystem()) {- $this->log->info("Auth: Trying to login to crm as a system user '{username}'.", [+ $this->log->info("Auth: Trying to log in to crm as a system user '{username}'.", ['username' => $user->getUserName(),]);@@ -390,7 +329,7 @@ class Authentication}if (!$user->isAdmin() && !$this->isPortal() && $user->isPortal()) {- $this->log->info("Auth: Trying to login to crm as a portal user '{username}'.", [+ $this->log->info("Auth: Trying to log in to crm as a portal user '{username}'.", ['username' => $user->getUserName(),]);@@ -400,7 +339,7 @@ class Authentication}if ($this->isPortal() && !$user->isPortal()) {- $this->log->info("Auth: Trying to login to portal as user '{username}' which is not portal user.", [+ $this->log->info("Auth: Trying to log in to portal as user '{username}' which is not portal user.", ['username' => $user->getUserName(),]);@@ -410,18 +349,13 @@ class Authentication}if ($this->isPortal()) {- $isPortalRelatedToUser = $this->entityManager- ->getRDBRepository(Portal::ENTITY_TYPE)- ->getRelation($this->getPortal(), 'users')- ->isRelated($user);+ $isUserInPortal = $user->getPortals()->hasId($this->getPortal()->getId());- if (!$isPortalRelatedToUser) {- $msg = "Auth: Trying to login to portal as user '{username}' " .+ if (!$isUserInPortal) {+ $message = "Auth: Trying to log in to portal as user '{username}' " ."which is portal user but does not belong to portal.";- $this->log->info($msg, [- 'username' => $user->getUserName(),- ]);+ $this->log->info($message, ['username' => $user->getUserName()]);$this->logDenied($authLogRecord, AuthLogRecord::DENIAL_REASON_USER_IS_NOT_IN_PORTAL);@@ -453,7 +387,7 @@ class Authenticationprivate function getUser2FAMethod(User $user): ?string{- $userData = $this->getUserDataRepository()->getByUserId($user->getId());+ $userData = $this->userDataProvider->get($user->getId());if (!$userData) {return null;@@ -479,7 +413,7 @@ class Authenticationprivate function createAuthToken(User $user, Request $request, Response $response): AuthToken{$createSecret =- $request->getHeader(self::HEADER_CREATE_TOKEN_SECRET) === 'true' &&+ $request->getHeader(HeaderKey::CREATE_TOKEN_SECRET) === 'true' &&!$this->configDataProvider->isAuthTokenSecretDisabled();$ipAddress = $this->util->obtainIpFromRequest($request);@@ -498,26 +432,8 @@ class Authentication$this->setSecretInCookie($authToken->getSecret(), $response, $request);}- /** @noinspection PhpConditionAlreadyCheckedInspection */- if (- $this->configDataProvider->preventConcurrentAuthToken() &&- $authToken instanceof AuthTokenEntity- ) {- $concurrentAuthTokenList = $this->entityManager- ->getRDBRepository(AuthTokenEntity::ENTITY_TYPE)- ->select([Attribute::ID])- ->where([- 'userId' => $user->getId(),- 'isActive' => true,- 'id!=' => $authToken->getId(),- ])- ->find();-- foreach ($concurrentAuthTokenList as $concurrentAuthToken) {- $concurrentAuthToken->set('isActive', false);-- $this->entityManager->saveEntity($concurrentAuthToken);- }+ if ($this->configDataProvider->preventConcurrentAuthToken()) {+ $this->authTokenManager->inactiveOther($authToken);}return $authToken;@@ -586,7 +502,7 @@ class Authentication?string $username,?User $user,Request $request,- ?string $method = null+ ?string $method = null,): ?AuthLogRecord {if ($username === self::LOGOUT_USERNAME) {@@ -704,7 +620,7 @@ class AuthenticationResult $result,AuthenticationData $data,Request $request,- bool $byToken+ bool $byToken,): Result {if ($byToken) {@@ -721,7 +637,7 @@ class Authenticationprivate function processSecondStepRequired(Result $result,AuthenticationData $data,- Request $request+ Request $request,): Result {$this->hookManager->processOnSecondStepRequired($result, $data, $request);@@ -729,19 +645,9 @@ class Authenticationreturn $result;}- private function getUserDataRepository(): UserDataRepository- {- /** @var UserDataRepository */- return $this->entityManager->getRepository(UserData::ENTITY_TYPE);- }-private function getUsernameByAuthToken(AuthToken $authToken): ?string{- $user = $this->entityManager- ->getRDBRepositoryByClass(User::class)- ->select([User::FIELD_USER_NAME])- ->where([Attribute::ID => $authToken->getUserId()])- ->findOne();+ $user = $this->userRepository->findOneById($authToken->getUserId(), [User::FIELD_USER_NAME]);return $user?->getUserName();}@@ -766,10 +672,7 @@ class Authenticationreturn [null, FailReason::ANOTHER_USER_NOT_ALLOWED];}- $loggedUser = $this->entityManager- ->getRDBRepositoryByClass(User::class)- ->where([User::FIELD_USER_NAME => $username])- ->findOne();+ $loggedUser = $this->userRepository->findOneByUsername($username);if (!$loggedUser) {return [null, FailReason::ANOTHER_USER_NOT_FOUND];@@ -787,14 +690,14 @@ class Authenticationprivate function prepareUser(User $user, Request $request): void{if ($this->isPortal()) {- $user->set('portalId', $this->getPortal()->getId());+ $user->set(User::ATTR_PORTAL_ID, $this->getPortal()->getId());}if (!$this->isPortal()) {$user->loadLinkMultipleField(Field::TEAMS);}- $user->set('ipAddress', $this->util->obtainIpFromRequest($request));+ $user->set(User::FIELD_IP_ADDRESS, $this->util->obtainIpFromRequest($request));}/**@@ -844,4 +747,146 @@ class Authenticationreturn $this->configDataProvider->isTwoFactorEnabled();}++ /**+ * @throws Forbidden+ * @throws ServiceUnavailable+ */+ private function processBeforeLoginHook(AuthenticationData $data, Request $request): void+ {+ try {+ $this->hookManager->processBeforeLogin($data, $request);+ } catch (Forbidden $e) {+ $this->processForbidden($e);+ }+ }++ private function toProcessTwoFactor(Result $result, ?AuthToken $authToken): bool+ {+ return+ !$result->bypassSecondStep() &&+ !$result->isSecondStepRequired() &&+ !$authToken &&+ $this->getTwoFactorEnabled();+ }++ /**+ * @throws ServiceUnavailable+ */+ private function throwMaintenanceModeException(): never+ {+ throw ServiceUnavailable::createWithBody(+ "Application is in maintenance mode.",+ Body::create()+ ->withMessage($this->language->translateLabel('maintenanceModeError', 'messages'))+ );+ }++ private function processLogin(+ string $method,+ ?string $username,+ ?string $password,+ ?AuthToken $authToken,+ Request $request,+ ): Result {++ $login = $this->loginFactory->create($method, $this->isPortal());++ $loginData = LoginData::createBuilder()+ ->setUsername($username)+ ->setPassword($password)+ ->setAuthToken($authToken)+ ->build();++ return $login->login($loginData, $request);+ }++ private function processMethodCheck(AuthenticationData $data, Request $request): ?Result+ {+ $method = $data->getMethod();++ if ($method && !$this->configDataProvider->authenticationMethodIsApi($method)) {+ $this->log->warning("Auth: Trying to use not allowed authentication method '{method}'.", [+ 'method' => $method,+ ]);++ return $this->processFail(Result::fail(FailReason::METHOD_NOT_ALLOWED), $data, $request);+ }++ return null;+ }++ private function processHasPasswordCheck(AuthenticationData $data): ?Result+ {+ $password = $data->getPassword();+ $method = $data->getMethod();++ if (!$method && $password === null) {+ $this->log->error("Auth: Trying to log in w/o password.");++ return Result::fail(FailReason::NO_PASSWORD);+ }++ return null;+ }++ /**+ * @return array{?AuthToken, bool}+ */+ private function getAuthToken(?string $method, ?string $password, Request $request): array+ {+ $authToken = null;++ if (!$method) {+ if ($password === null) {+ throw new LogicException();+ }++ $authToken = $this->authTokenManager->get($password);+ }++ if ($authToken && $authToken->getSecret()) {+ $sentSecret = $request->getCookieParam(self::COOKIE_AUTH_TOKEN_SECRET);++ if ($sentSecret !== $authToken->getSecret()) {+ $authToken = null;+ }+ }++ $authTokenIsFound = $authToken !== null;++ if ($authToken && !$authToken->isActive()) {+ $authToken = null;+ }++ return [$authToken, $authTokenIsFound];+ }++ private function processAuthTokenNotFoundCheck(+ AuthenticationData $data,+ Request $request,+ ?AuthToken $authToken,+ ): ?Result {++ if ($authToken) {+ return null;+ }++ if ($this->isByTokenAndUsername($request) || $data->byTokenOnly()) {+ if ($data->getUsername()) {+ $this->log->info("Auth: Trying to log in as user '{username}' by token but token is not found.", [+ 'username' => $data->getUsername(),+ ]);+ }++ return $this->processFail(Result::fail(FailReason::TOKEN_NOT_FOUND), $data, $request);+ }++ return null;+ }++ private function isByTokenAndUsername(Request $request): bool+ {+ return $request->getHeader(HeaderKey::AUTHORIZATION_BY_TOKEN) === 'true';+ }}diff --git a/application/Espo/Core/Authentication/HeaderKey.php b/application/Espo/Core/Authentication/HeaderKey.phpindex 8b9192e460..1f939103b6 100644--- a/application/Espo/Core/Authentication/HeaderKey.php+++ b/application/Espo/Core/Authentication/HeaderKey.php@@ -31,7 +31,8 @@ namespace Espo\Core\Authentication;class HeaderKey{- public const AUTHORIZATION_BY_TOKEN = 'Espo-Authorization-By-Token';- public const AUTHORIZATION_CODE = 'Espo-Authorization-Code';- public const AUTHORIZATION = 'Espo-Authorization';+ public const string AUTHORIZATION_BY_TOKEN = 'Espo-Authorization-By-Token';+ public const string AUTHORIZATION_CODE = 'Espo-Authorization-Code';+ public const string AUTHORIZATION = 'Espo-Authorization';+ public const string CREATE_TOKEN_SECRET = 'Espo-Authorization-Create-Token-Secret';}diff --git a/application/Espo/Core/Authentication/Repository/AuthLogRecordRepository.php b/application/Espo/Core/Authentication/Repository/AuthLogRecordRepository.phpnew file mode 100644index 0000000000..9e614e90ff--- /dev/null+++ b/application/Espo/Core/Authentication/Repository/AuthLogRecordRepository.php@@ -0,0 +1,58 @@+<?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\Core\Authentication\Repository;++use Espo\Core\ORM\EntityManagerProxy;+use Espo\Entities\AuthLogRecord;++class AuthLogRecordRepository+{+ public function __construct(+ private EntityManagerProxy $entityManager,+ ) {}++ /**+ * @param ?string[] $select+ */+ public function findOneByAuthTokenId(string $authTokenId, ?array $select = null): ?AuthLogRecord+ {+ $builder = $this->entityManager+ ->getRDBRepositoryByClass(AuthLogRecord::class);++ if ($select) {+ $builder->select($select);+ }++ return $builder+ ->where([AuthLogRecord::ATTR_AUTH_TOKEN_ID => $authTokenId])+ ->order(AuthLogRecord::FIELD_REQUEST_TIME, true)+ ->findOne();+ }+}diff --git a/application/Espo/Core/Authentication/Repository/UserRepository.php b/application/Espo/Core/Authentication/Repository/UserRepository.phpnew file mode 100644index 0000000000..9357dffe2e--- /dev/null+++ b/application/Espo/Core/Authentication/Repository/UserRepository.php@@ -0,0 +1,66 @@+<?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\Core\Authentication\Repository;++use Espo\Core\ORM\EntityManagerProxy;+use Espo\Entities\User;+use Espo\ORM\Name\Attribute;++class UserRepository+{+ public function __construct(+ private EntityManagerProxy $entityManager,+ ) {}++ /**+ * @param ?string[] $select+ */+ public function findOneById(string $id, ?array $select = null): ?User+ {+ $builder = $this->entityManager+ ->getRDBRepositoryByClass(User::class);++ if ($select) {+ $builder->select($select);+ }++ return $builder+ ->where([Attribute::ID => $id])+ ->findOne();+ }++ public function findOneByUsername(string $username): ?User+ {+ return $this->entityManager+ ->getRDBRepositoryByClass(User::class)+ ->where([User::FIELD_USER_NAME => $username])+ ->findOne();+ }+}diff --git a/application/Espo/Core/Authentication/Result.php b/application/Espo/Core/Authentication/Result.phpindex 35bbd8c5c2..ea94ed5b3a 100644--- a/application/Espo/Core/Authentication/Result.php+++ b/application/Espo/Core/Authentication/Result.php@@ -41,14 +41,13 @@ use stdClass;*/class Result{- public const STATUS_SUCCESS = 'success';- public const STATUS_SECOND_STEP_REQUIRED = 'secondStepRequired';- public const STATUS_FAIL = 'fail';+ public const string STATUS_SUCCESS = 'success';+ public const string STATUS_SECOND_STEP_REQUIRED = 'secondStepRequired';+ public const string STATUS_FAIL = 'fail';private ?User $user;private string $status;private ?string $message = null;- private ?string $token = null;private ?string $view = null;private ?string $failReason = null;private bool $bypassSecondStep = false;@@ -63,7 +62,6 @@ class Resultif ($data) {$this->message = $data->getMessage();- $this->token = $data->getToken();$this->view = $data->getView();$this->failReason = $data->getFailReason();}@@ -172,15 +170,7 @@ class Result}/**- * A token can be returned to a client to be used instead of password in a request for a second step.- */- public function getToken(): ?string- {- return $this->token;- }-- /**- * Additional data that can be needed for a second step.+ * Additional data that can be needed for the second step.*/public function getData(): ?stdClass{diff --git a/application/Espo/Core/Authentication/Result/Data.php b/application/Espo/Core/Authentication/Result/Data.phpindex 90f0c6ddb0..75014cd0fd 100644--- a/application/Espo/Core/Authentication/Result/Data.php+++ b/application/Espo/Core/Authentication/Result/Data.php@@ -43,7 +43,6 @@ class Dataprivate function __construct(private ?string $message = null,private ?string $failReason = null,- private ?string $token = null,private ?string $view = null) {}@@ -72,11 +71,6 @@ class Datareturn $this->message;}- public function getToken(): ?string- {- return $this->token;- }-public function getFailReason(): ?string{return $this->failReason;@@ -104,15 +98,6 @@ class Datareturn $obj;}- /** @noinspection PhpUnused */- public function withToken(?string $token): self- {- $obj = clone $this;- $obj->token = $token;-- return $obj;- }-/** @noinspection PhpUnused */public function withView(?string $view): self{diff --git a/application/Espo/Entities/AuthLogRecord.php b/application/Espo/Entities/AuthLogRecord.phpindex 699aa12f64..a82adf2e48 100644--- a/application/Espo/Entities/AuthLogRecord.php+++ b/application/Espo/Entities/AuthLogRecord.php@@ -44,6 +44,9 @@ class AuthLogRecord extends Entitypublic const DENIAL_REASON_IS_SYSTEM_USER = 'IS_SYSTEM_USER';public const DENIAL_REASON_FORBIDDEN = 'FORBIDDEN';+ public const string ATTR_AUTH_TOKEN_ID = 'authTokenId';+ public const string FIELD_REQUEST_TIME = 'requestTime';+public function setUsername(?string $username): self{$this->set('username', $username);diff --git a/application/Espo/Entities/AuthToken.php b/application/Espo/Entities/AuthToken.phpindex 21e62da63c..db657625ce 100644--- a/application/Espo/Entities/AuthToken.php+++ b/application/Espo/Entities/AuthToken.php@@ -40,14 +40,23 @@ class AuthToken extends BaseEntity implements AuthTokenInterface/** @since 10.0.0 */public const string FIELD_PASSWORD_VERSION = 'passwordVersion';+ /** @since 10.1.0 */+ public const string FIELD_IS_ACTIVE = 'isActive';++ /** @since 10.1.0 */+ public const string FIELD_TOKEN = 'token';++ /** @since 10.1.0 */+ public const string ATTR_USER_ID = 'userId';+public function getToken(): string{- return $this->get('token');+ return $this->get(self::FIELD_TOKEN);}public function getUserId(): string{- return $this->get('userId');+ return $this->get(self::ATTR_USER_ID);}public function getPortalId(): ?string@@ -62,7 +71,7 @@ class AuthToken extends BaseEntity implements AuthTokenInterfacepublic function isActive(): bool{- return $this->get('isActive');+ return $this->get(self::FIELD_IS_ACTIVE);}public function getPasswordVersion(): ?int@@ -82,14 +91,14 @@ class AuthToken extends BaseEntity implements AuthTokenInterfacepublic function setIsActive(bool $isActive): self{- $this->set('isActive', $isActive);+ $this->set(self::FIELD_IS_ACTIVE, $isActive);return $this;}public function setUserId(string $userId): self{- $this->set('userId', $userId);+ $this->set(self::ATTR_USER_ID, $userId);return $this;}@@ -103,7 +112,7 @@ class AuthToken extends BaseEntity implements AuthTokenInterfacepublic function setToken(string $token): self{- $this->set('token', $token);+ $this->set(self::FIELD_TOKEN, $token);return $this;}diff --git a/application/Espo/Entities/Portal.php b/application/Espo/Entities/Portal.phpindex cfb4e06893..99fa59fd1b 100644--- a/application/Espo/Entities/Portal.php+++ b/application/Espo/Entities/Portal.php@@ -35,7 +35,7 @@ use Espo\Repositories\Portal as PortalRepository;class Portal extends Entity{- public const ENTITY_TYPE = 'Portal';+ public const string ENTITY_TYPE = 'Portal';/*** @var string[]@@ -57,6 +57,8 @@ class Portal extends Entity'defaultCurrency',];+ public const string LINK_USERS = 'users';+/*** @return string[]*/diff --git a/application/Espo/Entities/User.php b/application/Espo/Entities/User.phpindex 381ad067b4..68dd2233d4 100644--- a/application/Espo/Entities/User.php+++ b/application/Espo/Entities/User.php@@ -43,6 +43,24 @@ class User extends Personpublic const ATTR_TYPE = 'type';public const ATTR_IS_ACTIVE = 'isActive';+ /**+ * @internal+ * @since 10.1.0+ */+ public const string ATTR_PORTAL_ID = 'portalId';++ /**+ * @internal+ * @since 10.1.0+ */+ public const string ATTR_AUTH_TOKEN_ID = 'authTokenId';++ /**+ * @internal+ * @since 10.1.0+ */+ public const string ATTR_AUTH_LOG_RECORD_ID = 'authLogRecordId';+/** @since 10.0.0 */public const string FIELD_USER_NAME = 'userName';/** @since 10.0.0 */@@ -56,6 +74,18 @@ class User extends Person/** @since 10.0.4 */public const string FIELD_AUTH_METHOD = 'authMethod';+ /**+ * @internal+ * @since 10.1.0+ */+ public const string FIELD_TOKEN = 'token';++ /**+ * @internal+ * @since 10.1.0+ */+ public const string FIELD_IP_ADDRESS = 'ipAddress';+public const LINK_ACCOUNTS = 'accounts';public const LINK_CONTACT = 'contact';public const LINK_PORTALS = 'portals';diff --git a/application/Espo/Tools/App/AppService.php b/application/Espo/Tools/App/AppService.phpindex d010c07391..f950819e84 100644--- a/application/Espo/Tools/App/AppService.php+++ b/application/Espo/Tools/App/AppService.php@@ -60,7 +60,7 @@ class AppService/** @var string[] */private array $forbiddenUserAttributeList = ['apiKey',- 'authTokenId',+ User::ATTR_AUTH_TOKEN_ID,User::FIELD_PASSWORD,'rolesIds','rolesNames',@@ -142,7 +142,7 @@ class AppService'user' => $this->getUserDataForFrontend(),'acl' => $this->getAclDataForFrontend(),'preferences' => $preferencesData,- 'token' => $this->user->get('token'),+ 'token' => $this->user->get(User::FIELD_TOKEN),'settings' => $settings,'language' => $language,'appParams' => $this->getAppParams(),diff --git a/application/Espo/Tools/User/UserDataProvider.php b/application/Espo/Tools/User/UserDataProvider.phpindex adcc9dc35e..0a55ba37ca 100644--- a/application/Espo/Tools/User/UserDataProvider.php+++ b/application/Espo/Tools/User/UserDataProvider.php@@ -29,15 +29,15 @@namespace Espo\Tools\User;+use Espo\Core\ORM\EntityManagerProxy;use Espo\Entities\UserData;-use Espo\ORM\EntityManager;use Espo\Repositories\UserData as UserDataRepository;use RuntimeException;class UserDataProvider{public function __construct(- private EntityManager $entityManager,+ private EntityManagerProxy $entityManager,) {}public function get(string $userId): ?UserDatadiff --git a/tests/integration/Core/BaseTestCase.php b/tests/integration/Core/BaseTestCase.phpindex dddbf11c8a..a628b15123 100644--- a/tests/integration/Core/BaseTestCase.php+++ b/tests/integration/Core/BaseTestCase.php@@ -50,6 +50,7 @@ use Exception;use integration\Core\NoTransaction;use PHPUnit\Framework\TestCase;+use Psr\Http\Message\ServerRequestInterface;use ReflectionClass;use ReflectionException;use ReflectionMethod;@@ -316,7 +317,9 @@ abstract class BaseTestCase extends TestCase{}/**- * @param array<string, mixed> $queryParams+ * @param array<string, string> $headers+ * @param array<string, string> $queryParams+ * @param array<string, string> $cookieParams*/protected function createRequest(string $method,@@ -324,11 +327,18 @@ abstract class BaseTestCase extends TestCasearray $headers = [],?string $body = null,array $routeParams = [],+ array $cookieParams = [],): RequestWrapper {$request = (new RequestFactory())->createRequest($method, 'http://localhost/?' . http_build_query($queryParams));+ if (!$request instanceof ServerRequestInterface) {+ throw new RuntimeException();+ }++ $request = $request->withCookieParams($cookieParams);+foreach ($headers as $name => $value) {$request = $request->withHeader($name, $value);}diff --git a/tests/integration/Espo/Core/Authentication/AuthenticationTest.php b/tests/integration/Espo/Core/Authentication/AuthenticationTest.phpnew file mode 100644index 0000000000..6d2fb3eb2f--- /dev/null+++ b/tests/integration/Espo/Core/Authentication/AuthenticationTest.php@@ -0,0 +1,313 @@+<?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 integration\Espo\Core\Authentication;++use Espo\Core\Api\Method;+use Espo\Core\Api\RequestWrapper;+use Espo\Core\Api\Response;+use Espo\Core\ApplicationUser;+use Espo\Core\Authentication\Authentication;+use Espo\Core\Authentication\AuthenticationData;+use Espo\Core\Authentication\HeaderKey;+use Espo\Core\Binding\BindingContainerBuilder;+use Espo\Entities\AuthToken;+use Espo\Entities\User;+use tests\integration\Core\BaseTestCase;++class AuthenticationTest extends BaseTestCase+{+ private const string COOKIE_AUTH_TOKEN_SECRET = 'auth-token-secret';++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testLoginBasicSuccess(): void+ {+ $username = 'test';+ $password = 'hello';++ $this->createUser([+ User::FIELD_USER_NAME => $username,+ User::FIELD_PASSWORD => $password,+ ]);++ $applicationUser = $this->createMock(ApplicationUser::class);++ $applicationUser+ ->expects(self::once())+ ->method('setUser')+ ->with(+ $this->callback(function (User $user) use ($username) {+ return $user->getUserName() === $username;+ })+ );++ $result = $this->createAuthentication($applicationUser)->login(+ data: AuthenticationData::create()+ ->withUsername($username)+ ->withPassword($password),+ request: $this->createSimpleGetRequest(),+ response: $this->createMock(Response::class)+ );++ $this->assertTrue($result->isSuccess());+ $this->assertFalse($result->isFail());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testLoginBasicFailPassword(): void+ {+ $username = 'test';+ $password = 'hello';++ $this->createUser([+ User::FIELD_USER_NAME => $username,+ User::FIELD_PASSWORD => $password,+ ]);++ $applicationUser = $this->createMock(ApplicationUser::class);++ $applicationUser+ ->expects(self::never())+ ->method('setUser');++ $result = $this->createAuthentication($applicationUser)->login(+ data: AuthenticationData::create()+ ->withUsername($username)+ ->withPassword('wrong'),+ request: $this->createSimpleGetRequest(),+ response: $this->createMock(Response::class),+ );++ $this->assertFalse($result->isSuccess());+ $this->assertTrue($result->isFail());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testLoginBasicFailUsername(): void+ {+ $username = 'test';+ $password = 'hello';++ $this->createUser([+ User::FIELD_USER_NAME => $username,+ User::FIELD_PASSWORD => $password,+ ]);++ $applicationUser = $this->createMock(ApplicationUser::class);++ $applicationUser+ ->expects(self::never())+ ->method('setUser');++ $result = $this->createAuthentication($applicationUser)->login(+ data: AuthenticationData::create()+ ->withUsername('wrong')+ ->withPassword($password),+ request: $this->createSimpleGetRequest(),+ response: $this->createMock(Response::class),+ );++ $this->assertFalse($result->isSuccess());+ $this->assertTrue($result->isFail());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testLoginBasicFailNoPassword(): void+ {+ $username = 'test';+ $password = 'hello';++ $this->createUser([+ User::FIELD_USER_NAME => $username,+ User::FIELD_PASSWORD => $password,+ ]);++ $applicationUser = $this->createMock(ApplicationUser::class);++ $applicationUser+ ->expects(self::never())+ ->method('setUser');++ $result = $this->createAuthentication($applicationUser)->login(+ data: AuthenticationData::create()+ ->withUsername($username),+ request: $this->createSimpleGetRequest(),+ response: $this->createMock(Response::class),+ );++ $this->assertTrue($result->isFail());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testLoginAuthTokenSuccess(): void+ {+ $username = 'test';+ $password = 'hello';++ $this->createUser([+ User::FIELD_USER_NAME => $username,+ User::FIELD_PASSWORD => $password,+ ]);++ $result = $this->createAuthentication()->login(+ data: AuthenticationData::create()+ ->withUsername($username)+ ->withPassword($password),+ request: $this->createSimpleGetRequest(+ headers: [+ HeaderKey::AUTHORIZATION => 'any',+ ],+ ),+ response: $this->createMock(Response::class),+ );++ $this->assertTrue($result->isSuccess());++ $token = $result->getUser()->get(User::FIELD_TOKEN);++ $this->assertNotNull($token);++ //++ $secret = $this->getTokenSecret($token);++ $this->assertNotNull($secret);++ $secondResult = $this->createAuthentication()->login(+ data: AuthenticationData::create()+ ->withUsername($username)+ ->withPassword($token),+ request: $this->createSimpleGetRequest(+ cookieParams: [+ self::COOKIE_AUTH_TOKEN_SECRET => $secret,+ ]+ ),+ response: $this->createMock(Response::class),+ );++ $this->assertTrue($secondResult->isSuccess());+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testLoginAuthTokenFailWrongSecret(): void+ {+ $username = 'test';+ $password = 'hello';++ $this->createUser([+ User::FIELD_USER_NAME => $username,+ User::FIELD_PASSWORD => $password,+ ]);++ $result = $this->createAuthentication()->login(+ data: AuthenticationData::create()+ ->withUsername($username)+ ->withPassword($password),+ request: $this->createSimpleGetRequest(+ headers: [+ HeaderKey::AUTHORIZATION => 'any',+ ],+ ),+ response: $this->createMock(Response::class),+ );++ $this->assertTrue($result->isSuccess());++ $token = $result->getUser()->get(User::FIELD_TOKEN);++ $this->assertNotNull($token);++ //++ $secondResult = $this->createAuthentication()->login(+ data: AuthenticationData::create()+ ->withUsername($username)+ ->withPassword($token),+ request: $this->createSimpleGetRequest(+ cookieParams: [+ self::COOKIE_AUTH_TOKEN_SECRET => 'wrong',+ ]+ ),+ response: $this->createMock(Response::class),+ );++ $this->assertFalse($secondResult->isSuccess());+ }++ private function createAuthentication(?ApplicationUser $applicationUser = null): Authentication+ {+ $applicationUser ??= $this->createMock(ApplicationUser::class);++ return $this->getInjectableFactory()->createWithBinding(+ Authentication::class,+ BindingContainerBuilder::create()+ ->bindInstance(ApplicationUser::class, $applicationUser)+ ->build(),+ );+ }++ /**+ * @param array<string, mixed> $headers+ */+ private function createSimpleGetRequest(+ array $headers = [],+ array $cookieParams = [],+ ): RequestWrapper {+ return $this->createRequest(+ method: Method::GET,+ headers: [+ HeaderKey::CREATE_TOKEN_SECRET => 'true',+ ...$headers,+ ],+ cookieParams: $cookieParams,+ );+ }++ private function getTokenSecret(string $token): ?string+ {+ $authToken = $this->getEntityManager()+ ->getRDBRepositoryByClass(AuthToken::class)+ ->where([AuthToken::FIELD_TOKEN => $token])+ ->findOne();++ return $authToken?->getSecret();+ }+}