Skip to content

EspoCRM – Open Source CRM Application

External account refactoring

Yurii9d7f66fbd81a
diff --git a/application/Espo/Controllers/ExternalAccount.php b/application/Espo/Controllers/ExternalAccount.php
index 22c82d196a..bfaa88cc4d 100644
--- a/application/Espo/Controllers/ExternalAccount.php
+++ b/application/Espo/Controllers/ExternalAccount.php
@@ -29,19 +29,16 @@
namespace Espo\Controllers;
+use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\NotFound;
-
use Espo\Entities\ExternalAccount as ExternalAccountEntity;
-use Espo\Entities\Integration as IntegrationEntity;
-use Espo\Services\ExternalAccount as Service;
-
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Controllers\RecordBase;
use Espo\Core\Record\ReadParams;
-
+use Espo\Tools\ExternalAccount\Service;
use stdClass;
class ExternalAccount extends RecordBase
@@ -55,74 +52,23 @@ class ExternalAccount extends RecordBase
public function getActionList(Request $request, Response $response): stdClass
{
- $integrations = $this->entityManager
- ->getRDBRepository(IntegrationEntity::ENTITY_TYPE)
- ->find();
-
- $list = [];
-
- foreach ($integrations as $entity) {
- if (
- $entity->get('enabled') &&
- $this->metadata->get('integrations.' . $entity->getId() .'.allowUserAccounts')
- ) {
- $id = $entity->getId();
-
- $userAccountAclScope = $this->metadata
- ->get(['integrations', $id, 'userAccountAclScope']);
-
- if ($userAccountAclScope) {
- if (!$this->acl->checkScope($userAccountAclScope)) {
- continue;
- }
- }
-
- $list[] = [
- 'id' => $id,
- ];
- }
- }
-
- return (object) [
- 'list' => $list
- ];
+ return $this->createService()->getList();
}
+ /**
+ * @throws BadRequest
+ * @throws Forbidden
+ */
public function getActionGetOAuth2Info(Request $request): ?stdClass
{
- $id = $request->getQueryParam('id');
-
- if ($id === null) {
- throw new BadRequest();
- }
-
- list($integration, $userId) = explode('__', $id);
+ $id = $request->getQueryParam('id') ?? throw new BadRequest();
- if ($this->user->getId() != $userId && !$this->user->isAdmin()) {
- throw new Forbidden();
- }
-
- $entity = $this->entityManager->getEntityById(IntegrationEntity::ENTITY_TYPE, $integration);
-
- if ($entity) {
- return (object) [
- 'clientId' => $entity->get('clientId'),
- 'redirectUri' => $this->config->get('siteUrl') . '?entryPoint=oauthCallback',
- 'isConnected' => $this->getExternalAccount()->ping($integration, $userId)
- ];
- }
-
- return null;
+ return $this->createService()->getActionGetOAuth2Info($id);
}
public function getActionRead(Request $request, Response $response): stdClass
{
- /** @var string $id */
- $id = $request->getRouteParam('id');
-
- if ($id === '') {
- throw new BadRequest();
- }
+ $id = $request->getRouteParam('id') ?: throw new BadRequest();
return $this->getRecordService()
->read($id, ReadParams::create())
@@ -131,55 +77,33 @@ class ExternalAccount extends RecordBase
public function putActionUpdate(Request $request, Response $response): stdClass
{
- /** @var string $id */
- $id = $request->getRouteParam('id');
+ $id = $request->getRouteParam('id') ?? throw new BadRequest();
$data = $request->getParsedBody();
- [, $userId] = explode('__', $id);
-
- if ($this->user->getId() !== $userId && !$this->user->isAdmin()) {
- throw new Forbidden();
- }
-
- if (isset($data->enabled) && !$data->enabled) {
- $data->data = null;
- }
-
- $entity = $this->entityManager->getEntityById(ExternalAccountEntity::ENTITY_TYPE, $id);
-
- if (!$entity) {
- throw new NotFound();
- }
-
- $entity->set($data);
-
- $this->entityManager->saveEntity($entity);
-
- return $entity->getValueMap();
+ return $this->createService()->update($id, $data);
}
+ /**
+ * @throws Forbidden
+ * @throws NotFound
+ * @throws Error
+ * @throws BadRequest
+ */
public function postActionAuthorizationCode(Request $request): bool
{
$data = $request->getParsedBody();
- $id = $data->id;
- $code = $data->code;
-
- list ($integration, $userId) = explode('__', $id);
-
- if ($this->user->getId() != $userId && !$this->user->isAdmin()) {
- throw new Forbidden();
- }
+ $id = $data->id ?? throw new BadRequest("No ID.");
+ $code = $data->code ?? throw new BadRequest("No code.");
- $this->getExternalAccount()->authorizationCode($integration, $userId, $code);
+ $this->createService()->authorizationCode($id, $code);
return true;
}
- private function getExternalAccount(): Service
+ private function createService(): Service
{
- /** @var Service */
- return $this->getRecordService();
+ return $this->injectableFactory->create(Service::class);
}
}
diff --git a/application/Espo/Core/Di/HookManagerSetter.php b/application/Espo/Core/Di/HookManagerSetter.php
index b8350c93bf..7691514807 100644
--- a/application/Espo/Core/Di/HookManagerSetter.php
+++ b/application/Espo/Core/Di/HookManagerSetter.php
@@ -31,6 +31,9 @@ namespace Espo\Core\Di;
use Espo\Core\HookManager;
+/**
+ * @phpstan-ignore-next-line method.unused
+ */
trait HookManagerSetter
{
/**
diff --git a/application/Espo/Core/ExternalAccount/Clients/OAuth2Abstract.php b/application/Espo/Core/ExternalAccount/Clients/OAuth2Abstract.php
index f7af33acfe..473f2b27d5 100644
--- a/application/Espo/Core/ExternalAccount/Clients/OAuth2Abstract.php
+++ b/application/Espo/Core/ExternalAccount/Clients/OAuth2Abstract.php
@@ -214,7 +214,6 @@ abstract class OAuth2Abstract implements IClient
* expiresAt: ?string,
* refreshToken: ?string,
* }
- * @throws Exception
*/
public function getAccessTokenFromAuthorizationCode(string $code)
{
diff --git a/application/Espo/Core/ExternalAccount/OAuth2/Client.php b/application/Espo/Core/ExternalAccount/OAuth2/Client.php
index db6a97823c..05e3c346b0 100644
--- a/application/Espo/Core/ExternalAccount/OAuth2/Client.php
+++ b/application/Espo/Core/ExternalAccount/OAuth2/Client.php
@@ -418,7 +418,6 @@ class Client
* contentType: string|false,
* header: string,
* }
- * @throws Exception
*/
public function getAccessToken($url, $grantType, array $params)
{
@@ -445,6 +444,10 @@ class Client
throw new LogicException("Bad auth type.");
}
- return $this->execute($url, $params, self::HTTP_METHOD_POST, $httpHeaders, self::REFRESH_TOKEN_TIMEOUT);
+ try {
+ return $this->execute($url, $params, self::HTTP_METHOD_POST, $httpHeaders, self::REFRESH_TOKEN_TIMEOUT);
+ } catch (Exception $e) {
+ throw new RuntimeException(previous: $e);
+ }
}
}
diff --git a/application/Espo/Entities/Integration.php b/application/Espo/Entities/Integration.php
index e03f3ac602..cc7a760443 100644
--- a/application/Espo/Entities/Integration.php
+++ b/application/Espo/Entities/Integration.php
@@ -81,6 +81,11 @@ class Integration extends Entity
$this->set(self::ATTR_DATA, $data);
}
+ public function setMultiple(array|stdClass $valueMap): static
+ {
+ return $this->set($valueMap);
+ }
+
public function set($attribute, $value = null): static
{
if (is_object($attribute)) {
diff --git a/application/Espo/Services/ExternalAccount.php b/application/Espo/Services/ExternalAccount.php
index 5be020a485..0ea57e98a2 100644
--- a/application/Espo/Services/ExternalAccount.php
+++ b/application/Espo/Services/ExternalAccount.php
@@ -30,124 +30,42 @@
namespace Espo\Services;
use Espo\Core\Record\ReadResult;
-use Espo\ORM\Entity;
-use Espo\Core\ExternalAccount\Clients\OAuth2Abstract;
-use Espo\Core\ExternalAccount\ClientManager;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Exceptions\NotFoundSilent;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Record\ReadParams;
-use Espo\Core\Di;
use Espo\Entities\ExternalAccount as ExternalAccountEntity;
-use Espo\Entities\Integration as IntegrationEntity;
+use Espo\Tools\ExternalAccount\OAuthService;
use Exception;
/**
* @extends Record<ExternalAccountEntity>
*/
-class ExternalAccount extends Record implements Di\HookManagerAware
+class ExternalAccount extends Record
{
- use Di\HookManagerSetter;
-
- /**
- * @throws NotFound
- * @throws Error
- */
- private function getClient(string $integration, string $id): ?object
- {
- /** @var IntegrationEntity|null $integrationEntity */
- $integrationEntity = $this->entityManager->getEntityById(IntegrationEntity::ENTITY_TYPE, $integration);
-
- if (!$integrationEntity) {
- throw new NotFound();
- }
-
- if (!$integrationEntity->get('enabled')) {
- throw new Error("$integration is disabled.");
- }
-
- return $this->injectableFactory
- ->create(ClientManager::class)
- ->create($integration, $id);
- }
-
- private function getExternalAccountEntity(string $integration, string $userId): ?ExternalAccountEntity
- {
- $id = $integration . '__' . $userId;
-
- /** @var ?ExternalAccountEntity */
- return $this->entityManager->getEntityById(ExternalAccountEntity::ENTITY_TYPE, $id);
- }
-
/**
* @return bool
- * @todo In v9.1. Move to Tools. Fix all usages.
+ * @deprecated As of v10.0. Use `Espo\Tools\OAuthService`.
+ * @todo Fix all usages.
+ * @todo Remove in v11.0.
*/
public function ping(string $integration, string $userId)
{
- try {
- $client = $this->getClient($integration, $userId);
-
- if ($client && method_exists($client, 'ping')) {
- /** @var bool */
- return $client->ping();
- }
- } catch (Exception) {}
-
- return false;
+ return $this->injectableFactory->create(OAuthService::class)->ping($integration, $userId);
}
/**
- * @return bool
* @throws NotFound
* @throws Error
* @throws Exception
- * @todo In v9.1. Return void. Move to Tools. Fix all usages.
+ * @deprecated As of v10.0. Use `Espo\Tools\OAuthService`.
+ * @todo Fix all usages.
+ * @todo Remove in v11.0.
*/
- public function authorizationCode(string $integration, string $userId, string $code)
+ public function authorizationCode(string $integration, string $userId, string $code): void
{
- $entity = $this->getExternalAccountEntity($integration, $userId);
-
- if (!$entity) {
- throw new NotFound();
- }
-
- $entity->set('enabled', true);
-
- $this->entityManager->saveEntity($entity);
-
- $client = $this->getClient($integration, $userId);
-
- if (!$client instanceof OAuth2Abstract) {
- throw new Error("Could not load client for $integration.");
- }
-
-
- $result = $client->getAccessTokenFromAuthorizationCode($code);
-
- if (empty($result) || empty($result['accessToken'])) {
- throw new Error("Could not get access token for $integration.");
- }
-
- $entity->clear('accessToken');
- $entity->clear('refreshToken');
- $entity->clear('tokenType');
- $entity->clear('expiresAt');
-
- foreach ($result as $name => $value) {
- $entity->set($name, $value);
- }
-
- $this->entityManager->saveEntity($entity);
-
- $this->hookManager->process('ExternalAccount', 'afterConnect', $entity, [
- 'integration' => $integration,
- 'userId' => $userId,
- 'code' => $code,
- ]);
-
- return true;
+ $this->injectableFactory->create(OAuthService::class)->authorizationCode($integration, $userId, $code);
}
public function read(string $id, ReadParams $params = new ReadParams()): ReadResult
diff --git a/application/Espo/Tools/ExternalAccount/OAuthService.php b/application/Espo/Tools/ExternalAccount/OAuthService.php
new file mode 100644
index 0000000000..df9dfe1caa
--- /dev/null
+++ b/application/Espo/Tools/ExternalAccount/OAuthService.php
@@ -0,0 +1,144 @@
+<?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\ExternalAccount;
+
+use Espo\Core\Exceptions\Error;
+use Espo\Core\Exceptions\NotFound;
+use Espo\Core\ExternalAccount\ClientManager;
+use Espo\Core\ExternalAccount\Clients\OAuth2Abstract;
+use Espo\Core\HookManager;
+use Espo\Entities\ExternalAccount;
+use Espo\Entities\Integration;
+use Espo\ORM\EntityManager;
+use Exception;
+use RuntimeException;
+
+/**
+ * @since 10.0.0
+ */
+class OAuthService
+{
+ public function __construct(
+ private EntityManager $entityManager,
+ private HookManager $hookManager,
+ private ClientManager $clientManager,
+ ) {}
+
+ /**
+ * @throws Error
+ * @throws NotFound
+ */
+ public function authorizationCode(string $integration, string $userId, string $code): void
+ {
+ $entity = $this->getExternalAccountEntity($integration, $userId);
+
+ if (!$entity) {
+ throw new NotFound();
+ }
+
+ $entity->setIsEnabled(true);
+
+ $this->entityManager->saveEntity($entity);
+
+ $client = $this->getClient($integration, $userId);
+
+ if (!$client instanceof OAuth2Abstract) {
+ throw new RuntimeException("Could not load client for $integration.");
+ }
+
+ $result = $client->getAccessTokenFromAuthorizationCode($code);
+
+ if (!$result || empty($result['accessToken'])) {
+ throw new Error("Could not get access token for $integration.");
+ }
+
+ $entity->clear('accessToken');
+ $entity->clear('refreshToken');
+ $entity->clear('tokenType');
+ $entity->clear('expiresAt');
+
+ foreach ($result as $name => $value) {
+ $entity->set($name, $value);
+ }
+
+ $this->entityManager->saveEntity($entity);
+
+ $this->hookManager->process('ExternalAccount', 'afterConnect', $entity, [
+ 'integration' => $integration,
+ 'userId' => $userId,
+ 'code' => $code,
+ ]);
+ }
+
+ public function ping(string $integration, string $userId): bool
+ {
+ try {
+ $client = $this->getClient($integration, $userId);
+
+ if (!$client) {
+ return false;
+ }
+
+ if (!$client instanceof OAuth2Abstract) {
+ throw new Exception("Could not load client for $integration.");
+ }
+
+ return $client->ping();
+ } catch (Exception) {}
+
+ return false;
+ }
+
+ /**
+ * @throws NotFound
+ * @throws Error
+ */
+ private function getClient(string $integration, string $id): ?object
+ {
+ $entity = $this->entityManager->getRDBRepositoryByClass(Integration::class)->getById($integration);
+
+ if (!$entity) {
+ throw new NotFound();
+ }
+
+ if (!$entity->isEnabled()) {
+ throw new Error("$integration is disabled.");
+ }
+
+ return $this->clientManager->create($integration, $id);
+ }
+
+ private function getExternalAccountEntity(string $integration, string $userId): ?ExternalAccount
+ {
+ $id = $integration . '__' . $userId;
+
+ return $this->entityManager->getRDBRepositoryByClass(ExternalAccount::class)->getById($id);
+ }
+}
diff --git a/application/Espo/Tools/ExternalAccount/Service.php b/application/Espo/Tools/ExternalAccount/Service.php
new file mode 100644
index 0000000000..a24cfb79a2
--- /dev/null
+++ b/application/Espo/Tools/ExternalAccount/Service.php
@@ -0,0 +1,165 @@
+<?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\ExternalAccount;
+
+use Espo\Core\Acl;
+use Espo\Core\Exceptions\Error;
+use Espo\Core\Exceptions\Forbidden;
+use Espo\Core\Exceptions\NotFound;
+use Espo\Core\Utils\Config\ApplicationConfig;
+use Espo\Core\Utils\Metadata;
+use Espo\Entities\ExternalAccount;
+use Espo\Entities\Integration;
+use Espo\Entities\User;
+use Espo\ORM\EntityManager;
+use stdClass;
+
+/**
+ * @since 10.0.0
+ */
+class Service
+{
+ public function __construct(
+ private Metadata $metadata,
+ private EntityManager $entityManager,
+ private Acl $acl,
+ private User $user,
+ private ApplicationConfig $config,
+ private OAuthService $oAuthService,
+ ) {}
+
+ /**
+ * @internal
+ */
+ public function getList(): stdClass
+ {
+ $integrations = $this->entityManager
+ ->getRDBRepositoryByClass(Integration::class)
+ ->find();
+
+ $list = [];
+
+ foreach ($integrations as $entity) {
+ if (
+ !$entity->isEnabled() ||
+ !$this->metadata->get("integrations.{$entity->getId()}.allowUserAccounts")
+ ) {
+ continue;
+ }
+
+ $id = $entity->getId();
+
+ $userAccountAclScope = $this->metadata->get(['integrations', $id, 'userAccountAclScope']);
+
+ if ($userAccountAclScope && !$this->acl->checkScope($userAccountAclScope)) {
+ continue;
+ }
+
+ $list[] = [
+ 'id' => $id,
+ ];
+ }
+
+ return (object) [
+ 'list' => $list
+ ];
+ }
+
+ /**
+ * @throws Forbidden
+ * @internal
+ */
+ public function getActionGetOAuth2Info(string $id): ?stdClass
+ {
+ [$integration, $userId] = explode('__', $id);
+
+ if ($this->user->getId() != $userId && !$this->user->isAdmin()) {
+ throw new Forbidden();
+ }
+
+ $entity = $this->entityManager->getRDBRepositoryByClass(Integration::class)->getById($integration);
+
+ if (!$entity) {
+ return null;
+ }
+
+ return (object) [
+ 'clientId' => $entity->get('clientId'),
+ 'redirectUri' => $this->config->getSiteUrl() . '?entryPoint=oauthCallback',
+ 'isConnected' => $this->oAuthService->ping($integration, $userId)
+ ];
+ }
+
+ /**
+ * @throws Forbidden
+ * @throws NotFound
+ */
+ public function update(string $id, stdClass $data): stdClass
+ {
+ [, $userId] = explode('__', $id);
+
+ if ($this->user->getId() !== $userId && !$this->user->isAdmin()) {
+ throw new Forbidden();
+ }
+
+ if (isset($data->enabled) && !$data->enabled) {
+ $data->data = null;
+ }
+
+ $entity = $this->entityManager->getRDBRepositoryByClass(ExternalAccount::class)->getById($id);
+
+ if (!$entity) {
+ throw new NotFound();
+ }
+
+ $entity->setMultiple($data);
+
+ $this->entityManager->saveEntity($entity);
+
+ return $entity->getValueMap();
+ }
+
+ /**
+ * @internal
+ * @throws Forbidden
+ * @throws NotFound
+ * @throws Error
+ */
+ public function authorizationCode(string $id, string $code): void
+ {
+ [$integration, $userId] = explode('__', $id);
+
+ if ($this->user->getId() !== $userId && !$this->user->isAdmin()) {
+ throw new Forbidden();
+ }
+
+ $this->oAuthService->authorizationCode($integration, $userId, $code);
+ }
+}