EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
Set user after 2fa, tests
Yurii88753251ff3a
diff --git a/application/Espo/Core/Authentication/Authentication.php b/application/Espo/Core/Authentication/Authentication.phpindex e70ddbf3a0..6ca04caea0 100644--- a/application/Espo/Core/Authentication/Authentication.php+++ b/application/Espo/Core/Authentication/Authentication.php@@ -30,6 +30,7 @@namespace Espo\Core\Authentication;use Espo\Core\Authentication\Repository\UserRepository;+use Espo\Core\Authentication\TwoFactor\MethodProvider as TwoFactorMethodProvider;use Espo\Core\Exceptions\Forbidden;use Espo\Core\Exceptions\NotFound;use Espo\Core\Name\Field;@@ -58,7 +59,6 @@ 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;@@ -88,7 +88,7 @@ class Authenticationprivate MethodProvider $methodProvider,private Util $util,private LanguageProxy $language,- private UserDataProvider $userDataProvider,+ private TwoFactorMethodProvider $twoFactorMethodProvider,private UserRepository $userRepository,private AuthLogRecordRepository $authLogRecordRepository,) {}@@ -183,10 +183,6 @@ class Authenticationreturn $this->processFail(Result::fail($anotherUserFailReason), $data, $request);}- if ($result->isSuccess()) {- $this->applicationUser->setUser($loggedUser);- }-if ($this->toProcessTwoFactor($result, $authToken)) {$result = $this->processTwoFactor($result, $request);@@ -195,6 +191,10 @@ class Authentication}}+ if ($result->isSuccess()) {+ $this->applicationUser->setUser($loggedUser);+ }+try {$this->hookManager->processOnLogin($result, $data, $request);} catch (Forbidden $e) {@@ -374,7 +374,7 @@ class Authenticationthrow new RuntimeException("No user.");}- $method = $this->getUser2FAMethod($user);+ $method = $this->twoFactorMethodProvider->get($user->getId());if (!$method) {return $result;@@ -385,31 +385,6 @@ class Authenticationreturn $login->login($result, $request);}- private function getUser2FAMethod(User $user): ?string- {- $userData = $this->userDataProvider->get($user->getId());-- if (!$userData) {- return null;- }-- if (!$userData->getAuth2FA()) {- return null;- }-- $method = $userData->getAuth2FAMethod();-- if (!$method) {- return null;- }-- if (!in_array($method, $this->configDataProvider->getTwoFactorMethodList())) {- return null;- }-- return $method;- }-private function createAuthToken(User $user, Request $request, Response $response): AuthToken{$createSecret =diff --git a/application/Espo/Core/Authentication/TwoFactor/MethodProvider.php b/application/Espo/Core/Authentication/TwoFactor/MethodProvider.phpnew file mode 100644index 0000000000..4bfb6278f1--- /dev/null+++ b/application/Espo/Core/Authentication/TwoFactor/MethodProvider.php@@ -0,0 +1,72 @@+<?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\TwoFactor;++use Espo\Core\Authentication\ConfigDataProvider;+use Espo\Tools\User\UserDataProvider;++/**+ * @internal+ */+class MethodProvider+{+ public function __construct(+ private UserDataProvider $userDataProvider,+ private ConfigDataProvider $configDataProvider,+ ) {}++ /**+ * Obtain 2FA method for a user.+ */+ public function get(string $userId): ?string+ {+ $userData = $this->userDataProvider->get($userId);++ if (!$userData) {+ return null;+ }++ if (!$userData->getAuth2FA()) {+ return null;+ }++ $method = $userData->getAuth2FAMethod();++ if (!$method) {+ return null;+ }++ if (!in_array($method, $this->configDataProvider->getTwoFactorMethodList())) {+ return null;+ }++ return $method;+ }+}diff --git a/tests/integration/Espo/Core/Authentication/AuthenticationTest.php b/tests/integration/Espo/Core/Authentication/AuthenticationTest.phpindex 7c1935d94e..e812b769e1 100644--- a/tests/integration/Espo/Core/Authentication/AuthenticationTest.php+++ b/tests/integration/Espo/Core/Authentication/AuthenticationTest.php@@ -29,6 +29,7 @@namespace integration\Espo\Core\Authentication;+use Closure;use Espo\Core\Api\Method;use Espo\Core\Api\RequestWrapper;use Espo\Core\Api\Response;@@ -37,6 +38,10 @@ use Espo\Core\Authentication\Authentication;use Espo\Core\Authentication\AuthenticationData;use Espo\Core\Authentication\AuthToken\Manager;use Espo\Core\Authentication\HeaderKey;+use Espo\Core\Authentication\Result;+use Espo\Core\Authentication\TwoFactor\Login;+use Espo\Core\Authentication\TwoFactor\LoginFactory as TwoFactorLoginFactory;+use Espo\Core\Authentication\TwoFactor\MethodProvider as TwoFactorMethodProvider;use Espo\Core\Binding\BindingContainerBuilder;use Espo\Entities\AuthToken;use Espo\Entities\User;@@ -392,16 +397,145 @@ class AuthenticationTest extends BaseTestCase$this->assertTrue($secondResult->isSuccess());}- private function createAuthentication(?ApplicationUser $applicationUser = null): Authentication+ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testLogin2Fa(): void{- $applicationUser ??= $this->createMock(ApplicationUser::class);+ $this->setConfigParams([+ 'auth2FA' => true,+ 'auth2FAMethodList' => ['TestMethod'],+ ]);++ [$username, $password, $user] = $this->prepareTestUser();++ $applicationUser = $this->createMock(ApplicationUser::class);++ $applicationUser+ ->expects(self::never())+ ->method('setUser');++ $twoFactorLogin = $this->createMock(Login::class);++ $twoFactorLogin+ ->expects(self::once())+ ->method('login')+ ->with(+ $this->callback(function (Result $result) use ($user) {+ return $result->getUser()->getId() === $user->getId();+ })+ )+ ->willReturn(+ Result::secondStepRequired(+ user: $user,+ data: Result\Data::create(),+ )+ );++ $authentication = $this->createAuthentication(+ applicationUser: $applicationUser,+ twoFactorLogin: $twoFactorLogin,+ twoFactorMethod: 'TestMethod',+ userId: $user->getId(),+ );++ $result = $authentication->login(+ data: AuthenticationData::create()+ ->withUsername($username)+ ->withPassword($password),+ request: $this->createSimpleGetRequest(),+ response: $this->createMock(Response::class)+ );++ $this->assertFalse($result->isSuccess());+ $this->assertFalse($result->isFail());+ $this->assertTrue($result->isSecondStepRequired());++ $this->assertNull(+ $this->getEntityManager()+ ->getRDBRepositoryByClass(AuthToken::class)+ ->where([AuthToken::ATTR_USER_ID => $user->getId()])+ ->findOne()+ );++ //++ $applicationUser = $this->createMock(ApplicationUser::class);- return $this->getInjectableFactory()->createWithBinding(- Authentication::class,- BindingContainerBuilder::create()- ->bindInstance(ApplicationUser::class, $applicationUser)- ->build(),+ $applicationUser+ ->expects(self::once())+ ->method('setUser');++ $twoFactorLogin = $this->createMock(Login::class);++ $twoFactorLogin+ ->expects(self::once())+ ->method('login')+ ->with(+ $this->callback(function (Result $result) use ($user) {+ return $result->getUser()->getId() === $user->getId();+ })+ )+ ->willReturnCallback(function (Result $result) {+ return $result;+ });++ $authentication = $this->createAuthentication(+ applicationUser: $applicationUser,+ twoFactorLogin: $twoFactorLogin,+ twoFactorMethod: 'TestMethod',+ userId: $user->getId(),+ );++ $result = $authentication->login(+ data: AuthenticationData::create()+ ->withUsername($username)+ ->withPassword($password),+ request: $this->createSimpleGetRequest(),+ response: $this->createMock(Response::class));++ $this->assertTrue($result->isSuccess());+ $this->assertFalse($result->isSecondStepRequired());+ }++ private function createAuthentication(+ ?ApplicationUser $applicationUser = null,+ ?Login $twoFactorLogin = null,+ ?string $twoFactorMethod = null,+ ?string $userId = null,+ ): Authentication {++ $applicationUser ??= $this->createMock(ApplicationUser::class);++ $builder = BindingContainerBuilder::create()+ ->bindInstance(ApplicationUser::class, $applicationUser);++ if ($twoFactorLogin) {+ $twoFactorLoginFactory = $this->createMock(TwoFactorLoginFactory::class);++ $twoFactorLoginFactory+ ->expects(self::once())+ ->method('create')+ ->with($twoFactorMethod)+ ->willReturn($twoFactorLogin);++ $builder->bindInstance(TwoFactorLoginFactory::class, $twoFactorLoginFactory);+ }++ if ($userId && $twoFactorMethod) {+ $twoFactorMethodProvider = $this->createMock(TwoFactorMethodProvider::class);++ $twoFactorMethodProvider+ ->expects(self::once())+ ->method('get')+ ->with($userId)+ ->willReturn($twoFactorMethod);++ $builder->bindInstance(TwoFactorMethodProvider::class, $twoFactorMethodProvider);+ }++ return $this->getInjectableFactory()->createWithBinding(Authentication::class, $builder->build());}/**@@ -481,18 +615,18 @@ class AuthenticationTest extends BaseTestCase}/**- * @return array{string, string}+ * @return array{string, string, User}*/private function prepareTestUser(bool $isActive = true): array{[$username, $password] = $this->prepareUsernamePassword();- $this->createUser([+ $user = $this->createUser([User::FIELD_USER_NAME => $username,User::FIELD_PASSWORD => $password,User::FIELD_IS_ACTIVE => $isActive,]);- return [$username, $password];+ return [$username, $password, $user];}}