repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/Repository/ReadImageFolderRepositoryInterface.php | centreon/src/Core/Media/Application/Repository/ReadImageFolderRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Media\Domain\Model\ImageFolder\ImageFolder;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadImageFolderRepositoryInterface
{
/**
* @param int[] $folderIds
*
* @throws RepositoryException
*
* @return int[]
*/
public function findExistingFolderIds(array $folderIds): array;
/**
* Method dedicated and specific to Resource Access Management
*
* @param int[] $folderIds
*
* @throws RepositoryException
*
* @return ResourceNamesById
*/
public function findFolderNames(array $folderIds): ResourceNamesById;
/**
* @param RequestParametersInterface $requestParameters
*
* @throws RepositoryException
*
* @return ImageFolder[]
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array;
/**
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
*
* @throws RepositoryException
*
* @return ImageFolder[]
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array;
/**
* Checks if the user through the AccessGroups has at least one Resource Access
* giving access to all media folders
*
* @param AccessGroup[] $accessGroups
*
* @throws RepositoryException
*
* @return bool
*/
public function hasAccessToAllImageFolders(array $accessGroups): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/Repository/WriteMediaRepositoryInterface.php | centreon/src/Core/Media/Application/Repository/WriteMediaRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Application\Repository;
use Core\Media\Domain\Model\Media;
use Core\Media\Domain\Model\NewMedia;
interface WriteMediaRepositoryInterface
{
/**
* @param NewMedia $media
*
* @throws \Throwable
*
* @return int
*/
public function add(NewMedia $media): int;
/**
* @param Media $media
*
* @throws \Throwable
*/
public function delete(Media $media): void;
/**
* @param Media $media
*
* @throws \Throwable
*/
public function update(Media $media): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Application/Repository/ReadMediaRepositoryInterface.php | centreon/src/Core/Media/Application/Repository/ReadMediaRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Application\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Media\Domain\Model\Media;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
interface ReadMediaRepositoryInterface
{
/**
* Indicates whether the media exists using its path.
*
* @param string $path (ex: /logos/centreon_logo.png)
*
* @throws \Throwable
*
* @return bool
*/
public function existsByPath(string $path): bool;
/**
* @throws \Throwable
*
* @return \Traversable<int, Media>&\Countable
*/
public function findAll(): \Traversable&\Countable;
/**
* @param RequestParametersInterface $requestParameters
*
* @throws RepositoryException
*
* @return \Traversable<int, Media>
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): \Traversable;
/**
* @param RequestParametersInterface $requestParameters
* @param AccessGroup[] $accessGroups
*
* @throws RepositoryException
*
* @return \Traversable<int, Media>
*/
public function findByRequestParametersAndAccessGroups(RequestParametersInterface $requestParameters, array $accessGroups): \Traversable;
/**
* @param int $mediaId
*
* @throws \Throwable
*
* @return Media|null
*/
public function findById(int $mediaId): ?Media;
/**
* Return the medias by their ids.
*
* @param int[] $mediaIds
*
* @throws \Throwable
*
* @return array<int,Media>
*/
public function findByIds(array $mediaIds): array;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Domain/Model/NewMedia.php | centreon/src/Core/Media/Domain/Model/NewMedia.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
class NewMedia
{
private ?string $comment = null;
/**
* @param string $filename
* @param string $directory
* @param string $data
*
* @throws AssertionFailedException
*/
public function __construct(private string $filename, private string $directory, private string $data)
{
$this->filename = trim($this->filename);
Assertion::notEmptyString($this->filename, 'NewMedia::filename');
$this->filename = str_replace(' ', '_', $this->filename);
$this->directory = str_replace(' ', '', $this->directory);
Assertion::notEmptyString($this->directory, 'NewMedia::directory');
Assertion::regex($this->directory, '/^[a-zA-Z0-9_-]+$/', 'NewMedia::directory');
}
public function setFilename(string $filename): void
{
$this->filename = $filename;
}
public function getFilename(): string
{
return $this->filename;
}
public function setDirectory(string $directory): void
{
$this->directory = $directory;
}
public function getDirectory(): string
{
return $this->directory;
}
public function setData(string $data): void
{
$this->data = $data;
}
public function getData(): string
{
return $this->data;
}
public function setComment(?string $comment): void
{
$this->comment = $comment !== null ? trim($comment) : null;
}
public function getComment(): ?string
{
return $this->comment;
}
/**
* @param Media $media
*
* @throws AssertionFailedException
*
* @return NewMedia
*/
public static function createFromMedia(Media $media): self
{
$newMedia = new self(
$media->getFilename(),
$media->getDirectory(),
$media->getData() ?? '',
);
$newMedia->setComment($media->getComment());
return $newMedia;
}
public function hash(): string
{
return md5($this->data);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Domain/Model/Media.php | centreon/src/Core/Media/Domain/Model/Media.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\Comparable;
use Core\Common\Domain\Identifiable;
class Media implements Comparable, Identifiable
{
/**
* @param int $id
* @param string $filename
* @param string $directory
* @param string|null $comment
* @param string|null $data
*
* @throws AssertionFailedException
*/
public function __construct(
readonly private int $id,
private string $filename,
private string $directory,
private ?string $comment,
private ?string $data,
) {
Assertion::positiveInt($this->id, 'Media::id');
$this->filename = trim($this->filename);
Assertion::notEmptyString($this->filename, 'Media::filename');
$this->filename = str_replace(' ', '_', $this->filename);
$this->directory = str_replace(' ', '', $this->directory);
Assertion::notEmptyString($this->directory, 'Media::directory');
if ($this->comment !== null) {
$this->comment = trim($this->comment);
}
Assertion::regex($this->directory, '/^[a-zA-Z0-9_-]+$/', 'Media::directory');
}
public function getId(): int
{
return $this->id;
}
public function getFilename(): string
{
return $this->filename;
}
public function getDirectory(): string
{
return $this->directory;
}
public function getData(): ?string
{
return $this->data;
}
public function getComment(): ?string
{
return $this->comment;
}
/**
* @return string (ex: directory/filename)
*/
public function getRelativePath(): string
{
return $this->directory . DIRECTORY_SEPARATOR . $this->filename;
}
public function hash(): ?string
{
return $this->data !== null ? md5($this->data) : null;
}
public function isEqual(object $object): bool
{
return $object instanceof self && $object->getEqualityHash() === $this->getEqualityHash();
}
public function getEqualityHash(): string
{
return md5($this->getRelativePath());
}
public function setData(?string $data): self
{
$this->data = $data;
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Domain/Model/ImageFolder/ImageFolderId.php | centreon/src/Core/Media/Domain/Model/ImageFolder/ImageFolderId.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Domain\Model\ImageFolder;
use Webmozart\Assert\Assert;
final readonly class ImageFolderId
{
public function __construct(
public int $value,
) {
Assert::positiveInteger($value);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Domain/Model/ImageFolder/ImageFolderName.php | centreon/src/Core/Media/Domain/Model/ImageFolder/ImageFolderName.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Domain\Model\ImageFolder;
use Webmozart\Assert\Assert;
final readonly class ImageFolderName
{
public function __construct(
public string $value,
) {
Assert::lengthBetween($value, 1, 255);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Domain/Model/ImageFolder/ImageFolderDescription.php | centreon/src/Core/Media/Domain/Model/ImageFolder/ImageFolderDescription.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Domain\Model\ImageFolder;
use Webmozart\Assert\Assert;
final readonly class ImageFolderDescription
{
public function __construct(
public string $value,
) {
Assert::minLength($value, 1);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Domain/Model/ImageFolder/ImageFolder.php | centreon/src/Core/Media/Domain/Model/ImageFolder/ImageFolder.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Domain\Model\ImageFolder;
final class ImageFolder
{
private ?ImageFolderName $alias = null;
private ?ImageFolderDescription $description = null;
public function __construct(
private ?ImageFolderId $id,
private ImageFolderName $name,
) {
}
public function id(): ImageFolderId
{
if (! $this->id instanceof ImageFolderId) {
throw new \RuntimeException(
\sprintf('Id of "%s" is not defined. Maybe it has not been inserted in database yet?', self::class)
);
}
return $this->id;
}
public function alias(): ?ImageFolderName
{
return $this->alias;
}
public function description(): ?ImageFolderDescription
{
return $this->description;
}
public function setDescription(?ImageFolderDescription $description): self
{
$this->description = $description;
return $this;
}
public function setAlias(?ImageFolderName $alias): self
{
$this->alias = $alias;
return $this;
}
public function name(): ImageFolderName
{
return $this->name;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Repository/ApiReadMediaRepository.php | centreon/src/Core/Media/Infrastructure/Repository/ApiReadMediaRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\Repository\ApiCallIterator;
use Core\Common\Infrastructure\Repository\ApiRepositoryTrait;
use Core\Media\Application\Repository\ReadMediaRepositoryInterface;
use Core\Media\Domain\Model\Media;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class ApiReadMediaRepository implements ReadMediaRepositoryInterface
{
use ApiRepositoryTrait;
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly RouterInterface $router,
private readonly LoggerInterface $logger,
) {
}
/**
* @inheritDoc
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): \Traversable {
throw new RepositoryException('Not yet implemented');
}
/**
* @inheritDoc
*/
public function findById(int $mediaId): ?Media
{
throw new RepositoryException('Not yet implemented');
}
/**
* @inheritDoc
*/
public function findByIds(array $mediaIds): array
{
throw new RepositoryException('Not yet implemented');
}
/**
* @inheritDoc
*/
public function existsByPath(string $path): bool
{
throw new RepositoryException('Not yet implemented');
}
/**
* @inheritDoc
*/
public function findAll(): \Traversable&\Countable
{
$apiEndpoint = $this->router->generate('FindMedias');
$options = [
'verify_peer' => true,
'verify_host' => true,
'timeout' => $this->timeout,
'headers' => ['X-AUTH-TOKEN: ' . $this->authenticationToken],
];
if ($this->proxy !== null) {
$options['proxy'] = $this->proxy;
$this->logger->info('Getting media using proxy');
}
$debugOptions = $options;
unset($debugOptions['headers'][0]);
$this->logger->debug('Connexion configuration', [
'url' => $apiEndpoint,
'options' => $debugOptions,
]);
return new ApiCallIterator(
$this->httpClient,
$this->url . $apiEndpoint,
$options,
$this->maxItemsByRequest,
$this->createMedia(...),
$this->logger
);
}
/**
* @inheritDoc
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): \Traversable
{
throw new RepositoryException('Not yet implemented');
}
/**
* @param array{id: int, filename: string, directory: string} $data
*
* @throws AssertionFailedException
*
* @return Media
*/
private function createMedia(array $data): Media
{
return new Media(
$data['id'],
(string) $data['filename'],
(string) $data['directory'],
null,
null
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Repository/FileWriteMediaRepository.php | centreon/src/Core/Media/Infrastructure/Repository/FileWriteMediaRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Repository;
use Core\Common\Infrastructure\Repository\FileDataStoreEngine;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Media\Domain\Model\Media;
use Core\Media\Domain\Model\NewMedia;
class FileWriteMediaRepository implements WriteMediaRepositoryInterface
{
public function __construct(readonly private FileDataStoreEngine $engine)
{
$this->engine->throwsException(true);
}
/**
* {@inheritDoc}
*
* @return int Returns the bytes written
*/
public function add(NewMedia $media): int
{
$status = $this->engine->addFile(
$media->getDirectory() . DIRECTORY_SEPARATOR . $media->getFilename(),
$media->getData()
);
if ($status === false) {
throw new \Exception($this->engine->getLastError());
}
return $status;
}
/**
* {@inheritDoc}
*/
public function update(Media $media): void
{
if (
$media->getData() === null
|| $media->getData() === ''
) {
throw new \Exception('File content cannot be empty on update');
}
if (! $this->engine->addFile(
$media->getDirectory() . DIRECTORY_SEPARATOR . $media->getFilename(),
$media->getData()
)
) {
throw new \Exception($this->engine->getLastError());
}
}
/**
* @inheritDoc
*/
public function delete(Media $media): void
{
$this->engine->deleteFromFileSystem($media->getDirectory() . DIRECTORY_SEPARATOR . $media->getFilename());
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Repository/DbWriteMediaRepository.php | centreon/src/Core/Media/Infrastructure/Repository/DbWriteMediaRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Repository;
use Centreon\Infrastructure\DatabaseConnection;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Media\Domain\Model\Media;
use Core\Media\Domain\Model\NewMedia;
class DbWriteMediaRepository extends AbstractRepositoryRDB implements WriteMediaRepositoryInterface
{
/**
* @param DatabaseConnection $db
*/
public function __construct(DatabaseConnection $db)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function update(Media $media): void
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$directoryId = $this->findDirectoryByName($media->getDirectory());
if ($directoryId === null) {
throw new \Exception('Directory linked to the media not found');
}
$this->unlinkMediaToDirectory($media, $directoryId);
$this->deleteMedia($media);
$this->db->commit();
} catch (\Throwable $ex) {
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function delete(Media $media): void
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$directoryId = $this->findDirectoryByName($media->getDirectory());
if ($directoryId === null) {
throw new \Exception('Directory linked to the media not found');
}
$this->unlinkMediaToDirectory($media, $directoryId);
$this->deleteMedia($media);
$this->db->commit();
} catch (\Throwable $ex) {
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
}
/**
* @inheritDoc
*/
public function add(NewMedia $media): int
{
$alreadyInTransaction = $this->db->inTransaction();
if (! $alreadyInTransaction) {
$this->db->beginTransaction();
}
try {
$mediaId = $this->addMedia($media);
$directoryId = $this->findDirectoryByName($media->getDirectory())
?? $this->addDirectory($media->getDirectory());
$this->linkMediaToDirectory($mediaId, $directoryId);
} catch (\Throwable $ex) {
if (! $alreadyInTransaction) {
$this->db->rollBack();
}
throw $ex;
}
return $mediaId;
}
private function deleteMedia(Media $media): void
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.view_img WHERE img_id = :imageId
SQL
)
);
$statement->bindValue(':imageId', $media->getId(), \PDO::PARAM_INT);
$statement->execute();
}
private function unlinkMediaToDirectory(Media $media, int $directoryId): void
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
DELETE FROM `:db`.view_img_dir_relation
WHERE img_img_id = :imageId AND dir_dir_parent_id = :directoryId
SQL
)
);
$statement->bindValue(':imageId', $media->getId(), \PDO::PARAM_INT);
$statement->bindValue(':directoryId', $directoryId, \PDO::PARAM_INT);
$statement->execute();
}
/**
* @param NewMedia $media
*
* @throws \PDOException
*
* @return int
*/
private function addMedia(NewMedia $media): int
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`view_img`
(`img_name`,`img_path`,`img_comment`)
VALUES (:name, :path, :comments)
SQL
)
);
$fileInfo = explode('.', $media->getFilename());
$statement->bindValue(':name', $fileInfo[0]);
$statement->bindValue(':path', $media->getFilename());
$statement->bindValue(':comments', $media->getComment());
$statement->execute();
return (int) $this->db->lastInsertId();
}
private function findDirectoryByName(string $directory): ?int
{
$statement = $this->db->prepare(
$this->translateDbName('SELECT `dir_id` FROM `:db`.`view_img_dir` WHERE `dir_name` = :name')
);
$statement->bindValue(':name', $directory);
$statement->execute();
return ($id = $statement->fetchColumn()) !== false
? (int) $id
: null;
}
/**
* @param string $directory
*
* @throws \PDOException
*
* @return int
*/
private function addDirectory(string $directory): int
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`view_img_dir`
(`dir_name`,`dir_alias`)
VALUES (:name, :alias)
SQL
)
);
$statement->bindValue(':name', $directory);
$statement->bindValue(':alias', $directory);
$statement->execute();
return (int) $this->db->lastInsertId();
}
/**
* @param int $mediaId
* @param int $directory
*
* @throws \PDOException
*/
private function linkMediaToDirectory(int $mediaId, int $directory): void
{
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
INSERT INTO `:db`.`view_img_dir_relation`
(`img_img_id`,`dir_dir_parent_id`)
VALUES (:media_id, :directory_id)
SQL
)
);
$statement->bindValue(':media_id', $mediaId, \PDO::PARAM_INT);
$statement->bindValue(':directory_id', $directory, \PDO::PARAM_INT);
$statement->execute();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Repository/ApiWriteMediaRepository.php | centreon/src/Core/Media/Infrastructure/Repository/ApiWriteMediaRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\Repository\RepositoryException;
use Core\Common\Infrastructure\Repository\ApiRepositoryTrait;
use Core\Common\Infrastructure\Repository\ApiResponseTrait;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Media\Domain\Model\Media;
use Core\Media\Domain\Model\NewMedia;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class ApiWriteMediaRepository implements WriteMediaRepositoryInterface
{
use LoggerTrait;
use ApiRepositoryTrait;
use ApiResponseTrait;
public function __construct(readonly private HttpClientInterface $httpClient)
{
}
/**
* @inheritDoc
*/
public function update(Media $media): void
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function delete(Media $media): void
{
throw RepositoryException::notYetImplemented();
}
/**
* @inheritDoc
*/
public function add(NewMedia $media): int
{
$apiEndpoint = $this->url . '/api/latest/configuration/medias';
$options = [
'verify_peer' => true,
'verify_host' => true,
'timeout' => $this->timeout,
];
if ($this->proxy !== null) {
$options['proxy'] = $this->proxy;
$this->info('Adding media using proxy');
}
$this->debug('Connexion configuration', [
'url' => $apiEndpoint,
'options' => $options,
]);
$stream = fopen('php://memory', 'r+');
if ($stream === false) {
throw new \Exception('Impossible to create resource on php://memory');
}
fwrite($stream, $media->getData());
rewind($stream);
$formFields = [
'data' => new DataPart($stream, $media->getFilename(), 'multipart/form-data'),
'directory' => $media->getDirectory(),
];
$formData = new FormDataPart($formFields);
$options['headers'] = $formData->getPreparedHeaders()->toArray();
$options['headers'][] = 'X-AUTH-TOKEN: ' . $this->authenticationToken;
$options['body'] = $formData->bodyToString();
/** @var array{result: array<int, array{id: int}>, errors: array<int, array{reason: string}>} $response */
$response = $this->getResponseOrFail($this->httpClient->request('POST', $apiEndpoint, $options));
if (isset($response['errors'][0]['reason'])) {
throw new \Exception($response['errors'][0]['reason']);
}
return (int) $response['result'][0]['id'];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Repository/DbReadMediaRepository.php | centreon/src/Core/Media/Infrastructure/Repository/DbReadMediaRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\Repository\AbstractRepositoryRDB;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Media\Application\Repository\ReadMediaRepositoryInterface;
use Core\Media\Domain\Model\Media;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use Psr\Log\LoggerInterface;
/**
* @phpstan-type _Media array{
* img_id: int,
* img_path: string,
* dir_name: string,
* img_comment: string,
* }
*/
class DbReadMediaRepository extends AbstractRepositoryRDB implements ReadMediaRepositoryInterface
{
use SqlMultipleBindTrait;
private const MAX_ITEMS_BY_REQUEST = 100;
public function __construct(DatabaseConnection $db, readonly private LoggerInterface $logger)
{
$this->db = $db;
}
/**
* @inheritDoc
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): \Traversable {
try {
if ($accessGroups === []) {
return new \EmptyIterator();
}
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
[$bindValues, $bindQuery] = $this->createMultipleBindQuery($accessGroupIds, ':access_group_id');
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'id' => 'img_id',
'name' => 'img_path',
'directory' => 'dir_name',
]);
$request = <<<SQL_WRAP
SELECT SQL_CALC_FOUND_ROWS
`img`.img_id,
`img`.img_path,
`img`.img_comment,
`dir`.dir_name
FROM `:db`.`view_img` img
INNER JOIN `:db`.`view_img_dir_relation` rel
ON rel.img_img_id = img.img_id
INNER JOIN `:db`.`view_img_dir` dir
ON dir.dir_id = rel.dir_dir_parent_id
INNER JOIN `:db`.acl_resources_image_folder_relations amdr
ON amdr.dir_id = dir.dir_id
INNER JOIN `:db`.acl_res_group_relations argr
ON argr.acl_res_id = amdr.acl_res_id
AND argr.acl_group_id IN ({$bindQuery})
SQL_WRAP;
$searchRequest = $sqlTranslator->translateSearchParameterToSql();
if ($searchRequest !== null) {
$request .= $searchRequest;
}
// Handle sort
$sortRequest = $sqlTranslator->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY img_id';
$request .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
/** @var int $type */
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
foreach ($bindValues as $bindKey => $bindValue) {
$statement->bindValue($bindKey, $bindValue, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
return new class ($statement, $this->createMedia(...)) implements \IteratorAggregate {
public function __construct(
readonly private \PDOStatement $statement,
readonly private \Closure $factory,
) {
}
public function getIterator(): \Traversable
{
foreach ($this->statement as $result) {
yield ($this->factory)($result);
}
}
};
} catch (\Exception $e) {
throw new RepositoryException(
message: 'An error occurred while fetching media by request parameters and access groups.',
context: [
'request_parameters' => $requestParameters->toArray(),
'access_groups' => $accessGroupIds,
],
previous: $e,
);
}
}
/**
* @inheritDoc
*/
public function findById(int $mediaId): ?Media
{
$request = <<<'SQL'
SELECT
`img`.img_id,
`img`.img_path,
`img`.img_comment,
`dir`.dir_name
FROM `:db`.`view_img` img
INNER JOIN `:db`.`view_img_dir_relation` rel
ON rel.img_img_id = img.img_id
INNER JOIN `:db`.`view_img_dir` dir
ON dir.dir_id = rel.dir_dir_parent_id
WHERE `img`.img_id = :mediaId
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindValue(':mediaId', $mediaId, \PDO::PARAM_INT);
$statement->execute();
/** @var _Media|false */
$record = $statement->fetch(\PDO::FETCH_ASSOC);
if ($record === false) {
return null;
}
return $this->createMedia($record);
}
/**
* @inheritDoc
*/
public function findByIds(array $mediaIds): array
{
if ($mediaIds === []) {
return [];
}
[$bindValues, $bindQuery] = $this->createMultipleBindQuery(
$mediaIds,
':mediaId_',
);
$request = <<<SQL
SELECT
`img`.img_id,
`img`.img_path,
`img`.img_comment,
`dir`.dir_name
FROM `:db`.`view_img` img
INNER JOIN `:db`.`view_img_dir_relation` rel
ON rel.img_img_id = img.img_id
INNER JOIN `:db`.`view_img_dir` dir
ON dir.dir_id = rel.dir_dir_parent_id
WHERE `img`.img_id IN ({$bindQuery})
SQL;
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($bindValues as $key => $value) {
$statement->bindValue($key, $value, \PDO::PARAM_INT);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$result = [];
foreach ($statement as $record) {
/** @var _Media $record */
$result[$record['img_id']] = $this->createMedia($record);
}
return $result;
}
/**
* @inheritDoc
*/
public function existsByPath(string $path): bool
{
$pathInfo = pathInfo($path);
if ($path === '' || $pathInfo['filename'] === '' || empty($pathInfo['dirname'])) {
return false;
}
$statement = $this->db->prepare(
$this->translateDbName(
<<<'SQL'
SELECT 1
FROM `:db`.`view_img` img
INNER JOIN `:db`.`view_img_dir_relation` rel
ON rel.img_img_id = img.img_id
INNER JOIN `:db`.`view_img_dir` dir
ON dir.dir_id = rel.dir_dir_parent_id
WHERE img_path = :media_name
AND dir.dir_name = :media_path
SQL
)
);
$statement->bindValue(':media_name', $pathInfo['basename']);
$statement->bindValue(':media_path', $pathInfo['dirname']);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* To avoid loading all database elements at once, this iterator allows you to retrieve them in blocks of
* MAX_ITEMS_BY_REQUEST elements.
*
* {@inheritDoc}
*/
public function findAll(): \Traversable&\Countable
{
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
`img`.img_id,
`img`.img_path,
`img`.img_comment,
`dir`.dir_name
FROM `:db`.`view_img` img
INNER JOIN `:db`.`view_img_dir_relation` rel
ON rel.img_img_id = img.img_id
INNER JOIN `:db`.`view_img_dir` dir
ON dir.dir_id = rel.dir_dir_parent_id
ORDER BY img_id
LIMIT :from, :max_item_by_request
SQL_WRAP;
$index = 0;
$statement = $this->db->prepare($this->translateDbName($request));
$statement->bindParam(':from', $index, \PDO::PARAM_INT);
$statement->bindValue(':max_item_by_request', self::MAX_ITEMS_BY_REQUEST, \PDO::PARAM_INT);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
/** @var int<0,max> $totalItems */
$totalItems = ($result !== false && ($total = $result->fetchColumn()) !== false)
? (int) $total
: 0;
return new class (
$statement,
$index,
$totalItems,
self::MAX_ITEMS_BY_REQUEST,
$this->createMedia(...),
$this->logger
) implements \IteratorAggregate, \Countable {
/** @var list<Media> */
private array $findAllCache = [];
/**
* @param int<0, max> $totalItem
*/
public function __construct(
private readonly \PDOStatement $statement,
private int &$index,
private readonly int $totalItem,
private readonly int $maxItemByRequest,
private readonly \Closure $factory,
private readonly LoggerInterface $logger,
) {
}
public function getIterator(): \Traversable
{
if ($this->findAllCache !== []) {
foreach ($this->findAllCache as $media) {
yield $media;
}
} else {
$itemCounter = 0;
do {
$this->logger->debug(
sprintf('Loading media from %d/%d', $this->index, $this->maxItemByRequest)
);
foreach ($this->statement as $result) {
$itemCounter++;
$this->findAllCache[] = ($this->factory)($result);
}
$this->index += $this->maxItemByRequest;
$this->statement->execute();
} while ($itemCounter < $this->totalItem);
foreach ($this->findAllCache as $media) {
yield $media;
}
}
}
/**
* @return int<0, max>
*/
public function count(): int
{
return $this->totalItem;
}
};
}
/**
* @inheritDoc
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): \Traversable
{
$sqlTranslator = new SqlRequestParametersTranslator($requestParameters);
$sqlTranslator->setConcordanceArray([
'id' => 'img_id',
'name' => 'img_path',
'directory' => 'dir_name',
]);
$request = <<<'SQL_WRAP'
SELECT SQL_CALC_FOUND_ROWS
`img`.img_id,
`img`.img_path,
`img`.img_comment,
`dir`.dir_name
FROM `:db`.`view_img` img
INNER JOIN `:db`.`view_img_dir_relation` rel
ON rel.img_img_id = img.img_id
INNER JOIN `:db`.`view_img_dir` dir
ON dir.dir_id = rel.dir_dir_parent_id
SQL_WRAP;
$searchRequest = $sqlTranslator->translateSearchParameterToSql();
if ($searchRequest !== null) {
$request .= $searchRequest;
}
// Handle sort
$sortRequest = $sqlTranslator->translateSortParameterToSql();
$request .= $sortRequest ?? ' ORDER BY img_id';
$request .= $sqlTranslator->translatePaginationToSql();
$statement = $this->db->prepare($this->translateDbName($request));
foreach ($sqlTranslator->getSearchValues() as $key => $data) {
/** @var int $type */
$type = key($data);
$value = $data[$type];
$statement->bindValue($key, $value, $type);
}
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$result = $this->db->query('SELECT FOUND_ROWS()');
if ($result !== false && ($total = $result->fetchColumn()) !== false) {
$sqlTranslator->getRequestParameters()->setTotal((int) $total);
}
return new class ($statement, $this->createMedia(...)) implements \IteratorAggregate {
public function __construct(
readonly private \PDOStatement $statement,
readonly private \Closure $factory,
) {
}
public function getIterator(): \Traversable
{
foreach ($this->statement as $result) {
yield ($this->factory)($result);
}
}
};
}
/**
* @param array<string, int|string> $data
*
* @throws AssertionFailedException
*
* @return Media
*/
private function createMedia(array $data): Media
{
return new Media(
(int) $data['img_id'],
(string) $data['img_path'],
(string) $data['dir_name'],
(string) $data['img_comment'],
null
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Repository/DbReadImageFolderRepository.php | centreon/src/Core/Media/Infrastructure/Repository/DbReadImageFolderRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ConnectionInterface;
use Adaptation\Database\Connection\Enum\QueryParameterTypeEnum;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\QueryBuilder\Exception\QueryBuilderException;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\TransformerException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Domain\TrimmedString;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Common\Infrastructure\RequestParameters\Transformer\SearchRequestParametersTransformer;
use Core\Media\Application\Repository\ReadImageFolderRepositoryInterface;
use Core\Media\Domain\Model\ImageFolder\ImageFolder;
use Core\Media\Domain\Model\ImageFolder\ImageFolderDescription;
use Core\Media\Domain\Model\ImageFolder\ImageFolderId;
use Core\Media\Domain\Model\ImageFolder\ImageFolderName;
use Core\ResourceAccess\Domain\Model\DatasetFilter\ResourceNamesById;
use Core\Security\AccessGroup\Domain\Model\AccessGroup;
use InvalidArgumentException;
final class DbReadImageFolderRepository extends DatabaseRepository implements ReadImageFolderRepositoryInterface
{
use SqlMultipleBindTrait;
public function __construct(
ConnectionInterface $connection,
private readonly SqlRequestParametersTranslator $sqlRequestTranslator,
) {
parent::__construct($connection);
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT)
->setConcordanceErrorMode(RequestParameters::CONCORDANCE_ERRMODE_SILENT);
}
/**
* @inheritDoc
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): array
{
try {
$this->sqlRequestTranslator->setConcordanceArray(
[
'id' => 'folders.dir_id',
'name' => 'folders.dir_name',
'alias' => 'folders.dir_alias',
'comment' => 'folders.dir_comment',
]
);
$queryBuilder = $this->connection->createQueryBuilder();
$queryBuilder
->select(
<<<'SQL'
folders.dir_id AS `id`,
folders.dir_name AS `name`,
folders.dir_alias AS `alias`,
folders.dir_comment AS `comment`
SQL
)
->from('`:db`.view_img_dir', 'folders');
if ($requestParameters->getSearch() !== []) {
$this->sqlRequestTranslator->appendQueryBuilderWithSearchParameter($queryBuilder);
$queryBuilder->andWhere("folders.dir_name NOT IN ('centreon-map', 'dashboards', 'ppm')");
} else {
$queryBuilder->where("folders.dir_name NOT IN ('centreon-map', 'dashboards', 'ppm')");
}
if ($requestParameters->getSort() !== []) {
$this->sqlRequestTranslator->appendQueryBuilderWithSortParameter($queryBuilder);
} else {
$queryBuilder->orderBy('folders.dir_name', 'ASC');
}
$this->sqlRequestTranslator->appendQueryBuilderWithPagination($queryBuilder);
$records = $this->connection->iterateAssociative(
$this->translateDbName($queryBuilder->getQuery()),
SearchRequestParametersTransformer::reverseToQueryParameters(
$this->sqlRequestTranslator->getSearchValues()
)
);
$folders = [];
foreach ($records as $record) {
/** @var array{id:int, name:string, alias:?string, comment:?string} $record */
$folders[] = $this->createImageFolderFromRecord($record);
}
// get total without pagination
$queryTotal = $queryBuilder
->select('COUNT(*)')
->resetLimit()
->offset(0)
->getQuery();
$total = $this->connection->fetchOne(
$this->translateDbName($queryTotal),
SearchRequestParametersTransformer::reverseToQueryParameters(
$this->sqlRequestTranslator->getSearchValues()
)
);
$this->sqlRequestTranslator->getRequestParameters()->setTotal($total);
return $folders;
} catch (QueryBuilderException|TransformerException|ConnectionException $exception) {
throw new RepositoryException(
message: sprintf('An error occurred while retrieving image folders: %s', $exception->getMessage()),
context: [
'request_parameters' => $requestParameters->toArray(),
],
previous: $exception,
);
}
}
/**
* @inheritDoc
*/
public function findByRequestParametersAndAccessGroups(
RequestParametersInterface $requestParameters,
array $accessGroups,
): array {
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
if ($accessGroupIds === []) {
return [];
}
try {
$this->sqlRequestTranslator->setConcordanceArray(
[
'id' => 'folders.dir_id',
'name' => 'folders.dir_name',
'alias' => 'folders.dir_alias',
'comment' => 'folders.dir_comment',
]
);
$queryBuilder = $this->connection->createQueryBuilder();
[
'parameters' => $accessGroupQueryParameters,
'placeholderList' => $accessGroupQueryPlaceHolders,
] = $this->createMultipleBindParameters(
values: $accessGroupIds,
prefix: 'access_group_id',
paramType: QueryParameterTypeEnum::INTEGER
);
$queryParameters = new QueryParameters($accessGroupQueryParameters);
$queryBuilder
->select(
<<<'SQL'
folders.dir_id AS `id`,
folders.dir_name AS `name`,
folders.dir_alias AS `alias`,
folders.dir_comment AS `comment`
SQL
)
->from(
'`:db`.view_img_dir',
'folders',
)
->innerJoin(
'folders',
'`:db`.acl_resources_image_folder_relations',
'armdr',
'armdr.dir_id = folders.dir_id',
)
->innerJoin(
'armdr',
'`:db`.acl_res_group_relations',
'argr',
'argr.acl_res_id = armdr.acl_res_id',
)
->innerJoin(
'argr',
'`:db`.acl_groups',
'ag',
"ag.acl_group_id = argr.acl_group_id AND ag.acl_group_id IN ({$accessGroupQueryPlaceHolders})",
);
// handle search
if ($requestParameters->getSearch() !== []) {
$this->sqlRequestTranslator->appendQueryBuilderWithSearchParameter($queryBuilder);
$queryBuilder->andWhere("folders.dir_name NOT IN ('centreon-map', 'dashboards', 'ppm')");
} else {
$queryBuilder->where("folders.dir_name NOT IN ('centreon-map', 'dashboards', 'ppm')");
}
// handle sort
if ($requestParameters->getSort() !== []) {
$this->sqlRequestTranslator->appendQueryBuilderWithSortParameter($queryBuilder);
} else {
$queryBuilder->orderBy('folders.dir_name', 'ASC');
}
// handle pagination
$this->sqlRequestTranslator->appendQueryBuilderWithPagination($queryBuilder);
// Handle groupBy
$queryBuilder->groupBy('folders.dir_id', 'folders.dir_name');
$queryParametersFromSearch = SearchRequestParametersTransformer::reverseToQueryParameters(
$this->sqlRequestTranslator->getSearchValues(),
);
$queryParameters = $queryParametersFromSearch->mergeWith($queryParameters);
$records = $this->connection->iterateAssociative(
$this->translateDbName($queryBuilder->getQuery()),
$queryParameters,
);
$folders = [];
foreach ($records as $record) {
/** @var array{id:int, name:string, alias:?string, comment:?string} $record */
$folders[] = $this->createImageFolderFromRecord($record);
}
// get total without pagination
$queryTotal = $queryBuilder
->select('COUNT(*)')
->resetLimit()
->offset(0)
->getQuery();
$total = $this->connection->fetchOne(
$this->translateDbName($queryTotal),
$queryParameters,
);
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
return $folders;
} catch (\Exception $exception) {
throw new RepositoryException(
message: sprintf('An error occurred while retrieving image folders: %s', $exception->getMessage()),
context: [
'access_groups' => $accessGroupIds,
'request_parameters' => $requestParameters->toArray(),
],
previous: $exception,
);
}
}
/**
* @inheritDoc
*/
public function hasAccessToAllImageFolders(array $accessGroups): bool
{
if ($accessGroups === []) {
return false;
}
try {
$accessGroupIds = array_map(
static fn (AccessGroup $accessGroup): int => $accessGroup->getId(),
$accessGroups
);
['parameters' => $queryParameters, 'placeholderList' => $placeHolders]
= $this->createMultipleBindParameters(
values: $accessGroupIds,
prefix: 'access_group_id',
paramType: QueryParameterTypeEnum::INTEGER
);
$request = <<<SQL
SELECT res.all_image_folders
FROM `:db`.acl_resources res
INNER JOIN `:db`.acl_res_group_relations argr
ON argr.acl_res_id = res.acl_res_id
INNER JOIN `:db`.acl_groups ag
ON ag.acl_group_id = argr.acl_group_id
WHERE res.acl_res_activate = '1' AND ag.acl_group_id IN ({$placeHolders})
SQL;
$values = $this->connection->fetchFirstColumn(
$this->translateDbName($request),
QueryParameters::create($queryParameters),
);
return in_array(1, $values, true);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
message: sprintf('An error occurred while retrieving image folders: %s', $exception->getMessage()),
context: ['access_groups' => $accessGroups],
previous: $exception,
);
}
}
/**
* @inheritDoc
*/
public function findExistingFolderIds(array $folderIds): array
{
if ($folderIds === []) {
return [];
}
try {
['parameters' => $queryParameters, 'placeholderList' => $queryBindString]
= $this->createMultipleBindParameters(
values: $folderIds,
prefix: 'directory_id',
paramType: QueryParameterTypeEnum::INTEGER,
);
$query = <<<SQL
SELECT dir_id FROM `:db`.view_img_dir WHERE dir_id IN ({$queryBindString})
SQL;
return $this->connection->fetchFirstColumn(
$this->translateDbName($query),
QueryParameters::create($queryParameters),
);
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
message: sprintf(
'An error occurred while testing folders accessibility in database: %s',
$exception->getMessage()
),
context: ['directory_ids' => $folderIds],
previous: $exception,
);
}
}
/**
* @inheritDoc
*/
public function findFolderNames(array $folderIds): ResourceNamesById
{
$folders = new ResourceNamesById();
if ($folderIds === []) {
return $folders;
}
try {
['parameters' => $queryParameters, 'placeholderList' => $queryBindString]
= $this->createMultipleBindParameters(
values: $folderIds,
prefix: 'directory_id',
paramType: QueryParameterTypeEnum::INTEGER,
);
$query = <<<SQL
SELECT dir_id, dir_name FROM `:db`.view_img_dir WHERE dir_id IN ({$queryBindString})
SQL;
/** @var string[] $records */
$records = $this->connection->fetchAllKeyValue(
$this->translateDbName($query),
QueryParameters::create($queryParameters),
);
foreach ($records as $directoryId => $directoryName) {
$folders->addName($directoryId, new TrimmedString($directoryName));
}
return $folders;
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
throw new RepositoryException(
message: sprintf('An error occurred while retrieving media folders: %s', $exception->getMessage()),
context: ['directory_ids' => $folderIds],
previous: $exception,
);
}
}
/**
* @param array{id:int, name:string, alias:?string, comment:?string} $record
*
* @throws InvalidArgumentException
* @return ImageFolder
*/
private function createImageFolderFromRecord(array $record): ImageFolder
{
$folder = new ImageFolder(
id: new ImageFolderId($record['id']),
name: new ImageFolderName($record['name']),
);
$folder->setAlias(! empty($record['alias']) ? new ImageFolderName($record['alias']) : null);
$folder->setDescription(! empty($record['comment']) ? new ImageFolderDescription($record['comment']) : null);
return $folder;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Repository/FileProxyWriteMediaRepository.php | centreon/src/Core/Media/Infrastructure/Repository/FileProxyWriteMediaRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Repository;
use Core\Media\Application\Repository\WriteMediaRepositoryInterface;
use Core\Media\Domain\Model\Media;
use Core\Media\Domain\Model\NewMedia;
class FileProxyWriteMediaRepository implements WriteMediaRepositoryInterface
{
public function __construct(
readonly private DbWriteMediaRepository $dbWriteMediaRepository,
readonly private FileWriteMediaRepository $fileWriteMediaRepository,
) {
}
/**
* @inheritDoc
*/
public function update(Media $media): void
{
$this->dbWriteMediaRepository->update($media);
$this->fileWriteMediaRepository->update($media);
}
/**
* Creates the file in the directory after it has been saved in the databases.
*
* {@inheritDoc}
*/
public function add(NewMedia $media): int
{
$mediaId = $this->dbWriteMediaRepository->add($media);
$this->fileWriteMediaRepository->add($media);
return $mediaId;
}
/**
* Deletes the file from the database and also from the file system.
*
* {@inheritDoc}
*/
public function delete(Media $media): void
{
$this->dbWriteMediaRepository->delete($media);
$this->fileWriteMediaRepository->delete($media);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Repository/FileProxyReadMediaRepository.php | centreon/src/Core/Media/Infrastructure/Repository/FileProxyReadMediaRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Repository;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Media\Application\Repository\ReadMediaRepositoryInterface;
use Core\Media\Domain\Model\Media;
class FileProxyReadMediaRepository implements ReadMediaRepositoryInterface
{
/**
* @param DbReadMediaRepository $dbReadMediaRepository
* @param string $absoluteMediaPath
*
* @throws \Exception
*/
public function __construct(
private readonly DbReadMediaRepository $dbReadMediaRepository,
private string $absoluteMediaPath,
) {
$this->absoluteMediaPath = realpath($absoluteMediaPath)
?: throw new \Exception(sprintf('Path invalid \'%s\'', $absoluteMediaPath));
}
/**
* @inheritDoc
*/
public function findById(int $mediaId): ?Media
{
return $this->dbReadMediaRepository->findById($mediaId);
}
public function findByIds(array $mediaIds): array
{
return $this->dbReadMediaRepository->findByIds($mediaIds);
}
/**
* @inheritDoc
*/
public function existsByPath(string $path): bool
{
return $this->dbReadMediaRepository->existsByPath($path);
}
/**
* @inheritDoc
*/
public function findAll(): \Traversable&\Countable
{
return new class ($this->absoluteMediaPath, $this->dbReadMediaRepository->findAll()) implements \IteratorAggregate, \Countable {
/**
* @param string $absoluteMediaPath
* @param \Traversable<int, Media>&\Countable $medias
*/
public function __construct(
readonly private string $absoluteMediaPath,
readonly private \Traversable&\Countable $medias,
) {
}
public function getIterator(): \Traversable
{
foreach ($this->medias as $media) {
$absoluteMediaPath = $this->absoluteMediaPath . DIRECTORY_SEPARATOR . $media->getRelativePath();
if (file_exists($absoluteMediaPath)) {
yield new Media(
$media->getId(),
$media->getFilename(),
$media->getDirectory(),
$media->getComment(),
file_get_contents($absoluteMediaPath)
?: throw new \Exception(
'Cannot get content of file ' . $media->getRelativePath()
)
);
} else {
yield $media;
}
}
}
public function count(): int
{
return count($this->medias);
}
};
}
/**
* @inheritDoc
*/
public function findByRequestParametersAndAccessGroups(RequestParametersInterface $requestParameters, array $accessGroups): \Traversable
{
return $this->createTraversable($this->dbReadMediaRepository->findByRequestParametersAndAccessGroups($requestParameters, $accessGroups));
}
/**
* @inheritDoc
*/
public function findByRequestParameters(RequestParametersInterface $requestParameters): \Traversable
{
return $this->createTraversable($this->dbReadMediaRepository->findByRequestParameters($requestParameters));
}
/**
* @param \Traversable<int, Media> $medias
*
* @return \Traversable<int, Media>
*/
private function createTraversable(\Traversable $medias): \Traversable
{
return new class ($this->absoluteMediaPath, $medias) implements \IteratorAggregate {
/**
* @param string $absoluteMediaPath
* @param \Traversable<int, Media> $medias
*/
public function __construct(
readonly private string $absoluteMediaPath,
readonly private \Traversable $medias,
) {
}
public function getIterator(): \Traversable
{
foreach ($this->medias as $media) {
$absoluteMediaPath = $this->absoluteMediaPath . DIRECTORY_SEPARATOR . $media->getRelativePath();
if (file_exists($absoluteMediaPath)) {
yield new Media(
$media->getId(),
$media->getFilename(),
$media->getDirectory(),
$media->getComment(),
file_get_contents($absoluteMediaPath) ?: null
);
} else {
yield $media;
}
}
}
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/FindImageFolders/FindImageFoldersController.php | centreon/src/Core/Media/Infrastructure/API/FindImageFolders/FindImageFoldersController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\FindImageFolders;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Media\Application\UseCase\FindImageFolders\FindImageFolders;
use Core\Media\Domain\Model\ImageFolder\ImageFolder;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\SerializerInterface;
final class FindImageFoldersController extends AbstractController
{
public function __construct(
private readonly ExceptionLogger $exceptionLogger,
private readonly RequestParametersInterface $requestParameters,
private readonly SerializerInterface $serializer,
) {
}
#[Route(
path: '/configuration/media/folders',
name: 'FindImageFolders',
methods: 'GET',
)]
public function __invoke(
FindImageFolders $useCase,
): Response {
try {
$response = $useCase();
$imageFolders = array_map(
static fn (ImageFolder $folder): ImageFolderDto => new ImageFolderDto(
id: $folder->id()->value,
name: $folder->name()->value,
alias: $folder->alias()?->value,
comment: $folder->description()?->value,
),
$response->imageFolders
);
return JsonResponse::fromJsonString(
$this->serializer->serialize(
[
'result' => $imageFolders,
'meta' => $this->requestParameters->toArray(),
],
JsonEncoder::FORMAT,
)
);
} catch (RepositoryException|\Exception|ExceptionInterface $exception) {
$this->exceptionLogger->log($exception);
return new JsonResponse(
data: [
'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
'message' => $exception->getMessage(),
]
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/FindImageFolders/ImageFolderDto.php | centreon/src/Core/Media/Infrastructure/API/FindImageFolders/ImageFolderDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\FindImageFolders;
final readonly class ImageFolderDto
{
public function __construct(
public int $id,
public string $name,
public ?string $alias,
public ?string $comment,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/Voters/MediaVoters.php | centreon/src/Core/Media/Infrastructure/API/Voters/MediaVoters.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\Voters;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* @extends Voter<string, mixed>
*/
final class MediaVoters extends Voter
{
public const CREATE_MEDIA = 'create_media';
public const UPDATE_MEDIA = 'update_media';
/**
* {@inheritDoc}
*/
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::CREATE_MEDIA, self::UPDATE_MEDIA], true);
}
/**
* {@inheritDoc}
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (! $user instanceof ContactInterface) {
return false;
}
return match ($attribute) {
self::CREATE_MEDIA, self::UPDATE_MEDIA => $user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_PARAMETERS_IMAGES_RW),
default => throw new \LogicException('Action on media not handled'),
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/AddMedia/AddMediaPresenter.php | centreon/src/Core/Media/Infrastructure/API/AddMedia/AddMediaPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\AddMedia;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Media\Application\UseCase\AddMedia\AddMediaPresenterInterface;
use Core\Media\Application\UseCase\AddMedia\AddMediaResponse;
class AddMediaPresenter extends AbstractPresenter implements AddMediaPresenterInterface
{
public function presentResponse(AddMediaResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present([
'result' => array_map(fn (array $media) => [
'id' => $media['id'],
'filename' => $media['filename'],
'directory' => $media['directory'],
'md5' => $media['md5'],
], $response->mediasRecorded),
'errors' => array_map(fn (array $errors) => [
'filename' => $errors['filename'],
'directory' => $errors['directory'],
'reason' => $errors['reason'],
], $response->errors),
]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/AddMedia/AddMediaController.php | centreon/src/Core/Media/Infrastructure/API/AddMedia/AddMediaController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\AddMedia;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Common\Infrastructure\Upload\FileCollection;
use Core\Media\Application\UseCase\AddMedia\AddMedia;
use Core\Media\Application\UseCase\AddMedia\AddMediaRequest;
use Core\Media\Infrastructure\API\Exception\MediaException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsGranted;
final class AddMediaController extends AbstractController
{
use LoggerTrait;
#[IsGranted('create_media', null, 'You are not allowed to add media', Response::HTTP_FORBIDDEN)]
public function __invoke(Request $request, AddMedia $useCase, AddMediaPresenter $presenter): Response
{
$uploadedFile = '';
$filesToDeleteAfterProcessing = [];
try {
$assertion = new AddMediaValidator($request);
$assertion->assertFilesSent();
$assertion->assertDirectory();
$fileIterator = new FileCollection();
/** @var UploadedFile|list<UploadedFile> $files */
$files = $request->files->get('data');
if (is_array($files)) {
foreach ($files as $file) {
$fileIterator->addFile($file);
$filesToDeleteAfterProcessing[] = $file->getPathname();
}
} else {
$fileIterator->addFile($files);
$filesToDeleteAfterProcessing[] = $files->getPathname();
}
$addMediaRequest = new AddMediaRequest($fileIterator->getFiles());
$addMediaRequest->directory = (string) $request->request->get('directory');
$useCase($addMediaRequest, $presenter);
} catch (MediaException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(
new ErrorResponse(
MediaException::errorUploadingFile($uploadedFile)->getMessage()
)
);
} finally {
foreach ($filesToDeleteAfterProcessing as $fileToDelete) {
if (is_file($fileToDelete)) {
unlink($fileToDelete);
$this->debug('Deleting the uploaded file', ['filename' => $fileToDelete]);
}
}
}
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/AddMedia/AddMediaValidator.php | centreon/src/Core/Media/Infrastructure/API/AddMedia/AddMediaValidator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\AddMedia;
use Core\Media\Infrastructure\API\Exception\MediaException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
class AddMediaValidator
{
/** @var array<string|int, mixed> */
private array $allProperties = [];
public function __construct(readonly private Request $request)
{
$this->allProperties = array_unique(
array_merge($this->request->request->keys(), $this->request->files->keys())
);
}
/**
* @throws MediaException
*/
public function assertFilesSent(): void
{
if (! in_array('data', $this->allProperties, true)) {
throw MediaException::propertyNotPresent('data');
}
$files = $this->request->files->get('data');
// The presence of an array means that it contains files.
if (! is_array($files)) {
$this->assertUploadedFile($files);
}
}
/**
* @throws MediaException
*/
public function assertDirectory(): void
{
if (! in_array('directory', $this->allProperties, true)) {
MediaException::propertyNotPresent('directory');
}
$value = $this->request->get('directory');
if (empty($value)) {
MediaException::stringPropertyCanNotBeEmpty('directory');
}
}
/**
* @param mixed $file
*
* @throws MediaException
*/
private function assertUploadedFile(mixed $file): void
{
if (! $file instanceof UploadedFile) {
throw MediaException::wrongFileType('data');
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/FindMedias/FindMediasController.php | centreon/src/Core/Media/Infrastructure/API/FindMedias/FindMediasController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\FindMedias;
use Centreon\Application\Controller\AbstractController;
use Core\Media\Application\UseCase\FindMedias\FindMedias;
use Core\Media\Application\UseCase\FindMedias\FindMediasPresenterInterface;
use Symfony\Component\HttpFoundation\Response;
final class FindMediasController extends AbstractController
{
public function __invoke(FindMedias $useCase, FindMediasPresenterInterface $presenter): Response
{
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/FindMedias/FindMediasPresenter.php | centreon/src/Core/Media/Infrastructure/API/FindMedias/FindMediasPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\FindMedias;
use Centreon\Domain\Log\Logger;
use Centreon\Domain\RequestParameters\Interfaces\RequestParametersInterface;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Infrastructure\Common\Api\HttpUrlTrait;
use Core\Infrastructure\Common\Presenter\PresenterFormatterInterface;
use Core\Media\Application\UseCase\FindMedias\FindMediasPresenterInterface;
use Core\Media\Application\UseCase\FindMedias\FindMediasResponse;
class FindMediasPresenter extends AbstractPresenter implements FindMediasPresenterInterface
{
use HttpUrlTrait;
private const IMG_FOLDER_PATH = '/img/media/';
public function __construct(
private readonly RequestParametersInterface $requestParameters,
protected PresenterFormatterInterface $presenterFormatter,
) {
parent::__construct($presenterFormatter);
}
public function presentResponse(FindMediasResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
if ($response instanceof ErrorResponse && ! is_null($response->getException())) {
ExceptionLogger::create()->log($response->getException(), $response->getContext());
} elseif ($response instanceof ForbiddenResponse) {
Logger::create()->warning("User doesn't have sufficient rights to list media", $response->getContext());
}
$this->setResponseStatus($response);
return;
}
$result = [];
foreach ($response->medias as $dto) {
$result[] = [
'id' => $dto->id,
'name' => $dto->filename,
'directory' => $dto->directory,
'md5' => $dto->md5,
'url' => $this->getBaseUri() . self::IMG_FOLDER_PATH . $dto->directory . '/' . $dto->filename,
];
}
$this->present([
'result' => $result,
'meta' => $this->requestParameters->toArray(),
]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/Exception/MediaException.php | centreon/src/Core/Media/Infrastructure/API/Exception/MediaException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\Exception;
class MediaException extends \Exception
{
/**
* @param string $propertyName
*
* @return self
*/
public static function wrongFileType(string $propertyName): self
{
return new self(sprintf(_('[%s] The property does not contain the file'), $propertyName));
}
/**
* @return self
*/
public static function moreThanOneFileNotAllowed(): self
{
return new self(_('On media update, only one file is allowed'));
}
/**
* @param string $propertyName
*
* @return self
*/
public static function stringPropertyCanNotBeEmpty(string $propertyName): self
{
return new self(sprintf(_('[%s] Empty value found, but a string is required'), $propertyName));
}
/**
* @param string $propertyName
*
* @return MediaException
*/
public static function propertyNotPresent(string $propertyName): self
{
return new self(sprintf(_('[%s] The property %s is required'), $propertyName, $propertyName));
}
/**
* @param string $filename
*
* @return MediaException
*/
public static function errorUploadingFile(string $filename): self
{
return new self(sprintf(_('Error uploading file \'%s\''), $filename));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/UpdateMedia/UpdateMediaController.php | centreon/src/Core/Media/Infrastructure/API/UpdateMedia/UpdateMediaController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\UpdateMedia;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMedia;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMediaRequest;
use Core\Media\Infrastructure\API\AddMedia\AddMediaValidator;
use Core\Media\Infrastructure\API\Exception\MediaException;
use enshrined\svgSanitize\Sanitizer;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsGranted;
final class UpdateMediaController extends AbstractController
{
use LoggerTrait;
/**
* @param Sanitizer $svgSanitizer
*/
public function __construct(private readonly Sanitizer $svgSanitizer)
{
}
#[IsGranted('update_media', null, 'You are not allowed to update media', Response::HTTP_FORBIDDEN)]
public function __invoke(int $mediaId, Request $request, UpdateMedia $useCase, UpdateMediaPresenter $presenter): Response
{
$uploadedFileName = '';
try {
$assertion = new AddMediaValidator($request);
$assertion->assertFilesSent();
if (is_array($request->files->get('data'))) {
throw MediaException::moreThanOneFileNotAllowed();
}
/** @var UploadedFile $file */
$file = $request->files->get('data');
$uploadedFileName = $file->getPathname();
$updateMediaRequest = new UpdateMediaRequest(
fileName: $file->getClientOriginalName(),
data: $this->sanitizeData($file)
);
$useCase($mediaId, $updateMediaRequest, $presenter);
} catch (MediaException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(new ErrorResponse($ex->getMessage()));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->presentResponse(
new ErrorResponse(
MediaException::errorUploadingFile($uploadedFileName)->getMessage()
)
);
} finally {
if (is_file($uploadedFileName)) {
if (! unlink($uploadedFileName)) {
$this->error(
'Failed to delete the temporary uploaded file',
['filename' => $uploadedFileName],
);
}
$this->debug('Deleting the uploaded file', ['filename' => $uploadedFileName]);
}
}
return $presenter->show();
}
/**
* @param UploadedFile $file
*
* @throws FileException
* @return string
*/
private function sanitizeData(UploadedFile $file): string
{
$fileInformation = pathinfo($file->getClientOriginalName());
if (
array_key_exists('extension', $fileInformation)
&& $fileInformation['extension'] === 'svg'
) {
$this->svgSanitizer->minify(true);
return $this->svgSanitizer->sanitize($file->getContent());
}
return $file->getContent();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/API/UpdateMedia/UpdateMediaPresenter.php | centreon/src/Core/Media/Infrastructure/API/UpdateMedia/UpdateMediaPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\API\UpdateMedia;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMediaPresenterInterface;
use Core\Media\Application\UseCase\UpdateMedia\UpdateMediaResponse;
class UpdateMediaPresenter extends AbstractPresenter implements UpdateMediaPresenterInterface
{
public function presentResponse(UpdateMediaResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->setResponseStatus($response);
} else {
$this->present([
'id' => $response->updatedMedia['id'],
'filename' => $response->updatedMedia['filename'],
'directory' => $response->updatedMedia['directory'],
'md5' => $response->updatedMedia['md5'],
]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Command/Exception/MediaMigrationCommandException.php | centreon/src/Core/Media/Infrastructure/Command/Exception/MediaMigrationCommandException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Command\Exception;
class MediaMigrationCommandException extends \Exception
{
/**
* @return self
*/
public static function contactNotFound(): self
{
return new self(_('Contact not found'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Command/MigrateAllMedias/MigrateAllMediasPresenter.php | centreon/src/Core/Media/Infrastructure/Command/MigrateAllMedias/MigrateAllMediasPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Command\MigrateAllMedias;
use Core\Application\Common\UseCase\CliAbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Media\Application\UseCase\MigrateAllMedias\MediaRecordedDto;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrateAllMediasPresenterInterface;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrationAllMediasResponse;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrationErrorDto;
/**
* @phpstan-type _MediaRecorded array{
* id: int,
* filename: string,
* directory: string,
* md5: string,
* }
* @phpstan-type _Errors array{
* filename: string,
* directory: string,
* reason: string,
* }
*/
class MigrateAllMediasPresenter extends CliAbstractPresenter implements MigrateAllMediasPresenterInterface
{
public function presentResponse(MigrationAllMediasResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->error($response->getMessage());
} else {
foreach ($response->results as $result) {
if ($result instanceof MediaRecordedDto) {
$absolutePath = $result->directory . DIRECTORY_SEPARATOR . $result->filename;
$this->write("<ok> OK</> {$absolutePath}");
} elseif ($result instanceof MigrationErrorDto) {
$absolutePath = $result->directory . DIRECTORY_SEPARATOR . $result->filename;
$this->write("<error>ERROR</> {$absolutePath} ({$result->reason})");
}
}
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Media/Infrastructure/Command/MigrateAllMedias/MigrateAllMediasCommand.php | centreon/src/Core/Media/Infrastructure/Command/MigrateAllMedias/MigrateAllMediasCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Media\Infrastructure\Command\MigrateAllMedias;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Infrastructure\Command\AbstractMigrationCommand;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrateAllMedias;
use Core\Media\Application\UseCase\MigrateAllMedias\MigrateAllMediasRequest;
use Core\Media\Infrastructure\Repository\ApiWriteMediaRepository;
use Core\Proxy\Application\Repository\ReadProxyRepositoryInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(
name: 'media:all',
description: 'Migrate all media from the current platform to the defined target platform'
)]
class MigrateAllMediasCommand extends AbstractMigrationCommand
{
use LoggerTrait;
private int $maxFilesize;
private int $postMax;
public function __construct(
ReadProxyRepositoryInterface $readProxyRepository,
readonly private ApiWriteMediaRepository $apiWriteMediaRepository,
readonly private MigrateAllMedias $useCase,
readonly private int $maxFile,
string $maxFilesize,
string $postMax,
) {
parent::__construct($readProxyRepository);
$this->maxFilesize = self::parseSize($maxFilesize);
$this->postMax = self::parseSize($postMax);
}
protected function configure(): void
{
$this->addArgument(
'target-url',
InputArgument::REQUIRED,
"The target platform base URL to connect to the API (ex: 'http://localhost')"
);
$this->setHelp(
"Migrates all media to the target platform.\r\n"
. 'However the media migration command will not replace media that already exists on the target platform.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
try {
$this->setStyle($output);
$proxy = $this->getProxy();
if ($proxy !== null && $proxy !== '') {
$this->apiWriteMediaRepository->setProxy($proxy);
}
if (is_string($target = $input->getArgument('target-url'))) {
$this->apiWriteMediaRepository->setUrl($target);
} else {
// Theoretically it should never happen
throw new \InvalidArgumentException('target-url is not a string');
}
$targetToken = $this->askAuthenticationToken(self::TARGET_PLATFORM, $input, $output);
$request = new MigrateAllMediasRequest();
$request->maxFile = $this->maxFile;
$request->maxFilesize = $this->maxFilesize;
$request->postMax = $this->postMax;
$this->apiWriteMediaRepository->setAuthenticationToken($targetToken);
($this->useCase)($request, new MigrateAllMediasPresenter($output));
} catch (\Throwable $ex) {
$this->writeError($ex->getMessage(), $output);
return self::FAILURE;
}
return self::SUCCESS;
}
private static function parseSize(string $size): int
{
if ($size === '') {
return 0;
}
$size = mb_strtolower($size);
$max = (int) ltrim($size, '+');
switch (mb_substr($size, -1)) {
case 't':
$max *= 1024;
// no break
case 'g':
$max *= 1024;
// no break
case 'm':
$max *= 1024;
// no break
case 'k':
$max *= 1024;
}
return $max;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/FindTokens/FindTokensPresenterInterface.php | centreon/src/Core/Security/Token/Application/UseCase/FindTokens/FindTokensPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\FindTokens;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindTokensPresenterInterface
{
public function presentResponse(FindTokensResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/FindTokens/FindTokens.php | centreon/src/Core/Security/Token/Application/UseCase/FindTokens/FindTokens.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\FindTokens;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Application\Common\UseCase\StandardResponseInterface;
use Core\Security\Token\Application\Exception\TokenException;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
final class FindTokens
{
use LoggerTrait;
/**
* @param ReadTokenRepositoryInterface $readTokenRepository
* @param ContactInterface $user
*/
public function __construct(
private readonly ReadTokenRepositoryInterface $readTokenRepository,
private readonly ContactInterface $user,
) {
}
public function __invoke(): ResponseStatusInterface|StandardResponseInterface
{
try {
$tokens = $this->canDisplayAllTokens()
? $this->readTokenRepository->findByRequestParameters()
: $this->readTokenRepository->findByUserIdAndRequestParameters($this->user->getId());
return new FindTokensResponse($tokens);
} catch (RequestParametersTranslatorException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
return new ErrorResponse($ex->getMessage());
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
return new ErrorResponse(TokenException::errorWhileSearching($ex));
}
}
private function canDisplayAllTokens(): bool
{
return $this->user->isAdmin() || $this->user->hasRole(Contact::ROLE_MANAGE_TOKENS);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/FindTokens/TokenDto.php | centreon/src/Core/Security/Token/Application/UseCase/FindTokens/TokenDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\FindTokens;
final class TokenDto
{
public function __construct(
public string $name,
public int $userId,
public string $userName,
public ?int $creatorId,
public string $creatorName,
public \DateTimeInterface $creationDate,
public \DateTimeInterface $expirationDate,
public bool $isRevoked,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/FindTokens/FindTokensResponse.php | centreon/src/Core/Security/Token/Application/UseCase/FindTokens/FindTokensResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\FindTokens;
use Core\Application\Common\UseCase\ListingResponseInterface;
use Core\Security\Token\Domain\Model\Token;
final class FindTokensResponse implements ListingResponseInterface
{
/**
* @param list<Token> $tokens
*/
public function __construct(public array $tokens)
{
}
/**
* @return list<Token>
*/
public function getData(): array
{
return $this->tokens;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/PartialUpdateToken/PartialUpdateToken.php | centreon/src/Core/Security/Token/Application/UseCase/PartialUpdateToken/PartialUpdateToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\PartialUpdateToken;
use Adaptation\Log\LoggerToken;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Common\Application\Type\NoValue;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Security\Token\Application\Exception\TokenException;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Application\Repository\WriteTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\ApiToken;
use Core\Security\Token\Domain\Model\JwtToken;
use Core\Security\Token\Domain\Model\Token;
use Exception;
use Psr\Log\LogLevel;
final class PartialUpdateToken
{
use LoggerTrait;
/**
* @param ContactInterface $user
* @param ReadTokenRepositoryInterface $readRepository
* @param WriteTokenRepositoryInterface $writeRepository
*/
public function __construct(
private readonly ContactInterface $user,
private readonly ReadTokenRepositoryInterface $readRepository,
private readonly WriteTokenRepositoryInterface $writeRepository,
) {
}
/**
* @param PartialUpdateTokenRequest $requestDto
* @param PresenterInterface $presenter
* @param string $tokenName
* @param int $userId
*/
public function __invoke(
PartialUpdateTokenRequest $requestDto,
PresenterInterface $presenter,
string $tokenName,
int $userId,
): void {
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_TOKENS_RW)) {
ExceptionLogger::create()->log(
TokenException::notAllowedToPartiallyUpdateToken(),
[
'message' => 'User is not allowed to partially update token',
'token_name' => $tokenName,
'user_id' => $this->user->getId(),
]
);
LoggerToken::create()->warning(
event: 'partial update',
reason: 'insufficient rights',
userId: $this->user->getId(),
tokenName: $tokenName
);
$presenter->setResponseStatus(
new ForbiddenResponse(TokenException::notAllowedToPartiallyUpdateToken())
);
return;
}
$token = $this->readRepository->findByNameAndUserId($tokenName, $userId);
if ($token === null) {
ExceptionLogger::create()->log(
TokenException::tokenNotFound(),
[
'message' => 'Token not found',
'token_name' => $tokenName,
'user_id' => $this->user->getId(),
]
);
LoggerToken::create()->warning(
event: 'partial update',
reason: 'not found',
userId: $this->user->getId(),
tokenName: $tokenName
);
$presenter->setResponseStatus(new NotFoundResponse('Token'));
return;
}
if (! $this->canUserUpdateToken($token)) {
ExceptionLogger::create()->log(
TokenException::notAllowedToPartiallyUpdateToken(),
[
'message' => 'User is not allowed to partially update token',
'token_name' => $tokenName,
'user_id' => $this->user->getId(),
]
);
LoggerToken::create()->warning(
event: 'partial update',
reason: 'insufficient rights on token',
userId: $this->user->getId(),
tokenName: $tokenName
);
$presenter->setResponseStatus(
new ForbiddenResponse(TokenException::notAllowedToPartiallyUpdateToken())
);
return;
}
if ($requestDto->isRevoked instanceof NoValue) {
ExceptionLogger::create()->log(
new Exception('is_revoked property is not provided'),
[
'message' => 'is_revoked property is not provided. Nothing to update',
'token_name' => $token->getName(),
'user_id' => $this->user->getId(),
],
LogLevel::DEBUG
);
LoggerToken::create()->warning(
event: 'revocation/activation',
reason: 'is_revoked property is not provided',
userId: $this->user->getId(),
tokenName: $token->getName(),
);
return;
}
$this->updateToken($requestDto, $token);
LoggerToken::create()->success(
event: $requestDto->isRevoked ? 'revocation' : 'activation',
userId: $this->user->getId(),
tokenName: $tokenName,
tokenType: $token->getType()->name
);
$presenter->setResponseStatus(new NoContentResponse());
} catch (\Throwable $ex) {
ExceptionLogger::create()->log(
$ex,
[
'user_id' => $this->user->getId(),
'token_name' => $tokenName,
]
);
LoggerToken::create()->warning(
event: $requestDto->isRevoked ? 'revocation' : 'activation',
reason: 'unexpected error',
userId: $this->user->getId(),
tokenName: $tokenName,
exception: $ex
);
$presenter->setResponseStatus(
new ErrorResponse(TokenException::errorWhilePartiallyUpdatingToken())
);
}
}
private function canUserUpdateToken(Token $token): bool
{
return (bool) (
$this->user->isAdmin()
|| $this->user->hasRole(Contact::ROLE_MANAGE_TOKENS)
|| ($token instanceof ApiToken && $token->getUserId() === $this->user->getId())
|| ($token instanceof JwtToken && $token->getCreatorId() === $this->user->getId())
);
}
/**
* @param PartialUpdateTokenRequest $requestDto
* @param Token $token
*
* @throws \Throwable
*/
private function updateToken(PartialUpdateTokenRequest $requestDto, Token $token): void
{
$token->setIsRevoked((bool) $requestDto->isRevoked);
$this->writeRepository->update($token);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/PartialUpdateToken/PartialUpdateTokenRequest.php | centreon/src/Core/Security/Token/Application/UseCase/PartialUpdateToken/PartialUpdateTokenRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\PartialUpdateToken;
use Core\Common\Application\Type\NoValue;
final class PartialUpdateTokenRequest
{
/**
* @param NoValue|bool $isRevoked
*/
public function __construct(public NoValue|bool $isRevoked = new NoValue())
{
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddTokenValidation.php | centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddTokenValidation.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\AddToken;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Contact\Application\Repository\ReadContactRepositoryInterface;
use Core\Security\Token\Application\Exception\TokenException;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
class AddTokenValidation
{
use LoggerTrait;
public function __construct(
private readonly ReadTokenRepositoryInterface $readTokenRepository,
private readonly ReadContactRepositoryInterface $readContactRepository,
private readonly ContactInterface $user,
) {
}
/**
* Assert name is not already used.
*
* @param string $name
* @param int $userId
*
* @throws TokenException|\Throwable
*/
public function assertIsValidName(string $name, int $userId): void
{
$trimmedName = trim($name);
if ($this->readTokenRepository->existsByNameAndUserId($trimmedName, $userId)) {
$this->error('Token name already exists', ['name' => $trimmedName, 'userId' => $userId]);
throw TokenException::nameAlreadyExists($trimmedName);
}
}
/**
* Assert user id is valid.
*
* @param int $userId
*
* @throws TokenException|\Throwable
*/
public function assertIsValidUser(int $userId): void
{
if (! $this->user->isAdmin() && $this->user->getId() !== $userId && ! $this->user->hasRole(Contact::ROLE_MANAGE_TOKENS)) {
throw TokenException::notAllowedToCreateTokenForUser($userId);
}
if ($this->readContactRepository->exists($userId) === false) {
throw TokenException::invalidUserId($userId);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddTokenResponse.php | centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddTokenResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\AddToken;
use Core\Application\Common\UseCase\StandardResponseInterface;
use Core\Security\Token\Domain\Model\Token;
final class AddTokenResponse implements StandardResponseInterface
{
public function __construct(public Token $token, public string $tokenString)
{
}
public function getData(): self
{
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddTokenRequest.php | centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddTokenRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\AddToken;
use Core\Security\Token\Domain\Model\TokenTypeEnum;
final class AddTokenRequest
{
/**
* @param string $name
* @param TokenTypeEnum $type
* @param int $userId
* @param \DateTimeInterface|null $expirationDate
*/
public function __construct(
public string $name = '',
public TokenTypeEnum $type = TokenTypeEnum::API,
public int $userId = 0,
public ?\DateTimeInterface $expirationDate = null,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddTokenPresenterInterface.php | centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddTokenPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\AddToken;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface AddTokenPresenterInterface
{
public function presentResponse(AddTokenResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddToken.php | centreon/src/Core/Security/Token/Application/UseCase/AddToken/AddToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\AddToken;
use Adaptation\Log\LoggerToken;
use Assert\AssertionFailedException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ConflictResponse;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Application\Common\UseCase\StandardResponseInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Security\Authentication\Application\Provider\ProviderAuthenticationFactoryInterface;
use Core\Security\ProviderConfiguration\Domain\Model\Provider;
use Core\Security\Token\Application\Exception\TokenException;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Application\Repository\WriteTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\TokenFactory;
final class AddToken
{
use LoggerTrait;
public function __construct(
private readonly WriteTokenRepositoryInterface $writeTokenRepository,
private readonly ReadTokenRepositoryInterface $readTokenRepository,
private readonly ProviderAuthenticationFactoryInterface $providerFactory,
private readonly AddTokenValidation $validation,
private readonly ContactInterface $user,
) {
}
/**
* @param AddTokenRequest $request
*/
public function __invoke(AddTokenRequest $request): ResponseStatusInterface|StandardResponseInterface
{
try {
$tokenString = $this->createToken($request);
$response = $this->createResponse($tokenString);
LoggerToken::create()->success(
event: 'creation',
userId: $this->user->getId(),
tokenName: $request->name,
tokenType: $request->type->name,
);
return $response;
} catch (AssertionFailedException|\ValueError $ex) {
ExceptionLogger::create()->log($ex, [
'user_id' => $this->user->getId(),
'token_name' => $request->name,
'token_type' => $request->type->name,
]);
LoggerToken::create()->warning(
event: 'creation',
reason: 'validation error',
userId: $this->user->getId(),
tokenName: $request->name,
tokenType: $request->type->name,
exception: $ex
);
return new InvalidArgumentResponse($ex);
} catch (TokenException $ex) {
ExceptionLogger::create()->log($ex, [
'user_id' => $this->user->getId(),
'token_name' => $request->name,
'token_type' => $request->type->name,
]);
LoggerToken::create()->warning(
event: 'creation',
reason: 'conflict error',
userId: $this->user->getId(),
tokenName: $request->name,
tokenType: $request->type->name,
exception: $ex
);
return match ($ex->getCode()) {
TokenException::CODE_CONFLICT => new ConflictResponse($ex),
default => new ErrorResponse($ex),
};
} catch (\Throwable $ex) {
ExceptionLogger::create()->log($ex, [
'user_id' => $this->user->getId(),
'token_name' => $request->name,
'token_type' => $request->type->name,
]);
LoggerToken::create()->warning(
event: 'creation',
reason: 'unexpected error',
userId: $this->user->getId(),
tokenName: $request->name,
tokenType: $request->type->name,
exception: $ex
);
return new ErrorResponse(TokenException::addToken());
}
}
/**
* @param AddTokenRequest $request
*
* @throws AssertionFailedException
* @throws TokenException
* @throws \Throwable
*
* @return string
*/
private function createToken(AddTokenRequest $request): string
{
$this->validation->assertIsValidUser($request->userId);
$this->validation->assertIsValidName($request->name, $request->userId);
$newToken = TokenFactory::createNew(
$request->type,
[
'name' => $request->name,
'user_id' => $request->userId,
'creator_id' => $this->user->getId(),
'creator_name' => $this->user->getName(),
'expiration_date' => $request->expirationDate,
'configuration_provider_id' => $this->providerFactory->create(Provider::LOCAL)->getConfiguration()->getId(),
],
);
$this->writeTokenRepository->add($newToken);
return $newToken->getToken();
}
/**
* @param string $tokenString
*
* @throws AssertionFailedException
* @throws TokenException
* @throws \Throwable
*
* @return AddTokenResponse
*/
private function createResponse(string $tokenString): AddTokenResponse
{
if (! ($token = $this->readTokenRepository->find($tokenString))) {
LoggerToken::create()->warning(
event: 'creation',
reason: 'token not retrieved successfully after creation',
userId: $this->user->getId(),
);
throw TokenException::errorWhileRetrievingObject();
}
return new AddTokenResponse($token, $tokenString);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/GetToken/GetToken.php | centreon/src/Core/Security/Token/Application/UseCase/GetToken/GetToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\GetToken;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Security\Token\Application\Exception\TokenException;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\JwtToken;
use Core\Security\Token\Domain\Model\TokenTypeEnum;
final class GetToken
{
use LoggerTrait;
public function __construct(
private readonly ReadTokenRepositoryInterface $readTokenRepository,
private readonly ContactInterface $user,
) {
}
public function __invoke(string $tokenName, ?int $userId = null): GetTokenResponse|ResponseStatusInterface
{
try {
$token = $this->readTokenRepository->findByNameAndUserId(
$tokenName,
$userId ?? $this->user->getId()
);
if (
$token === null
|| $token->getType() !== TokenTypeEnum::CMA
) {
return new NotFoundResponse('Token');
}
/** @var JwtToken $token */
return new GetTokenResponse($token, $token->getToken());
} catch (\Throwable $ex) {
$this->error(
"Error while retrieving a token: {$ex->getMessage()}",
[
'user_id' => $this->user->getId(),
'token_name' => $tokenName,
'exception' => ['message' => $ex->getMessage(), 'trace' => $ex->getTraceAsString()],
]
);
return new ErrorResponse(TokenException::errorWhileRetrievingObject()->getMessage());
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/GetToken/GetTokenResponse.php | centreon/src/Core/Security/Token/Application/UseCase/GetToken/GetTokenResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\GetToken;
use Core\Application\Common\UseCase\StandardResponseInterface;
use Core\Security\Token\Domain\Model\Token;
final class GetTokenResponse implements StandardResponseInterface
{
public function __construct(
public Token $token,
public string $tokenString,
) {
}
/**
* @inheritDoc
*/
public function getData(): mixed
{
return $this;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/UseCase/DeleteToken/DeleteToken.php | centreon/src/Core/Security/Token/Application/UseCase/DeleteToken/DeleteToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\UseCase\DeleteToken;
use Adaptation\Log\LoggerToken;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\ForbiddenResponse;
use Core\Application\Common\UseCase\NoContentResponse;
use Core\Application\Common\UseCase\NotFoundResponse;
use Core\Application\Common\UseCase\PresenterInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Security\Token\Application\Exception\TokenException;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Application\Repository\WriteTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\ApiToken;
use Core\Security\Token\Domain\Model\JwtToken;
use Core\Security\Token\Domain\Model\Token;
final class DeleteToken
{
use LoggerTrait;
public function __construct(
private readonly WriteTokenRepositoryInterface $writeTokenRepository,
private readonly ReadTokenRepositoryInterface $readTokenRepository,
private readonly ContactInterface $user,
) {
}
/**
* @param string $tokenName
* @param int $userId
* @param PresenterInterface $presenter
*/
public function __invoke(PresenterInterface $presenter, string $tokenName, ?int $userId = null): void
{
try {
if (! $this->user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_TOKENS_RW)) {
ExceptionLogger::create()->log(
TokenException::deleteNotAllowed(),
[
'message' => 'User doesn\'t have sufficient rights to delete a token',
'user_id' => $this->user->getId(),
'token_name' => $tokenName,
]
);
LoggerToken::create()->warning(
event: 'deletion',
reason: 'insufficient rights',
userId: $this->user->getId(),
tokenName: $tokenName
);
$presenter->setResponseStatus(
new ForbiddenResponse(TokenException::deleteNotAllowed())
);
return;
}
$userId ??= $this->user->getId();
if (! ($token = $this->readTokenRepository->findByNameAndUserId($tokenName, $userId))) {
ExceptionLogger::create()->log(
TokenException::tokenNotFound(),
[
'message' => 'Token not found',
'user_id' => $this->user->getId(),
'token_name' => $tokenName,
]
);
LoggerToken::create()->warning(
event: 'deletion',
reason: 'not found',
userId: $this->user->getId(),
tokenName: $tokenName
);
$presenter->setResponseStatus(new NotFoundResponse('Token'));
return;
}
if (! $this->canUserDeleteToken($this->user, $token)) {
ExceptionLogger::create()->log(
TokenException::notAllowedToDeleteTokenForUser($userId),
[
'message' => 'Not allowed to delete token linked to user who isn\'t the requester',
'token_name' => $tokenName,
'token_type' => $token->getType()->name,
'user_id' => $this->user->getId(),
]
);
LoggerToken::create()->warning(
event: 'deletion',
reason: 'not allowed to delete token for user',
userId: $this->user->getId(),
tokenName: $tokenName,
tokenType: $token->getType()->name
);
$presenter->setResponseStatus(
new ForbiddenResponse(TokenException::notAllowedToDeleteTokenForUser($userId))
);
return;
}
$this->writeTokenRepository->deleteByNameAndUserId($tokenName, $userId);
LoggerToken::create()->success(
event: 'deletion',
userId: $this->user->getId(),
tokenName: $tokenName,
tokenType: $token->getType()->name
);
$presenter->setResponseStatus(new NoContentResponse());
} catch (\Throwable $ex) {
ExceptionLogger::create()->log(
$ex,
[
'user_id' => $this->user->getId(),
'token_name' => $tokenName,
'token_type' => isset($token) ? $token->getType()->name : null,
]
);
LoggerToken::create()->warning(
event: 'deletion',
reason: 'unexpected error',
userId: $this->user->getId(),
tokenName: $tokenName,
tokenType: isset($token) ? $token->getType()->name : null,
exception: $ex
);
$presenter->setResponseStatus(
new ErrorResponse(TokenException::deleteToken())
);
}
}
private function canUserDeleteToken(
ContactInterface $user,
Token $token,
): bool {
return (bool) (
$user->isAdmin()
|| $user->hasRole(Contact::ROLE_MANAGE_TOKENS)
|| ($token instanceof ApiToken && $token->getUserId() === $user->getId())
|| ($token instanceof JwtToken && $token->getCreatorId() === $user->getId())
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/Exception/TokenException.php | centreon/src/Core/Security/Token/Application/Exception/TokenException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\Exception;
class TokenException extends \Exception
{
public const CODE_CONFLICT = 1;
/**
* @return self
*/
public static function addToken(): self
{
return new self(_('Error while adding a token'));
}
/**
* @return self
*/
public static function deleteToken(): self
{
return new self(_('Error while deleting a token'));
}
/**
* @return self
*/
public static function addNotAllowed(): self
{
return new self(_('You are not allowed to add tokens'));
}
/**
* @return self
*/
public static function deleteNotAllowed(): self
{
return new self(_('You are not allowed to delete tokens'));
}
/**
* @return self
*/
public static function errorWhileRetrievingObject(): self
{
return new self(_('Error while retrieving a token'));
}
/**
* @param string $name
*
* @return self
*/
public static function nameAlreadyExists(string $name): self
{
return new self(
sprintf(_("The token name '%s' already exists"), $name),
self::CODE_CONFLICT
);
}
/**
* @param int $userId
*
* @return self
*/
public static function invalidUserId(int $userId): self
{
return new self(
sprintf(_("The user with ID %d doesn't exist"), $userId),
self::CODE_CONFLICT
);
}
/**
* @param int $userId
*
* @return self
*/
public static function notAllowedToCreateTokenForUser(int $userId): self
{
return new self(
sprintf(_('You are not allowed to add tokens linked to user ID %d'), $userId),
self::CODE_CONFLICT
);
}
/**
* @param int $userId
*
* @return self
*/
public static function notAllowedToDeleteTokenForUser(int $userId): self
{
return new self(
sprintf(_('You are not allowed to delete tokens linked to user ID %d'), $userId),
self::CODE_CONFLICT
);
}
/**
* @param \Throwable $ex
*
* @return self
*/
public static function errorWhileSearching(\Throwable $ex): self
{
return new self(_('Error while searching for tokens'), 0, $ex);
}
public static function errorWhilePartiallyUpdatingToken(): self
{
return new self(_('Error while partially updating the token'));
}
public static function notAllowedToPartiallyUpdateToken(): self
{
return new self(_('You are not allowed to partially update the token'));
}
public static function tokenNotFound(): self
{
return new self(_('Token not found'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/Repository/WriteTokenRepositoryInterface.php | centreon/src/Core/Security/Token/Application/Repository/WriteTokenRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\Repository;
use Core\Security\Token\Domain\Model\NewToken;
use Core\Security\Token\Domain\Model\Token;
interface WriteTokenRepositoryInterface
{
/**
* @param NewToken $newToken
*
* @throws \Throwable
*/
public function add(NewToken $newToken): void;
/**
* @param string $tokenName
* @param int $userId
*
* @throws \Throwable
*/
public function deleteByNameAndUserId(string $tokenName, int $userId): void;
/**
* @param Token $token
*
* @throws \Throwable
*/
public function update(Token $token): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Application/Repository/ReadTokenRepositoryInterface.php | centreon/src/Core/Security/Token/Application/Repository/ReadTokenRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Application\Repository;
use Centreon\Infrastructure\RequestParameters\RequestParametersTranslatorException;
use Core\Security\Token\Domain\Model\JwtToken;
use Core\Security\Token\Domain\Model\Token;
interface ReadTokenRepositoryInterface
{
/**
* Find one token.
*
* @param string $tokenString
*
* @throws \Throwable
*
* @return Token|null
*/
public function find(string $tokenString): ?Token;
/**
* Find JWT tokens by their names.
* Response array is indexed by token name.
*
* @param string[] $tokenNames
*
* @return array<string,JwtToken>
*/
public function findByNames(array $tokenNames): array;
/**
* Find a token exists by its name and user ID.
*
* @param string $tokenName
* @param int $userId
*
* @throws \Throwable
*
* @return Token|null
*/
public function findByNameAndUserId(string $tokenName, int $userId): ?Token;
/**
* Determine if a token exists by its name and user ID.
*
* @param int $userId
*
* @throws RequestParametersTranslatorException
* @throws \Throwable
*
* @return list<Token>
*/
public function findByUserIdAndRequestParameters(int $userId): array;
/**
* @throws RequestParametersTranslatorException
* @throws \Throwable
*
* @return list<Token>
*/
public function findByRequestParameters(): array;
/**
* Determine if a token exists by its name.
*
* @param string $tokenName
* @param int $userId
*
* @throws \Throwable
*
* @return bool
*/
public function existsByNameAndUserId(string $tokenName, int $userId): bool;
/**
* Check if the token type is auto.
*
* @param string $token
*
* @throws \Throwable
*
* @return bool
*/
public function isTokenTypeAuto(string $token): bool;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Domain/Model/Token.php | centreon/src/Core/Security/Token/Domain/Model/Token.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\TrimmedString;
abstract class Token
{
public const MAX_TOKEN_NAME_LENGTH = 255;
public const MAX_USER_NAME_LENGTH = 255;
protected string $shortName;
/**
* @param TrimmedString $name
* @param int|null $creatorId
* @param TrimmedString $creatorName
* @param \DateTimeInterface $creationDate
* @param ?\DateTimeInterface $expirationDate
* @param TokenTypeEnum $type
* @param bool $isRevoked
*
* @throws AssertionFailedException
*/
public function __construct(
private readonly TrimmedString $name,
private readonly ?int $creatorId,
private readonly TrimmedString $creatorName,
private readonly \DateTimeInterface $creationDate,
private readonly ?\DateTimeInterface $expirationDate,
private readonly TokenTypeEnum $type,
private bool $isRevoked = false,
) {
Assertion::notEmptyString((string) $name, "{$this->shortName}::name");
Assertion::maxLength((string) $name, self::MAX_TOKEN_NAME_LENGTH, "{$this->shortName}::name");
if ($this->creatorId !== null) {
Assertion::positiveInt($this->creatorId, "{$this->shortName}::creatorId");
}
Assertion::notEmptyString((string) $creatorName, "{$this->shortName}::creatorName");
Assertion::maxLength((string) $creatorName, self::MAX_USER_NAME_LENGTH, "{$this->shortName}::creatorName");
if ($expirationDate !== null) {
Assertion::minDate($expirationDate, $creationDate, "{$this->shortName}::expirationDate");
}
}
public function getName(): string
{
return $this->name->value;
}
public function getCreatorId(): ?int
{
return $this->creatorId;
}
public function getCreatorName(): string
{
return $this->creatorName->value;
}
public function getCreationDate(): \DateTimeInterface
{
return $this->creationDate;
}
public function getExpirationDate(): ?\DateTimeInterface
{
return $this->expirationDate;
}
public function isRevoked(): bool
{
return $this->isRevoked;
}
public function getType(): TokenTypeEnum
{
return $this->type;
}
public function setIsRevoked(bool $isRevoked): void
{
$this->isRevoked = $isRevoked;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Domain/Model/JwtToken.php | centreon/src/Core/Security/Token/Domain/Model/JwtToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Domain\Model;
use Assert\AssertionFailedException;
use Core\Common\Domain\TrimmedString;
final class JwtToken extends Token
{
/**
* @param TrimmedString $name
* @param int|null $creatorId
* @param TrimmedString $creatorName
* @param \DateTimeInterface $creationDate
* @param ?\DateTimeInterface $expirationDate
* @param bool $isRevoked
* @param string $encodingKey for decoding the JWT token
* @param string $tokenString the JWT encoded token
*
* @throws AssertionFailedException
*/
public function __construct(
TrimmedString $name,
?int $creatorId,
TrimmedString $creatorName,
\DateTimeInterface $creationDate,
?\DateTimeInterface $expirationDate,
bool $isRevoked = false,
private readonly string $encodingKey = '',
private readonly string $tokenString = '',
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
parent::__construct(
$name,
$creatorId,
$creatorName,
$creationDate,
$expirationDate,
TokenTypeEnum::CMA,
$isRevoked
);
}
public function getEncodingKey(): string
{
return $this->encodingKey;
}
public function getToken(): string
{
return $this->tokenString;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Domain/Model/ApiToken.php | centreon/src/Core/Security/Token/Domain/Model/ApiToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\TrimmedString;
final class ApiToken extends Token
{
/**
* @param TrimmedString $name
* @param int $userId
* @param TrimmedString $userName
* @param int|null $creatorId
* @param TrimmedString $creatorName
* @param \DateTimeInterface $creationDate
* @param ?\DateTimeInterface $expirationDate
* @param bool $isRevoked
*
* @throws AssertionFailedException
*/
public function __construct(
TrimmedString $name,
private readonly int $userId,
private readonly TrimmedString $userName,
?int $creatorId,
TrimmedString $creatorName,
\DateTimeInterface $creationDate,
?\DateTimeInterface $expirationDate,
bool $isRevoked = false,
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($userId, "{$this->shortName}::userId");
Assertion::notEmptyString((string) $userName, "{$this->shortName}::userName");
Assertion::maxLength((string) $userName, self::MAX_USER_NAME_LENGTH, "{$this->shortName}::userName");
parent::__construct(
$name,
$creatorId,
$creatorName,
$creationDate,
$expirationDate,
TokenTypeEnum::API,
$isRevoked
);
}
public function getUserId(): int
{
return $this->userId;
}
public function getUserName(): string
{
return $this->userName->value;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Domain/Model/NewToken.php | centreon/src/Core/Security/Token/Domain/Model/NewToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\TrimmedString;
abstract class NewToken
{
protected readonly \DateTimeInterface $creationDate;
protected string $shortName;
/**
* @param TrimmedString $name
* @param int $creatorId
* @param TrimmedString $creatorName
* @param \DateTimeInterface|null $expirationDate
* @param TokenTypeEnum $type
*
* @throws AssertionFailedException
* @throws \Exception
*/
public function __construct(
private readonly TrimmedString $name,
private readonly int $creatorId,
private readonly TrimmedString $creatorName,
private readonly ?\DateTimeInterface $expirationDate,
private readonly TokenTypeEnum $type,
) {
$this->creationDate = new \DateTimeImmutable();
if ($this->expirationDate !== null) {
Assertion::minDate($this->expirationDate, $this->creationDate, "{$this->shortName}::expirationDate");
}
Assertion::notEmptyString($this->name->value, "{$this->shortName}::name");
Assertion::maxLength($this->name->value, Token::MAX_TOKEN_NAME_LENGTH, "{$this->shortName}::name");
Assertion::positiveInt($this->creatorId, "{$this->shortName}::creatorId");
Assertion::notEmptyString($this->creatorName->value, "{$this->shortName}::creatorName");
Assertion::maxLength($this->creatorName->value, Token::MAX_USER_NAME_LENGTH, "{$this->shortName}::creatorName");
}
abstract public function getToken(): string;
public function getCreationDate(): \DateTimeInterface
{
return $this->creationDate;
}
public function getExpirationDate(): ?\DateTimeInterface
{
return $this->expirationDate;
}
public function getName(): string
{
return $this->name->value;
}
public function getCreatorId(): int
{
return $this->creatorId;
}
public function getCreatorName(): string
{
return $this->creatorName->value;
}
public function getType(): TokenTypeEnum
{
return $this->type;
}
abstract protected function generateToken(): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Domain/Model/TokenFactory.php | centreon/src/Core/Security/Token/Domain/Model/TokenFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Domain\Model;
use Core\Common\Domain\TrimmedString;
use DateTimeImmutable;
use DateTimeInterface;
use Respect\Validation\Exceptions\DateTimeException;
/**
* @phpstan-type _ApiToken array{
* name: string,
* user_id: int,
* user_name: string,
* creator_id: ?int,
* creator_name: string,
* creation_date: int,
* expiration_date: ?int,
* token_type: string,
* is_revoked: int
* }
*
* @phpstan-type _JwtToken array{
* name: string,
* creator_id: ?int,
* creator_name: string,
* token_type: string,
* creation_date: int,
* expiration_date: ?int,
* is_revoked: int,
* token_string:string,
* encoding_key: string
* }
*
* @phpstan-type _Token array{
* name: string,
* user_id: ?int,
* user_name: ?string,
* creator_id: ?int,
* creator_name: string,
* creation_date: int,
* expiration_date: ?int,
* token_type: string,
* is_revoked: int,
* token_string: ?string,
* encoding_key: ?string
* }
*
* @phpstan-type _NewToken array{
* name: string,
* user_id: ?int,
* creator_id: int,
* creator_name: string,
* expiration_date: ?DateTimeInterface,
* configuration_provider_id: ?int,
* }
*
* @phpstan-type _NewJwtToken array{
* name: string,
* creator_id: int,
* creator_name: string,
* expiration_date: ?DateTimeInterface,
* }
*
* @phpstan-type _NewApiToken array{
* name: string,
* user_id: int,
* creator_id: int,
* creator_name: string,
* expiration_date: ?DateTimeInterface,
* configuration_provider_id: int,
* }
*/
final class TokenFactory
{
/**
* @param TokenTypeEnum $type
* @param _Token $data
*
* @throws DateTimeException
* @return ApiToken|JwtToken
*/
public static function create(
TokenTypeEnum $type,
array $data,
): Token {
if ($type === TokenTypeEnum::CMA) {
/** @var _JwtToken $data */
return new JwtToken(
new TrimmedString($data['name']),
$data['creator_id'],
new TrimmedString($data['creator_name']),
(new DateTimeImmutable())->setTimestamp($data['creation_date']),
$data['expiration_date'] !== null
? (new DateTimeImmutable())->setTimestamp($data['expiration_date'])
: null,
(bool) $data['is_revoked'],
$data['encoding_key'],
$data['token_string'],
);
}
/** @var _ApiToken $data */
return new ApiToken(
new TrimmedString($data['name']),
$data['user_id'],
new TrimmedString($data['user_name']),
$data['creator_id'],
new TrimmedString($data['creator_name']),
(new DateTimeImmutable())->setTimestamp($data['creation_date']),
$data['expiration_date'] !== null
? (new DateTimeImmutable())->setTimestamp($data['expiration_date'])
: null,
(bool) $data['is_revoked'],
);
}
/**
* @param TokenTypeEnum $type
* @param _NewToken $data
*
* @throws DateTimeException
* @return NewApiToken|NewJwtToken
*/
public static function createNew(TokenTypeEnum $type, array $data): NewToken
{
if ($type === TokenTypeEnum::CMA) {
/** @var _NewJwtToken $data */
return new NewJwtToken(
new TrimmedString($data['name']),
$data['creator_id'],
new TrimmedString($data['creator_name']),
$data['expiration_date'],
);
}
/** @var _NewApiToken $data */
return new NewApiToken(
$data['configuration_provider_id'],
new TrimmedString($data['name']),
$data['user_id'],
$data['creator_id'],
new TrimmedString($data['creator_name']),
$data['expiration_date'],
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Domain/Model/TokenTypeEnum.php | centreon/src/Core/Security/Token/Domain/Model/TokenTypeEnum.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Domain\Model;
enum TokenTypeEnum
{
case API;
case CMA;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Domain/Model/NewJwtToken.php | centreon/src/Core/Security/Token/Domain/Model/NewJwtToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Domain\Model;
use Assert\AssertionFailedException;
use Core\Common\Domain\TrimmedString;
use Firebase\JWT\JWT;
use Security\Encryption;
final class NewJwtToken extends NewToken
{
private string $tokenString;
private string $encodingKey;
/**
* @param TrimmedString $name
* @param int $creatorId
* @param TrimmedString $creatorName
* @param \DateTimeInterface|null $expirationDate
*
* @throws AssertionFailedException
* @throws \Exception
*/
public function __construct(
TrimmedString $name,
int $creatorId,
TrimmedString $creatorName,
?\DateTimeInterface $expirationDate,
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
parent::__construct(
$name,
$creatorId,
$creatorName,
$expirationDate,
TokenTypeEnum::CMA
);
$this->generateToken();
}
public function getEncodingKey(): string
{
return $this->encodingKey;
}
public function getToken(): string
{
return $this->tokenString;
}
protected function generateToken(): void
{
$this->encodingKey = Encryption::generateRandomString();
$this->tokenString = JWT::encode(
[
'name' => parent::getName(),
'iat' => parent::getCreationDate()->getTimestamp(),
'exp' => parent::getExpirationDate()?->getTimestamp(),
],
$this->encodingKey,
'HS256'
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Domain/Model/NewApiToken.php | centreon/src/Core/Security/Token/Domain/Model/NewApiToken.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Core\Common\Domain\TrimmedString;
use Security\Encryption;
final class NewApiToken extends NewToken
{
private string $token;
/**
* @param int $configurationProviderId
* @param TrimmedString $name
* @param int $userId
* @param int $creatorId
* @param TrimmedString $creatorName
* @param \DateTimeInterface|null $expirationDate
*
* @throws AssertionFailedException
* @throws \Exception
*/
public function __construct(
private readonly int $configurationProviderId,
TrimmedString $name,
private readonly int $userId,
int $creatorId,
TrimmedString $creatorName,
?\DateTimeInterface $expirationDate,
) {
$this->shortName = (new \ReflectionClass($this))->getShortName();
Assertion::positiveInt($this->userId, "{$this->shortName}::userId");
Assertion::positiveInt($this->configurationProviderId, "{$this->shortName}::configurationProviderId");
parent::__construct(
$name,
$creatorId,
$creatorName,
$expirationDate,
TokenTypeEnum::API,
);
$this->generateToken();
}
public function getToken(): string
{
return $this->token;
}
public function getUserId(): int
{
return $this->userId;
}
public function getConfigurationProviderId(): int
{
return $this->configurationProviderId;
}
protected function generateToken(): void
{
$this->token = Encryption::generateRandomString();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/Voters/TokenVoters.php | centreon/src/Core/Security/Token/Infrastructure/Voters/TokenVoters.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\Voters;
use Centreon\Domain\Contact\Contact;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* @extends Voter<string, mixed>
*/
final class TokenVoters extends Voter
{
public const TOKEN_ADD = 'token_add';
public const TOKEN_LIST = 'token_list';
public const ALLOWED_ATTRIBUTES = [
self::TOKEN_ADD,
self::TOKEN_LIST,
];
/**
* @inheritDoc
*/
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, self::ALLOWED_ATTRIBUTES, true);
}
/**
* @inheritDoc
*/
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (! $user instanceof ContactInterface) {
return false;
}
if (
$subject !== null
&& $subject !== $user->getId()
&& ! $this->canAccessOthersTokens($user, $subject)
) {
return false;
}
return match ($attribute) {
self::TOKEN_ADD, self::TOKEN_LIST => $this->checkUserRights($user),
default => false,
};
}
/**
* Check that user has rights to perform write operations on tokens.
*
* @param ContactInterface $user
*
* @return bool
*/
private function checkUserRights(ContactInterface $user): bool
{
return $user->hasTopologyRole(Contact::ROLE_ADMINISTRATION_AUTHENTICATION_TOKENS_RW);
}
/**
* Check that current user has rights to access other users' tokens.
*
* @param ContactInterface $user
* @param mixed $userId
*
* @return bool
*/
private function canAccessOthersTokens(ContactInterface $user, mixed $userId): bool
{
return
$user->isAdmin()
|| $user->hasRole(Contact::ROLE_MANAGE_TOKENS);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/Serializer/TokenNormalizer.php | centreon/src/Core/Security/Token/Infrastructure/Serializer/TokenNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\Serializer;
use Core\Security\Token\Domain\Model\Token;
use Core\Security\Token\Domain\Model\TokenTypeEnum;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class TokenNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private const ALREADY_CALLED = 'USER_NORMALIZER_ALREADY_CALLED';
/**
* @param Token $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws \Throwable
*
* @return array<string, mixed>
*/
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): array {
$context[self::ALREADY_CALLED] = true;
/** @var array<string, mixed> $response */
$response = $this->normalizer->normalize($object, $format, $context);
if (array_key_exists('user_id', $response) && array_key_exists('user_name', $response)) {
$response['user'] = [
'id' => $response['user_id'],
'name' => $response['user_name'],
];
unset($response['user_id'], $response['user_name']);
}
if (array_key_exists('creator_id', $response) && array_key_exists('creator_name', $response)) {
$response['creator'] = [
'id' => $response['creator_id'],
'name' => $response['creator_name'],
];
unset($response['creator_id'], $response['creator_name']);
}
$response['type'] = $this->enumToTypeConverter($object->getType());
return $response;
}
/**
* @param array<string, mixed> $context
* @param mixed $data
* @param ?string $format
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
return $data instanceof Token;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
Token::class => false,
];
}
/**
* Convert TokenTypeEnum to string value.
*
* @param TokenTypeEnum $code
*
* @return string
*/
private function enumToTypeConverter(TokenTypeEnum $code): string
{
return match ($code) {
TokenTypeEnum::CMA => 'cma',
TokenTypeEnum::API => 'api',
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/Serializer/TokenResponseNormalizer.php | centreon/src/Core/Security/Token/Infrastructure/Serializer/TokenResponseNormalizer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\Serializer;
use Core\Security\Token\Application\UseCase\AddToken\AddTokenResponse;
use Core\Security\Token\Application\UseCase\GetToken\GetTokenResponse;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class TokenResponseNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* @param AddTokenResponse $object
* @param string|null $format
* @param array<string, mixed> $context
*
* @throws \Throwable
*
* @return array<string, mixed>
*/
public function normalize(
mixed $object,
?string $format = null,
array $context = [],
): array {
/**
* @var array<string, mixed> $response
* @var array{groups?:string[]} $context
*/
$response = $this->normalizer->normalize($object->getData()->token, $format, $context);
$matches = array_filter(
$context['groups'] ?? [],
fn (string $group): bool => in_array($group, ['Token:Add', 'Token:Get'], true)
);
if ($matches !== []) {
$response['token'] = $object->getData()->tokenString;
}
return $response;
}
/**
* @param array<string, mixed> $context
* @param mixed $data
* @param ?string $format
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof AddTokenResponse || $data instanceof GetTokenResponse;
}
/**
* @param ?string $format
* @return array<class-string|'*'|'object'|string, bool|null>
*/
public function getSupportedTypes(?string $format): array
{
return [
AddTokenResponse::class => true,
GetTokenResponse::class => true,
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/Repository/DbReadTokenRepository.php | centreon/src/Core/Security/Token/Infrastructure/Repository/DbReadTokenRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\ConnectionInterface;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Centreon\Domain\Log\LoggerTrait;
use Centreon\Domain\RequestParameters\RequestParameters;
use Centreon\Infrastructure\RequestParameters\Interfaces\NormalizerInterface;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
use Core\Common\Domain\Exception\BusinessLogicException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\Common\Infrastructure\Repository\SqlMultipleBindTrait;
use Core\Common\Infrastructure\RequestParameters\Transformer\SearchRequestParametersTransformer;
use Core\Security\Token\Application\Repository\ReadTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\JwtToken;
use Core\Security\Token\Domain\Model\Token;
use Core\Security\Token\Domain\Model\TokenFactory;
use Core\Security\Token\Domain\Model\TokenTypeEnum;
/**
* @phpstan-import-type _ApiToken from \Core\Security\Token\Domain\Model\TokenFactory
* @phpstan-import-type _JwtToken from \Core\Security\Token\Domain\Model\TokenFactory
* @phpstan-import-type _Token from \Core\Security\Token\Domain\Model\TokenFactory
*/
class DbReadTokenRepository extends DatabaseRepository implements ReadTokenRepositoryInterface
{
use LoggerTrait;
use SqlMultipleBindTrait;
private const TYPE_API_MANUAL = 'manual';
private const TYPE_API_AUTO = 'auto';
/** @var SqlRequestParametersTranslator */
private SqlRequestParametersTranslator $sqlRequestTranslator;
public function __construct(
ConnectionInterface $connection,
SqlRequestParametersTranslator $sqlRequestTranslator,
) {
parent::__construct($connection);
$this->sqlRequestTranslator = $sqlRequestTranslator;
$this->sqlRequestTranslator
->getRequestParameters()
->setConcordanceStrictMode(RequestParameters::CONCORDANCE_MODE_STRICT);
$this->sqlRequestTranslator->setConcordanceArray([
'user.id' => 'user_id',
'user.name' => 'user_name',
'token_name' => 'name',
'creator.id' => 'creator_id',
'creator.name' => 'creator_name',
'creation_date' => 'creation_date',
'expiration_date' => 'expiration_date',
'is_revoked' => 'is_revoked',
'type' => 'token_type',
]);
$normaliserClass = new class () implements NormalizerInterface {
/**
* @inheritDoc
*/
public function normalize($valueToNormalize)
{
return $valueToNormalize;
}
};
$this->sqlRequestTranslator->addNormalizer(
'creation_date',
$normaliserClass
);
$this->sqlRequestTranslator->addNormalizer(
'expiration_date',
$normaliserClass
);
}
public function findByUserIdAndRequestParameters(int $userId): array
{
return $this->findAllByRequestParameters($userId);
}
/**
* @inheritDoc
*/
public function findByRequestParameters(): array
{
return $this->findAllByRequestParameters(null);
}
/**
* @inheritDoc
*/
public function find(string $tokenString): ?Token
{
try {
$result = $this->connection->fetchAssociative(
<<<'SQL'
SELECT
sat.token_name as name,
sat.user_id,
contact.contact_name as user_name,
sat.creator_id,
sat.creator_name,
provider_token.creation_date,
provider_token.expiration_date,
sat.is_revoked,
null as token_string,
null as encoding_key,
'API' as token_type
FROM security_authentication_tokens sat
INNER JOIN security_token provider_token
ON provider_token.id = sat.provider_token_id
INNER JOIN contact
ON contact.contact_id = sat.user_id
WHERE sat.token = :tokenString
AND sat.token_type = :tokenApiType
UNION
SELECT
token_name as name,
null as user_id,
null as user_name,
creator_id,
creator_name,
creation_date,
expiration_date,
is_revoked,
token_string,
encoding_key,
'JWT' as token_type
FROM jwt_tokens
WHERE token_string = :tokenString
SQL,
QueryParameters::create([
QueryParameter::string('tokenString', $tokenString),
QueryParameter::string('tokenApiType', self::TYPE_API_MANUAL),
])
);
if ($result !== []) {
/** @var _Token $result */
return TokenFactory::create(
$result['token_type'] === 'JWT' ? TokenTypeEnum::CMA : TokenTypeEnum::API,
$result
);
}
return null;
} catch (BusinessLogicException $exception) {
$this->error(
'Finding token by token string failed',
['exception' => $exception->getContext()]
);
throw new RepositoryException(
'Finding token by token string failed',
['exception' => $exception->getContext()],
$exception
);
} catch (\Throwable $exception) {
$this->error(
"Finding token by token string failed : {$exception->getMessage()}",
[
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
]
);
throw new RepositoryException(
"Finding token by token string failed : {$exception->getMessage()}",
[
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
],
$exception
);
}
}
/**
* @inheritDoc
*/
public function findByNames(array $tokenNames): array
{
if ($tokenNames === []) {
return [];
}
try {
[$tokenBindValues, $tokensQuery] = $this->createMultipleBindQuery($tokenNames, ':tokenName_');
$queryParams = QueryParameters::create([]);
foreach ($tokenBindValues as $key => $value) {
/** @var string $value */
$queryParams->add($key, QueryParameter::string($key, $value));
}
$data = $this->connection->fetchAllAssociative(
<<<SQL
SELECT
token_name as name,
null as user_id,
null as user_name,
creator_id,
creator_name,
creation_date,
expiration_date,
is_revoked,
token_string,
encoding_key,
'JWT' as token_type
FROM jwt_tokens
WHERE token_name IN ({$tokensQuery})
SQL,
$queryParams
);
$results = [];
foreach ($data as $row) {
/** @var _Token $row */
$results[$row['name']] = TokenFactory::create(
TokenTypeEnum::CMA,
$row
);
}
/** @var array<string,JwtToken> $results */
return $results;
} catch (BusinessLogicException $exception) {
$this->error(
'Finding tokens by names failed',
['exception' => $exception->getContext()]
);
throw new RepositoryException(
'Finding tokens by names failed',
['exception' => $exception->getContext()],
$exception
);
} catch (\Throwable $exception) {
$this->error(
"Finding tokens by names failed: {$exception->getMessage()}",
[
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
]
);
throw new RepositoryException(
"Finding
tokens by names failed: {$exception->getMessage()}",
[
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
],
$exception
);
}
}
/**
* @inheritDoc
*/
public function findByNameAndUserId(string $tokenName, int $userId): ?Token
{
try {
$result = $this->connection->fetchAssociative(
<<<'SQL'
SELECT
sat.token_name as name,
sat.user_id,
contact.contact_name as user_name,
sat.creator_id,
sat.creator_name,
provider_token.creation_date,
provider_token.expiration_date,
sat.is_revoked,
null as token_string,
null as encoding_key,
'API' as token_type
FROM security_authentication_tokens sat
INNER JOIN security_token provider_token
ON provider_token.id = sat.provider_token_id
INNER JOIN contact
ON contact.contact_id = sat.user_id
WHERE sat.token_name = :tokenName
AND sat.user_id = :userId
AND sat.token_type = :tokenApiType
UNION
SELECT
token_name as name,
null as user_id,
null as user_name,
creator_id,
creator_name,
creation_date,
expiration_date,
is_revoked,
token_string,
encoding_key,
'JWT' as token_type
FROM jwt_tokens
WHERE token_name = :tokenName
SQL,
QueryParameters::create([
QueryParameter::string('tokenName', $tokenName),
QueryParameter::int('userId', $userId),
QueryParameter::string('tokenApiType', self::TYPE_API_MANUAL),
])
);
if ($result === false) {
return null;
}
/** @var _Token $result */
return TokenFactory::create(
$result['token_type'] === 'JWT' ? TokenTypeEnum::CMA : TokenTypeEnum::API,
$result
);
} catch (BusinessLogicException $exception) {
$this->error(
'Finding token by name and user ID failed',
['token_name' => $tokenName, 'user_id' => $userId, 'exception' => $exception->getContext()]
);
throw new RepositoryException(
'Finding token by name and user ID failed',
['token_name' => $tokenName, 'user_id' => $userId, 'exception' => $exception->getContext()],
$exception
);
} catch (\Throwable $exception) {
$this->error(
"Finding token by token string failed: {$exception->getMessage()}",
[
'token' => $tokenName,
'user_id' => $userId,
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
]
);
throw new RepositoryException(
"Finding token by token string failed: {$exception->getMessage()}",
[
'token_name' => $tokenName,
'user_id' => $userId,
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
],
$exception
);
}
}
/**
* @inheritDoc
*/
public function existsByNameAndUserId(string $tokenName, int $userId): bool
{
try {
$result = $this->connection->fetchOne(
<<<'SQL'
SELECT 1
FROM security_authentication_tokens sat
WHERE sat.token_name = :tokenName
AND sat.user_id = :userId
AND sat.token_type = :tokenApiType
UNION
SELECT 1
FROM jwt_tokens
WHERE token_name = :tokenName
SQL,
QueryParameters::create([
QueryParameter::string('tokenName', $tokenName),
QueryParameter::int('userId', $userId),
QueryParameter::string('tokenApiType', self::TYPE_API_MANUAL),
]),
);
return (bool) $result;
} catch (BusinessLogicException $exception) {
$this->error(
'Finding token by name and user ID failed',
['token_name' => $tokenName, 'user_id' => $userId, 'exception' => $exception->getContext()]
);
throw new RepositoryException(
'Finding token by name and user ID failed',
['token_name' => $tokenName, 'user_id' => $userId, 'exception' => $exception->getContext()],
$exception
);
} catch (\Throwable $exception) {
$this->error(
"Finding token by name and user ID failed: {$exception->getMessage()}",
[
'token' => $tokenName,
'user_id' => $userId,
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
]
);
throw new RepositoryException(
"Finding token by name and user ID failed: {$exception->getMessage()}",
[
'token_name' => $tokenName,
'user_id' => $userId,
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
],
$exception
);
}
}
/**
* @inheritDoc
*/
public function isTokenTypeAuto(string $token): bool
{
try {
$result = $this->connection->fetchAssociative(
<<<'SQL'
SELECT 1
FROM security_authentication_tokens sat
WHERE sat.token = :token
AND sat.token_type = :tokenType
SQL,
QueryParameters::create([
QueryParameter::string('token', $token),
QueryParameter::string('tokenType', self::TYPE_API_AUTO),
])
);
return ! empty($result);
} catch (BusinessLogicException $exception) {
$this->error(
'Check is token of type auto failed',
['exception' => $exception->getContext()]
);
throw new RepositoryException(
'Check is token of type auto failed',
['exception' => $exception->getContext()],
$exception
);
}
}
/**
* @param int|null $userId
*
* @throws BusinessLogicException|\Throwable
*
* @return list<Token>
*/
private function findAllByRequestParameters(?int $userId): array
{
try {
// Search
$search = $this->sqlRequestTranslator->translateSearchParameterToSql();
// Sort
$sort = $this->sqlRequestTranslator->translateSortParameterToSql();
$sort = ! is_null($sort)
? $sort
: ' ORDER BY creation_date ASC';
// Pagination
$pagination = $this->sqlRequestTranslator->translatePaginationToSql();
$queryParameters = SearchRequestParametersTransformer::reverseToQueryParameters(
$this->sqlRequestTranslator->getSearchValues()
)
->add('tokenApiType', QueryParameter::string('tokenApiType', self::TYPE_API_MANUAL));
$userIdFilter = $userId !== null ? ' AND user_id = :user_id ' : '';
$creatorIdFilter = $userId !== null ? ' WHERE creator_id = :user_id ' : '';
if ($userId !== null) {
$queryParameters->add('user_id', QueryParameter::int('user_id', $userId));
}
$apiTokens = <<<SQL
SELECT
sat.token_name as name,
sat.user_id,
contact.contact_name as user_name,
sat.creator_id,
sat.creator_name,
provider_token.creation_date,
provider_token.expiration_date,
sat.is_revoked,
'API' as token_type,
null as token_string,
null as encoding_key
FROM security_authentication_tokens sat
INNER JOIN security_token provider_token
ON provider_token.id = sat.provider_token_id
INNER JOIN contact
ON contact.contact_id = sat.user_id
WHERE sat.token_type = :tokenApiType
{$userIdFilter}
SQL;
$jwtTokens = <<<SQL
SELECT
token_name as name,
null as user_id,
null as user_name,
creator_id,
creator_name,
creation_date,
expiration_date,
is_revoked,
'CMA' as token_type,
token_string,
encoding_key
FROM jwt_tokens
{$creatorIdFilter}
SQL;
$results = $this->connection->fetchAllAssociative(
<<<SQL
SELECT SQL_CALC_FOUND_ROWS
name,
user_id,
user_name,
creator_id,
creator_name,
creation_date,
expiration_date,
is_revoked,
token_type,
token_string,
encoding_key
FROM (
{$apiTokens}
UNION
{$jwtTokens}
) AS tokenUnion
{$search}
{$sort}
{$pagination}
SQL,
$queryParameters
);
$tokens = [];
foreach ($results as $result) {
/** @var _Token $result */
$tokens[] = TokenFactory::create(
$result['token_type'] === 'CMA' ? TokenTypeEnum::CMA : TokenTypeEnum::API,
$result
);
}
// get total for pagination
if (($total = $this->connection->fetchOne('SELECT FOUND_ROWS() from contact')) !== false) {
/** @var int $total */
$this->sqlRequestTranslator->getRequestParameters()->setTotal((int) $total);
}
return $tokens;
} catch (BusinessLogicException $exception) {
$this->error(
'Find tokens failed',
['user_id' => $userId, 'exception' => $exception->getContext()]
);
throw new RepositoryException(
'Find tokens failed',
['user_id' => $userId, 'exception' => $exception->getContext()],
$exception
);
} catch (\Throwable $exception) {
$this->error(
"Find tokens failed: {$exception->getMessage()}",
[
'user_id' => $userId,
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
]
);
throw new RepositoryException(
"Find tokens failed: {$exception->getMessage()}",
[
'user_id' => $userId,
'exception' => [
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
],
],
$exception
);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/Repository/DbWriteTokenRepository.php | centreon/src/Core/Security/Token/Infrastructure/Repository/DbWriteTokenRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\Repository;
use Adaptation\Database\Connection\Collection\QueryParameters;
use Adaptation\Database\Connection\Exception\ConnectionException;
use Adaptation\Database\Connection\ValueObject\QueryParameter;
use Centreon\Domain\Log\LoggerTrait;
use Core\Common\Domain\Exception\BusinessLogicException;
use Core\Common\Domain\Exception\CollectionException;
use Core\Common\Domain\Exception\RepositoryException;
use Core\Common\Domain\Exception\ValueObjectException;
use Core\Common\Infrastructure\Repository\DatabaseRepository;
use Core\Security\Token\Application\Repository\WriteTokenRepositoryInterface;
use Core\Security\Token\Domain\Model\ApiToken;
use Core\Security\Token\Domain\Model\JwtToken;
use Core\Security\Token\Domain\Model\NewApiToken;
use Core\Security\Token\Domain\Model\NewJwtToken;
use Core\Security\Token\Domain\Model\NewToken;
use Core\Security\Token\Domain\Model\Token;
class DbWriteTokenRepository extends DatabaseRepository implements WriteTokenRepositoryInterface
{
use LoggerTrait;
private const TYPE_API_MANUAL = 'manual';
/**
* @inheritDoc
*/
public function deleteByNameAndUserId(string $tokenName, int $userId): void
{
try {
$this->connection->delete(
<<<'SQL'
DELETE tokens FROM security_token tokens
JOIN security_authentication_tokens sat
ON sat.provider_token_id = tokens.id
WHERE sat.token_name = :tokenName
AND sat.user_id = :userId
SQL,
QueryParameters::create([
QueryParameter::string('tokenName', $tokenName),
QueryParameter::int('userId', $userId),
])
);
$this->connection->delete(
$this->connection->createQueryBuilder()->delete('jwt_tokens')
->where('token_name = :tokenName')
->andWhere('creator_id = :userId')
->getQuery(),
QueryParameters::create([
QueryParameter::string('tokenName', $tokenName),
QueryParameter::int('userId', $userId),
])
);
} catch (BusinessLogicException $exception) {
$this->error(
"Delete token failed : {$exception->getMessage()}",
[
'token_name' => $tokenName,
'user_id' => $userId,
'exception' => $exception->getContext(),
]
);
throw new RepositoryException(
"Delete token failed : {$exception->getMessage()}",
['token_name' => $tokenName, 'user_id' => $userId],
$exception
);
}
}
/**
* @inheritDoc
*/
public function add(NewToken $newToken): void
{
try {
if ($newToken instanceof NewJwtToken) {
$this->addJwtToken($newToken);
} else {
/** @var NewApiToken $newToken */
$this->addApiToken($newToken);
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
$this->error(
"Add token failed : {$exception->getMessage()}",
[
'token_name' => $newToken->getName(),
'creator_id' => $newToken->getCreatorId(),
'exception' => $exception->getContext(),
]
);
throw new RepositoryException(
"Add token failed : {$exception->getMessage()}",
['token_name' => $newToken->getName(), 'creator_id' => $newToken->getCreatorId()],
$exception
);
}
}
/**
* @inheritDoc
*/
public function update(Token $token): void
{
try {
if ($token instanceof JwtToken) {
$this->updateJwtToken($token);
} else {
/** @var ApiToken $token */
$this->updateApiToken($token);
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
$this->error(
"Update token failed : {$exception->getMessage()}",
[
'token_name' => $token->getName(),
'creator_id' => $token->getCreatorId(),
'exception' => $exception->getContext(),
]
);
throw new RepositoryException(
"Update token failed : {$exception->getMessage()}",
['token_name' => $token->getName(), 'creator_id' => $token->getCreatorId()],
$exception
);
}
}
// ------------------------------ JWT TOKEN METHODS ------------------------------
/**
* @param NewJwtToken $token
* @throws \Throwable
*/
private function addJwtToken(NewJwtToken $token): void
{
$this->connection->insert(
$this->connection->createQueryBuilder()->insert('jwt_tokens')
->values([
'token_string' => ':tokenString',
'token_name' => ':tokenName',
'creator_id' => ':creatorId',
'creator_name' => ':creatorName',
'encoding_key' => ':encodingKey',
'creation_date' => ':createdAt',
'expiration_date' => ':expireAt',
])
->getQuery(),
QueryParameters::create([
QueryParameter::string('tokenString', $token->getToken()),
QueryParameter::string('tokenName', $token->getName()),
QueryParameter::int('creatorId', $token->getCreatorId()),
QueryParameter::string('creatorName', $token->getCreatorName()),
QueryParameter::string('encodingKey', $token->getEncodingKey()),
QueryParameter::int('createdAt', $token->getCreationDate()->getTimestamp()),
QueryParameter::int('expireAt', $token->getExpirationDate()?->getTimestamp()),
])
);
}
/**
* @param JwtToken $token
* @throws \Throwable
*/
private function updateJwtToken(JwtToken $token): void
{
$this->connection->update(
$this->connection->createQueryBuilder()->update('jwt_tokens')
->set('is_revoked', ':isRevoked')
->where('token_name = :tokenName')
->getQuery(),
QueryParameters::create([
QueryParameter::int('isRevoked', (int) $token->isRevoked()),
QueryParameter::string('tokenName', $token->getName()),
])
);
}
// ------------------------------ API TOKEN METHODS ------------------------------
/**
* @param ApiToken $token
* @throws \Throwable
*/
private function updateApiToken(ApiToken $token): void
{
$this->connection->update(
$this->connection->createQueryBuilder()->update('security_authentication_tokens')
->set('is_revoked', ':isRevoked')
->where('token_name = :tokenName')
->andWhere('user_id = :userId')
->getQuery(),
QueryParameters::create([
QueryParameter::int('isRevoked', (int) $token->isRevoked()),
QueryParameter::string('tokenName', $token->getName()),
QueryParameter::int('userId', $token->getUserId()),
])
);
}
private function addApiToken(NewApiToken $token): void
{
$isTransactionActive = $this->connection->isTransactionActive();
try {
if (! $isTransactionActive) {
$this->connection->startTransaction();
}
$securityTokenId = $this->insertSecurityToken($token);
$this->insertSecurityAuthenticationToken($token, $securityTokenId);
if (! $isTransactionActive) {
$this->connection->commitTransaction();
}
} catch (ValueObjectException|CollectionException|ConnectionException $exception) {
$this->error(
"Add token failed : {$exception->getMessage()}",
[
'token_name' => $token->getName(),
'creator_id' => $token->getCreatorId(),
'exception' => $exception->getContext(),
]
);
if (! $isTransactionActive) {
try {
$this->connection->rollBackTransaction();
} catch (ConnectionException $rollbackException) {
$this->error(
"Rollback failed for tokens: {$rollbackException->getMessage()}",
[
'token_name' => $token->getName(),
'creator_id' => $token->getCreatorId(),
'exception' => $rollbackException->getContext(),
]
);
throw new RepositoryException(
"Rollback failed for tokens: {$rollbackException->getMessage()}",
['token' => $token],
$rollbackException
);
}
}
throw new RepositoryException(
"Add token failed : {$exception->getMessage()}",
['token_name' => $token->getName(), 'creator_id' => $token->getCreatorId()],
$exception
);
}
}
/**
* @param NewApiToken $token
*
* @throws \Throwable
*/
private function insertSecurityToken(NewToken $token): int
{
$this->connection->insert(
$this->connection->createQueryBuilder()->insert('security_token')
->values([
'token' => ':token',
'creation_date' => ':createdAt',
'expiration_date' => ':expireAt',
])
->getQuery(),
QueryParameters::create([
QueryParameter::string('token', $token->getToken()),
QueryParameter::int('createdAt', $token->getCreationDate()->getTimestamp()),
QueryParameter::int('expireAt', $token->getExpirationDate()?->getTimestamp()),
])
);
return (int) $this->connection->getLastInsertId();
}
/**
* @param NewApiToken $token
* @param int $securityTokenId
*
* @throws \Throwable
*/
private function insertSecurityAuthenticationToken(
NewApiToken $token,
int $securityTokenId,
): void {
$this->connection->insert(
$this->connection->createQueryBuilder()->insert('security_authentication_tokens')
->values([
'token' => ':token',
'provider_token_id' => ':tokenId',
'provider_configuration_id' => ':configurationId',
'user_id' => ':userId',
'token_name' => ':tokenName',
'token_type' => ':tokenType',
'creator_id' => ':creatorId',
'creator_name' => ':creatorName',
])
->getQuery(),
QueryParameters::create([
QueryParameter::string('token', $token->getToken()),
QueryParameter::int('tokenId', $securityTokenId),
QueryParameter::int('configurationId', $token->getConfigurationProviderId()),
QueryParameter::int('userId', $token->getUserId()),
QueryParameter::string('tokenName', $token->getName()),
QueryParameter::string('tokenType', self::TYPE_API_MANUAL),
QueryParameter::int('creatorId', $token->getCreatorId()),
QueryParameter::string('creatorName', $token->getCreatorName()),
])
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/API/FindTokens/FindTokensController.php | centreon/src/Core/Security/Token/Infrastructure/API/FindTokens/FindTokensController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\API\FindTokens;
use Centreon\Application\Controller\AbstractController;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Core\Security\Token\Application\UseCase\FindTokens\FindTokens;
use Core\Security\Token\Infrastructure\Voters\TokenVoters;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
TokenVoters::TOKEN_LIST,
null,
'You are not allowed to list the tokens',
Response::HTTP_FORBIDDEN
)]
final class FindTokensController extends AbstractController
{
/**
* @param FindTokens $useCase
* @param StandardPresenter $presenter
*
* @return Response
*/
public function __invoke(FindTokens $useCase, StandardPresenter $presenter): Response
{
$response = $useCase();
if ($response instanceof ResponseStatusInterface) {
return $this->createResponse($response);
}
return JsonResponse::fromJsonString(
$presenter->present(
$response,
[
'groups' => ['Token:List'],
]
),
Response::HTTP_OK
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/API/PartialUpdateToken/PartialUpdateTokenController.php | centreon/src/Core/Security/Token/Infrastructure/API/PartialUpdateToken/PartialUpdateTokenController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\API\PartialUpdateToken;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Application\Common\UseCase\InvalidArgumentResponse;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Security\Token\Application\Exception\TokenException;
use Core\Security\Token\Application\UseCase\PartialUpdateToken\PartialUpdateToken;
use Core\Security\Token\Application\UseCase\PartialUpdateToken\PartialUpdateTokenRequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class PartialUpdateTokenController extends AbstractController
{
use LoggerTrait;
/**
* @param Request $request
* @param DefaultPresenter $presenter
* @param PartialUpdateToken $useCase
* @param string $tokenName
* @param int $userId
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
Request $request,
DefaultPresenter $presenter,
PartialUpdateToken $useCase,
string $tokenName,
int $userId,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
try {
/**
* @var array{
* is_revoked?: bool
* } $data
*/
$data = $this->validateAndRetrieveDataSent($request, __DIR__ . '/PartialUpdateTokenSchema.json');
$requestDto = new PartialUpdateTokenRequest();
if (array_key_exists('is_revoked', $data)) {
$requestDto->isRevoked = $data['is_revoked'];
}
$useCase($requestDto, $presenter, $tokenName, $userId);
} catch (\InvalidArgumentException $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(new InvalidArgumentResponse($ex));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(
new ErrorResponse(TokenException::errorWhilePartiallyUpdatingToken())
);
}
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/API/AddToken/AddTokenInput.php | centreon/src/Core/Security/Token/Infrastructure/API/AddToken/AddTokenInput.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\API\AddToken;
use Symfony\Component\Validator\Constraints as Assert;
final readonly class AddTokenInput
{
public const API_TYPE = 'api';
public const CMA_TYPE = 'cma';
/**
* @param string $name
* @param ?string $expirationDate
* @param string $type
* @param int $userId
*/
public function __construct(
#[Assert\NotNull()]
#[Assert\Type('string')]
public mixed $name,
#[Assert\DateTime(
format: \DateTimeInterface::ATOM,
)]
public mixed $expirationDate,
#[Assert\NotNull()]
#[Assert\Choice(choices: [self::API_TYPE, self::CMA_TYPE])]
public mixed $type,
#[Assert\NotNull()]
#[Assert\Type('int')]
public mixed $userId,
) {
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/API/AddToken/AddTokenController.php | centreon/src/Core/Security/Token/Infrastructure/API/AddToken/AddTokenController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\API\AddToken;
use Centreon\Application\Controller\AbstractController;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Core\Security\Token\Application\UseCase\AddToken\AddToken;
use Core\Security\Token\Infrastructure\Voters\TokenVoters;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(
TokenVoters::TOKEN_ADD,
null,
'You are not allowed to add tokens',
Response::HTTP_FORBIDDEN
)]
final class AddTokenController extends AbstractController
{
use LoggerTrait;
/**
* @param AddTokenInput $request
* @param AddToken $useCase
* @param StandardPresenter $presenter
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
#[MapRequestPayload()] AddTokenInput $request,
AddToken $useCase,
StandardPresenter $presenter,
): Response {
$response = $useCase(AddTokenRequestTransformer::transform($request));
if ($response instanceof ResponseStatusInterface) {
return $this->createResponse($response);
}
return JsonResponse::fromJsonString(
$presenter->present(
$response,
[
'groups' => ['Token:Add'],
]
),
Response::HTTP_CREATED
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/API/AddToken/AddTokenRequestTransformer.php | centreon/src/Core/Security/Token/Infrastructure/API/AddToken/AddTokenRequestTransformer.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\API\AddToken;
use Core\Security\Token\Application\UseCase\AddToken\AddTokenRequest;
use Core\Security\Token\Domain\Model\TokenTypeEnum;
final class AddTokenRequestTransformer
{
public static function transform(AddTokenInput $input): AddTokenRequest
{
$expirationDate = $input->expirationDate !== null
? \DateTime::createFromFormat(\DateTimeInterface::ATOM, $input->expirationDate)
: null;
if ($expirationDate === false) {
throw new \InvalidArgumentException('Invalid date format');
}
return new AddTokenRequest(
$input->name,
$input->type === 'cma' ? TokenTypeEnum::CMA : TokenTypeEnum::API,
$input->userId,
$expirationDate
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/API/GetToken/GetTokenController.php | centreon/src/Core/Security/Token/Infrastructure/API/GetToken/GetTokenController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\API\GetToken;
use Centreon\Application\Controller\AbstractController;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Infrastructure\Common\Api\StandardPresenter;
use Core\Security\Token\Application\UseCase\GetToken\GetToken;
use Core\Security\Token\Infrastructure\Voters\TokenVoters;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsGranted;
final class GetTokenController extends AbstractController
{
#[IsGranted(
TokenVoters::TOKEN_LIST,
'userId',
'You are not allowed to access API tokens',
Response::HTTP_FORBIDDEN
)]
public function __invoke(
StandardPresenter $presenter,
GetToken $useCase,
string $tokenName,
?int $userId = null,
): Response {
$response = $useCase($tokenName, $userId);
if ($response instanceof ResponseStatusInterface) {
return $this->createResponse($response);
}
return JsonResponse::fromJsonString($presenter->present(
$response,
['groups' => ['Token:Get']]
));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Token/Infrastructure/API/DeleteToken/DeleteTokenController.php | centreon/src/Core/Security/Token/Infrastructure/API/DeleteToken/DeleteTokenController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Token\Infrastructure\API\DeleteToken;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Security\Token\Application\UseCase\DeleteToken\DeleteToken;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class DeleteTokenController extends AbstractController
{
/**
* @param DefaultPresenter $presenter
* @param DeleteToken $useCase
* @param string $tokenName
* @param int $userId
*
* @throws AccessDeniedException
*
* @return Response
*/
public function __invoke(
DefaultPresenter $presenter,
DeleteToken $useCase,
string $tokenName,
?int $userId = null,
): Response {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter, $tokenName, $userId);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfigurationPresenterInterface.php | centreon/src/Core/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfigurationPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\FindVaultConfiguration;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface FindVaultConfigurationPresenterInterface
{
public function presentResponse(FindVaultConfigurationResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfigurationResponse.php | centreon/src/Core/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfigurationResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\FindVaultConfiguration;
final class FindVaultConfigurationResponse
{
public string $address = '';
public int $port = 443;
public string $rootPath = '';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfiguration.php | centreon/src/Core/Security/Vault/Application/UseCase/FindVaultConfiguration/FindVaultConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\FindVaultConfiguration;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{ErrorResponse, ForbiddenResponse, NotFoundResponse};
use Core\Security\Vault\Application\Exceptions\VaultConfigurationException;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
final class FindVaultConfiguration
{
use LoggerTrait;
/**
* @param ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository
* @param ContactInterface $user
*/
public function __construct(
private readonly ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository,
private readonly ContactInterface $user,
) {
}
/**
* @param FindVaultConfigurationPresenterInterface $presenter
*/
public function __invoke(
FindVaultConfigurationPresenterInterface $presenter,
): void {
try {
if (! $this->user->isAdmin()) {
$this->error('User is not admin', ['user' => $this->user->getName()]);
$presenter->presentResponse(
new ForbiddenResponse(VaultConfigurationException::onlyForAdmin()->getMessage())
);
return;
}
if (! $this->readVaultConfigurationRepository->exists()) {
$this->info('Vault configuration not found');
$presenter->presentResponse(
new NotFoundResponse('Vault configuration')
);
return;
}
/** @var VaultConfiguration $vaultConfiguration */
$vaultConfiguration = $this->readVaultConfigurationRepository->find();
$presenter->presentResponse($this->createResponse($vaultConfiguration));
} catch (\Throwable $ex) {
$this->error(
'An error occurred in while getting vault configuration',
['trace' => $ex->getTraceAsString()]
);
$presenter->presentResponse(
new ErrorResponse(VaultConfigurationException::impossibleToFind()->getMessage())
);
}
}
/**
* @param VaultConfiguration $vaultConfiguration
*
* @return FindVaultConfigurationResponse
*/
private function createResponse(VaultConfiguration $vaultConfiguration): FindVaultConfigurationResponse
{
$findVaultConfigurationResponse = new FindVaultConfigurationResponse();
$findVaultConfigurationResponse->address = $vaultConfiguration->getAddress();
$findVaultConfigurationResponse->port = $vaultConfiguration->getPort();
$findVaultConfigurationResponse->rootPath = $vaultConfiguration->getRootPath();
return $findVaultConfigurationResponse;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialDto.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials;
class CredentialDto
{
public ?int $resourceId = null;
public CredentialTypeEnum $type = CredentialTypeEnum::TYPE_HOST;
public string $name = '';
public string $value = '';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialMigrator.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialMigrator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials;
use Centreon\Domain\Log\LoggerTrait;
use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\Broker\Application\Repository\ReadBrokerInputOutputRepositoryInterface;
use Core\Broker\Application\Repository\WriteBrokerInputOutputRepositoryInterface;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Application\UseCase\VaultTrait;
use Core\Common\Infrastructure\Repository\AbstractVaultRepository;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface;
use Core\HostTemplate\Domain\Model\HostTemplate;
use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Option\Application\Repository\WriteOptionRepositoryInterface;
use Core\Option\Domain\Option;
use Core\PollerMacro\Application\Repository\WritePollerMacroRepositoryInterface;
use Core\PollerMacro\Domain\Model\PollerMacro;
use Core\Security\ProviderConfiguration\Application\OpenId\Repository\WriteOpenIdConfigurationRepositoryInterface;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\Migrator\AccCredentialMigratorInterface;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
/**
* @implements \IteratorAggregate<CredentialRecordedDto|CredentialErrorDto>
*
* @phpstan-type _ExistingUuids array{
* hosts:string[],
* services:string[],
* pollerMacro:?string,
* openId:?string,
* brokerConfigs:string[],
* accs: string[]
* }
*/
class CredentialMigrator implements \IteratorAggregate, \Countable
{
use LoggerTrait;
use VaultTrait;
/**
* @param \Countable&\Traversable<CredentialDto> $credentials
* @param WriteVaultRepositoryInterface $writeVaultRepository
* @param WriteHostRepositoryInterface $writeHostRepository
* @param WriteHostTemplateRepositoryInterface $writeHostTemplateRepository
* @param WriteHostMacroRepositoryInterface $writeHostMacroRepository
* @param WriteServiceMacroRepositoryInterface $writeServiceMacroRepository
* @param WriteOptionRepositoryInterface $writeOptionRepository
* @param WritePollerMacroRepositoryInterface $writePollerMacroRepository
* @param ReadBrokerInputOutputRepositoryInterface $readBrokerInputOutputRepository
* @param WriteBrokerInputOutputRepositoryInterface $writeBrokerInputOutputRepository
* @param WriteAccRepositoryInterface $writeAccRepository
* @param AccCredentialMigratorInterface[] $accCredentialMigrators
* @param Host[] $hosts
* @param HostTemplate[] $hostTemplates
* @param Macro[] $hostMacros
* @param Macro[] $serviceMacros
* @param PollerMacro[] $pollerMacros,
* @param WriteOpenIdConfigurationRepositoryInterface $writeOpenIdConfigurationRepository
* @param Configuration $openIdProviderConfiguration
* @param array<int,BrokerInputOutput[]> $brokerInputOutputs
* @param Acc[] $accs
*/
public function __construct(
private readonly \Traversable&\Countable $credentials,
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly WriteHostRepositoryInterface $writeHostRepository,
private readonly WriteHostTemplateRepositoryInterface $writeHostTemplateRepository,
private readonly WriteHostMacroRepositoryInterface $writeHostMacroRepository,
private readonly WriteServiceMacroRepositoryInterface $writeServiceMacroRepository,
private readonly WriteOptionRepositoryInterface $writeOptionRepository,
private readonly WritePollerMacroRepositoryInterface $writePollerMacroRepository,
private readonly WriteOpenIdConfigurationRepositoryInterface $writeOpenIdConfigurationRepository,
private readonly ReadBrokerInputOutputRepositoryInterface $readBrokerInputOutputRepository,
private readonly WriteBrokerInputOutputRepositoryInterface $writeBrokerInputOutputRepository,
private readonly WriteAccRepositoryInterface $writeAccRepository,
private readonly array $accCredentialMigrators,
private readonly array $hosts,
private readonly array $hostTemplates,
private readonly array $hostMacros,
private readonly array $serviceMacros,
private readonly array $pollerMacros,
private readonly Configuration $openIdProviderConfiguration,
private readonly array $brokerInputOutputs,
private array $accs,
) {
}
public function getIterator(): \Traversable
{
$existingUuids = [
'hosts' => [],
'services' => [],
'pollerMacro' => null,
'openId' => null,
'brokerConfigs' => [],
'accs' => [],
];
/**
* @var CredentialDto $credential
*/
foreach ($this->credentials as $credential) {
try {
$recordInformation = match ($credential->type) {
CredentialTypeEnum::TYPE_HOST, CredentialTypeEnum::TYPE_HOST_TEMPLATE => $this
->migrateHostAndHostTemplateCredentials(
$credential,
$existingUuids
),
CredentialTypeEnum::TYPE_SERVICE => $this->migrateServiceAndServiceTemplateCredentials(
$credential,
$existingUuids
),
CredentialTypeEnum::TYPE_POLLER_MACRO => $this->migratePollerMacroPasswords(
$credential,
$existingUuids
),
CredentialTypeEnum::TYPE_KNOWLEDGE_BASE_PASSWORD => $this->migrateKnowledgeBasePassword(
$credential
),
CredentialTypeEnum::TYPE_OPEN_ID => $this->migrateOpenIdCredentials(
$credential,
$existingUuids
),
CredentialTypeEnum::TYPE_BROKER_INPUT_OUTPUT => $this->migrateBrokerInputOutputPasswords(
$credential,
$existingUuids
),
CredentialTypeEnum::TYPE_ADDITIONAL_CONNECTOR_CONFIGURATION => $this->migrateAccPasswords(
$credential,
$existingUuids
),
};
$status = new CredentialRecordedDto();
$status->uuid = $recordInformation['uuid'];
$status->resourceId = $credential->resourceId;
$status->vaultPath = $recordInformation['path'];
$status->type = $credential->type;
$status->credentialName = $credential->name;
yield $status;
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => (string) $ex]);
$status = new CredentialErrorDto();
$status->resourceId = $credential->resourceId;
$status->type = $credential->type;
$status->credentialName = $credential->name;
$status->message = $ex->getMessage();
yield $status;
}
}
}
/**
* @return int
*/
public function count(): int
{
return count($this->credentials);
}
/**
* @param CredentialDto $credential
* @param _ExistingUuids $existingUuids
*
* @return array{uuid: string, path: string}
*/
private function migrateHostAndHostTemplateCredentials(
CredentialDto $credential,
array &$existingUuids,
): array {
if ($credential->resourceId === null) {
throw new \Exception('Resource ID should not be null');
}
$uuid = null;
if (array_key_exists($credential->resourceId, $existingUuids['hosts'])) {
$uuid = $existingUuids['hosts'][$credential->resourceId];
}
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::HOST_VAULT_PATH);
$vaultKey = $credential->name === VaultConfiguration::HOST_SNMP_COMMUNITY_KEY
? $credential->name
: '_HOST' . $credential->name;
$vaultPaths = $this->writeVaultRepository->upsert(
$uuid,
[
$vaultKey => $credential->value,
]
);
$vaultPath = $vaultPaths[$vaultKey];
$uuid = $this->getUuidFromPath($vaultPath);
if ($uuid === null) {
throw new \Exception('UUID not found in the vault path');
}
$existingUuids['hosts'][$credential->resourceId] = $uuid;
if ($credential->name === VaultConfiguration::HOST_SNMP_COMMUNITY_KEY) {
if ($credential->type === CredentialTypeEnum::TYPE_HOST) {
foreach ($this->hosts as $host) {
if ($host->getId() === $credential->resourceId) {
$host->setSnmpCommunity($vaultPath);
$this->writeHostRepository->update($host);
}
}
} else {
foreach ($this->hostTemplates as $hostTemplate) {
if ($hostTemplate->getId() === $credential->resourceId) {
$hostTemplate->setSnmpCommunity($vaultPath);
$this->writeHostTemplateRepository->update($hostTemplate);
}
}
}
} else {
foreach ($this->hostMacros as $hostMacro) {
if ($hostMacro->getOwnerId() === $credential->resourceId) {
$hostMacro->setValue($vaultPath);
$this->writeHostMacroRepository->update($hostMacro);
}
}
}
return [
'uuid' => $existingUuids['hosts'][$credential->resourceId],
'path' => $vaultPath,
];
}
/**
* @param CredentialDto $credential
* @param _ExistingUuids $existingUuids
*
* @throws \Throwable
*
* @return array{uuid: string, path: string}
*/
private function migrateServiceAndServiceTemplateCredentials(
CredentialDto $credential,
array &$existingUuids,
): array {
if ($credential->resourceId === null) {
throw new \Exception('Resource ID should not be null');
}
$uuid = null;
if (array_key_exists($credential->resourceId, $existingUuids['services'])) {
$uuid = $existingUuids['services'][$credential->resourceId];
}
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::SERVICE_VAULT_PATH);
$vaultKey = '_SERVICE' . $credential->name;
$vaultPaths = $this->writeVaultRepository->upsert(
$uuid,
[$vaultKey => $credential->value]
);
$vaultPath = $vaultPaths[$vaultKey];
$uuid = $this->getUuidFromPath($vaultPath);
if ($uuid === null) {
throw new \Exception('UUID not found in the vault path');
}
$existingUuids['services'][$credential->resourceId] = $uuid;
foreach ($this->serviceMacros as $serviceMacro) {
if ($serviceMacro->getOwnerId() === $credential->resourceId) {
$serviceMacro->setValue($vaultPath);
$this->writeServiceMacroRepository->update($serviceMacro);
}
}
return [
'uuid' => $existingUuids['services'][$credential->resourceId],
'path' => $vaultPath,
];
}
/**
* @param CredentialDto $credential
* @param _ExistingUuids $existingUuids
*
* @throws \Throwable
*
* @return array{uuid: string, path: string}
*/
private function migratePollerMacroPasswords(CredentialDto $credential, array &$existingUuids): array
{
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::POLLER_MACRO_VAULT_PATH);
$vaultPaths = $this->writeVaultRepository->upsert(
$existingUuids['pollerMacro'] ?? null,
[$credential->name => $credential->value]
);
$vaultPath = $vaultPaths[$credential->name];
$uuid = $this->getUuidFromPath($vaultPath);
if ($uuid === null) {
throw new \Exception('UUID not found in the vault path');
}
$existingUuids['pollerMacro'] ??= $uuid;
foreach ($this->pollerMacros as $pollerMacro) {
if ($pollerMacro->getId() === $credential->resourceId) {
$pollerMacro->setValue($vaultPath);
$this->writePollerMacroRepository->update($pollerMacro);
}
}
return [
'uuid' => $existingUuids['pollerMacro'],
'path' => $vaultPath,
];
}
/**
* @param CredentialDto $credential
*
* @throws \Throwable
*
* @return array{uuid: string, path: string}
*/
private function migrateKnowledgeBasePassword(CredentialDto $credential): array
{
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::KNOWLEDGE_BASE_PATH);
$vaultPaths = $this->writeVaultRepository->upsert(
null,
[$credential->name => $credential->value]
);
$vaultPath = $vaultPaths[$credential->name];
$uuid = $this->getUuidFromPath($vaultPath);
if ($uuid === null) {
throw new \Exception('UUID not found in the vault path');
}
$option = new Option('kb_wiki_password', $vaultPath);
$this->writeOptionRepository->update($option);
return [
'uuid' => $uuid,
'path' => $vaultPath,
];
}
/**
* @param CredentialDto $credential
* @param _ExistingUuids $existingUuids
*
* @throws \Throwable
*
* @return array{uuid: string, path: string}
*/
private function migrateOpenIdCredentials(CredentialDto $credential, array &$existingUuids): array
{
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::OPEN_ID_CREDENTIALS_VAULT_PATH);
$vaultPaths = $this->writeVaultRepository->upsert(
$existingUuids['openId'] ?? null,
[$credential->name => $credential->value]
);
$vaultPath = $vaultPaths[$credential->name];
$uuid = $this->getUuidFromPath($vaultPath);
if ($uuid === null) {
throw new \Exception('UUID not found in the vault path');
}
$existingUuids['openId'] ??= $uuid;
/**
* @var CustomConfiguration $customConfiguration
*/
$customConfiguration = $this->openIdProviderConfiguration->getCustomConfiguration();
if ($credential->value === $customConfiguration->getClientId()) {
$customConfiguration->setClientId($vaultPath);
}
if ($credential->value === $customConfiguration->getClientSecret()) {
$customConfiguration->setClientSecret($vaultPath);
}
$this->openIdProviderConfiguration->setCustomConfiguration($customConfiguration);
$this->writeOpenIdConfigurationRepository->updateConfiguration($this->openIdProviderConfiguration);
return [
'uuid' => $existingUuids['openId'],
'path' => $vaultPath,
];
}
/**
* @param CredentialDto $credential
* @param _ExistingUuids $existingUuids
*
* @throws \Throwable
*
* @return array{uuid: string, path: string}
*/
private function migrateBrokerInputOutputPasswords(
CredentialDto $credential,
array &$existingUuids,
): array {
if ($credential->resourceId === null) {
throw new \Exception('Resource ID should not be null');
}
$uuid = null;
if (array_key_exists($credential->resourceId, $existingUuids['brokerConfigs'])) {
$uuid = $existingUuids['brokerConfigs'][$credential->resourceId];
}
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::BROKER_VAULT_PATH);
$vaultPaths = $this->writeVaultRepository->upsert(
$uuid,
[
$credential->name => $credential->value,
]
);
$vaultPath = $vaultPaths[$credential->name];
$uuid = $this->getUuidFromPath($vaultPath);
if ($uuid === null) {
throw new \Exception('UUID not found in the vault path');
}
$existingUuids['brokerConfigs'][$credential->resourceId] = $uuid;
$inputOutputs = $this->brokerInputOutputs[$credential->resourceId];
foreach ($inputOutputs as $inputOutput) {
if (str_starts_with($credential->name, $inputOutput->getName())) {
$credentialNamePart = str_replace($inputOutput->getName() . '_', '', $credential->name);
$params = $inputOutput->getParameters();
foreach ($params as $paramName => $param) {
if (is_array($param)) {
foreach ($param as $index => $groupedParams) {
if (
is_array($groupedParams)
&& isset($groupedParams['type'])
&& ($paramName . '_' . $groupedParams['name']) === $credentialNamePart
) {
if (! isset($params[$paramName][$index]) || ! is_array($params[$paramName][$index])) {
// for phpstan, should never happen.
throw new \Exception('Unexpected error');
}
$params[$paramName][$index]['value'] = $vaultPath;
}
}
} elseif ($paramName === $credentialNamePart) {
$params[$paramName] = $vaultPath;
}
}
$inputOutput->setParameters($params);
$this->writeBrokerInputOutputRepository->update(
$inputOutput,
$credential->resourceId,
$this->readBrokerInputOutputRepository->findParametersByType($inputOutput->getType()->id),
);
}
}
return [
'uuid' => $existingUuids['brokerConfigs'][$credential->resourceId],
'path' => $vaultPath,
];
}
/**
* @param CredentialDto $credential
* @param _ExistingUuids $existingUuids
*
* @throws \Throwable
*
* @return array{uuid: string, path: string}
*/
private function migrateAccPasswords(CredentialDto $credential, array &$existingUuids): array
{
$this->writeVaultRepository->setCustomPath(AbstractVaultRepository::ACC_VAULT_PATH);
$vaultPaths = $this->writeVaultRepository->upsert(
$existingUuids['accs'][$credential->resourceId] ?? null,
[$credential->name => $credential->value]
);
$vaultPath = $vaultPaths[$credential->name];
$uuid = $this->getUuidFromPath($vaultPath);
if ($uuid === null) {
throw new \Exception('UUID not found in the vault path');
}
$existingUuids['accs'][$credential->resourceId] ??= $uuid;
foreach ($this->accs as $index => $acc) {
if ($acc->getId() === $credential->resourceId) {
$updatedAcc = $acc;
foreach ($this->accCredentialMigrators as $migrator) {
$updatedAcc = $migrator->updateMigratedCredential($acc, $credential, $vaultPath);
}
$this->accs[$index] = $updatedAcc;
$this->writeAccRepository->update($updatedAcc);
}
}
return [
'uuid' => $existingUuids['accs'][$credential->resourceId],
'path' => $vaultPath,
];
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialRecordedDto.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialRecordedDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials;
class CredentialRecordedDto
{
public string $uuid = '';
public ?int $resourceId = null;
public string $vaultPath = '';
public CredentialTypeEnum $type = CredentialTypeEnum::TYPE_HOST;
public string $credentialName = '';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialTypeEnum.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialTypeEnum.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials;
enum CredentialTypeEnum
{
case TYPE_HOST;
case TYPE_HOST_TEMPLATE;
case TYPE_SERVICE;
case TYPE_KNOWLEDGE_BASE_PASSWORD;
case TYPE_POLLER_MACRO;
case TYPE_OPEN_ID;
case TYPE_BROKER_INPUT_OUTPUT;
case TYPE_ADDITIONAL_CONNECTOR_CONFIGURATION;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialErrorDto.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/CredentialErrorDto.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials;
class CredentialErrorDto
{
public ?int $resourceId = null;
public CredentialTypeEnum $type = CredentialTypeEnum::TYPE_HOST;
public string $message = '';
public string $credentialName = '';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentials.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentials.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials;
use Centreon\Domain\Log\LoggerTrait;
use Core\AdditionalConnectorConfiguration\Application\Repository\ReadAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Application\Repository\WriteAccRepositoryInterface;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\Application\Common\UseCase\ErrorResponse;
use Core\Broker\Application\Repository\ReadBrokerInputOutputRepositoryInterface;
use Core\Broker\Application\Repository\WriteBrokerInputOutputRepositoryInterface;
use Core\Broker\Domain\Model\BrokerInputOutput;
use Core\Common\Application\Repository\WriteVaultRepositoryInterface;
use Core\Common\Infrastructure\ExceptionLogger\ExceptionLogger;
use Core\Common\Infrastructure\FeatureFlags;
use Core\Host\Application\Repository\ReadHostRepositoryInterface;
use Core\Host\Application\Repository\WriteHostRepositoryInterface;
use Core\Host\Domain\Model\Host;
use Core\HostTemplate\Application\Repository\ReadHostTemplateRepositoryInterface;
use Core\HostTemplate\Application\Repository\WriteHostTemplateRepositoryInterface;
use Core\HostTemplate\Domain\Model\HostTemplate;
use Core\Macro\Application\Repository\ReadHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\ReadServiceMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteHostMacroRepositoryInterface;
use Core\Macro\Application\Repository\WriteServiceMacroRepositoryInterface;
use Core\Macro\Domain\Model\Macro;
use Core\Option\Application\Repository\ReadOptionRepositoryInterface;
use Core\Option\Application\Repository\WriteOptionRepositoryInterface;
use Core\Option\Domain\Option;
use Core\PollerMacro\Application\Repository\ReadPollerMacroRepositoryInterface;
use Core\PollerMacro\Application\Repository\WritePollerMacroRepositoryInterface;
use Core\PollerMacro\Domain\Model\PollerMacro;
use Core\Security\ProviderConfiguration\Application\OpenId\Repository\WriteOpenIdConfigurationRepositoryInterface;
use Core\Security\ProviderConfiguration\Application\Repository\ReadConfigurationRepositoryInterface;
use Core\Security\ProviderConfiguration\Domain\Model\Configuration;
use Core\Security\ProviderConfiguration\Domain\Model\Provider;
use Core\Security\ProviderConfiguration\Domain\OpenId\Model\CustomConfiguration;
use Core\Security\Vault\Application\Exceptions\VaultException;
use Core\Security\Vault\Application\Repository\ReadVaultConfigurationRepositoryInterface;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\Migrator\AccCredentialMigratorInterface;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
final class MigrateAllCredentials
{
use LoggerTrait;
private MigrateAllCredentialsResponse $response;
/** @var AccCredentialMigratorInterface[] */
private array $accCredentialMigrators = [];
/**
* @param WriteVaultRepositoryInterface $writeVaultRepository
* @param ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository
* @param ReadHostRepositoryInterface $readHostRepository
* @param ReadHostMacroRepositoryInterface $readHostMacroRepository
* @param ReadHostTemplateRepositoryInterface $readHostTemplateRepository
* @param ReadServiceMacroRepositoryInterface $readServiceMacroRepository
* @param ReadOptionRepositoryInterface $readOptionRepository
* @param ReadPollerMacroRepositoryInterface $readPollerMacroRepository
* @param ReadConfigurationRepositoryInterface $readProviderConfigurationRepository
* @param WriteHostRepositoryInterface $writeHostRepository
* @param WriteHostMacroRepositoryInterface $writeHostMacroRepository
* @param WriteHostTemplateRepositoryInterface $writeHostTemplateRepository
* @param WriteServiceMacroRepositoryInterface $writeServiceMacroRepository
* @param WriteOptionRepositoryInterface $writeOptionRepository
* @param WritePollerMacroRepositoryInterface $writePollerMacroRepository
* @param WriteOpenIdConfigurationRepositoryInterface $writeOpenIdConfigurationRepository
* @param ReadBrokerInputOutputRepositoryInterface $readBrokerInputOutputRepository
* @param WriteBrokerInputOutputRepositoryInterface $writeBrokerInputOutputRepository
* @param ReadAccRepositoryInterface $readAccRepository
* @param WriteAccRepositoryInterface $writeAccRepository
* @param FeatureFlags $flags
* @param \Traversable<AccCredentialMigratorInterface> $accCredentialMigrators
*/
public function __construct(
private readonly WriteVaultRepositoryInterface $writeVaultRepository,
private readonly ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository,
private readonly ReadHostRepositoryInterface $readHostRepository,
private readonly ReadHostMacroRepositoryInterface $readHostMacroRepository,
private readonly ReadHostTemplateRepositoryInterface $readHostTemplateRepository,
private readonly ReadServiceMacroRepositoryInterface $readServiceMacroRepository,
private readonly ReadOptionRepositoryInterface $readOptionRepository,
private readonly ReadPollerMacroRepositoryInterface $readPollerMacroRepository,
private readonly ReadConfigurationRepositoryInterface $readProviderConfigurationRepository,
private readonly WriteHostRepositoryInterface $writeHostRepository,
private readonly WriteHostMacroRepositoryInterface $writeHostMacroRepository,
private readonly WriteHostTemplateRepositoryInterface $writeHostTemplateRepository,
private readonly WriteServiceMacroRepositoryInterface $writeServiceMacroRepository,
private readonly WriteOptionRepositoryInterface $writeOptionRepository,
private readonly WritePollerMacroRepositoryInterface $writePollerMacroRepository,
private readonly WriteOpenIdConfigurationRepositoryInterface $writeOpenIdConfigurationRepository,
private readonly ReadBrokerInputOutputRepositoryInterface $readBrokerInputOutputRepository,
private readonly WriteBrokerInputOutputRepositoryInterface $writeBrokerInputOutputRepository,
private readonly ReadAccRepositoryInterface $readAccRepository,
private readonly WriteAccRepositoryInterface $writeAccRepository,
private readonly FeatureFlags $flags,
\Traversable $accCredentialMigrators,
) {
$this->response = new MigrateAllCredentialsResponse();
$this->accCredentialMigrators = iterator_to_array($accCredentialMigrators);
}
public function __invoke(MigrateAllCredentialsPresenterInterface $presenter): void
{
try {
if ($this->readVaultConfigurationRepository->find() === null) {
$presenter->presentResponse(new ErrorResponse(VaultException::noVaultConfigured()));
return;
}
$hosts = $this->readHostRepository->findAll();
$hostTemplates = $this->readHostTemplateRepository->findAll();
$hostMacros = $this->readHostMacroRepository->findPasswords();
$serviceMacros = $this->readServiceMacroRepository->findPasswords();
$knowledgeBasePasswordOption = $this->readOptionRepository->findByName('kb_wiki_password');
$pollerMacros = $this->readPollerMacroRepository->findPasswords();
$openIdConfiguration = $this->readProviderConfigurationRepository->getConfigurationByType(
Provider::OPENID
);
$brokerInputOutputs = $this->flags->isEnabled('vault_broker')
? $this->readBrokerInputOutputRepository->findAll()
: [];
$accs = $this->flags->isEnabled('vault_gorgone')
? $this->readAccRepository->findAll()
: [];
$credentials = $this->createCredentialDtos(
$hosts,
$hostTemplates,
$hostMacros,
$serviceMacros,
$pollerMacros,
$knowledgeBasePasswordOption,
$openIdConfiguration,
$brokerInputOutputs,
$accs,
);
$this->migrateCredentials(
$credentials,
$this->response,
$hosts,
$hostTemplates,
$hostMacros,
$serviceMacros,
$pollerMacros,
$openIdConfiguration,
$brokerInputOutputs,
$accs,
);
$presenter->presentResponse($this->response);
} catch (\Throwable $e) {
ExceptionLogger::create()->log($e);
$presenter->presentResponse(new ErrorResponse(VaultException::unableToMigrateCredentials()));
}
}
/**
* @param \Countable&\Traversable<CredentialDto> $credentials
* @param MigrateAllCredentialsResponse $response
* @param Host[] $hosts
* @param HostTemplate[] $hostTemplates
* @param Macro[] $hostMacros
* @param Macro[] $serviceMacros
* @param PollerMacro[] $pollerMacros
* @param Configuration $openIdConfiguration
* @param array<int,BrokerInputOutput[]> $brokerInputOutputs
* @param Acc[] $accs
*/
private function migrateCredentials(
\Traversable&\Countable $credentials,
MigrateAllCredentialsResponse $response,
array $hosts,
array $hostTemplates,
array $hostMacros,
array $serviceMacros,
array $pollerMacros,
Configuration $openIdConfiguration,
array $brokerInputOutputs,
array $accs,
): void {
$response->results = new CredentialMigrator(
$credentials,
$this->writeVaultRepository,
$this->writeHostRepository,
$this->writeHostTemplateRepository,
$this->writeHostMacroRepository,
$this->writeServiceMacroRepository,
$this->writeOptionRepository,
$this->writePollerMacroRepository,
$this->writeOpenIdConfigurationRepository,
$this->readBrokerInputOutputRepository,
$this->writeBrokerInputOutputRepository,
$this->writeAccRepository,
$this->accCredentialMigrators,
$hosts,
$hostTemplates,
$hostMacros,
$serviceMacros,
$pollerMacros,
$openIdConfiguration,
$brokerInputOutputs,
$accs,
);
}
/**
* @param Host[] $hosts
* @param HostTemplate[] $hostTemplates
* @param Macro[] $hostMacros
* @param Macro[] $serviceMacros
* @param PollerMacro[] $pollerMacros
* @param Option|null $knowledgeBasePasswordOption
* @param Configuration $openIdConfiguration
* @param array<int,BrokerInputOutput[]> $brokerInputOutputs
* @param Acc[] $accs
*
* @return \ArrayIterator<int, CredentialDto> $credentials
*/
private function createCredentialDtos(
array $hosts,
array $hostTemplates,
array $hostMacros,
array $serviceMacros,
array $pollerMacros,
?Option $knowledgeBasePasswordOption,
Configuration $openIdConfiguration,
array $brokerInputOutputs,
array $accs,
): \ArrayIterator {
$hostSNMPCommunityCredentialDtos = $this->createHostSNMPCommunityCredentialDtos($hosts);
$hostTemplateSNMPCommunityCredentialDtos = $this->createHostTemplateSNMPCommunityCredentialDtos($hostTemplates);
$hostMacroCredentialDtos = $this->createHostMacroCredentialDtos($hostMacros);
$serviceMacroCredentialDtos = $this->createServiceMacroCredentialDtos($serviceMacros);
$pollerMacroCredentialDtos = $this->createPollerMacroCredentialDtos($pollerMacros);
$knowledgeBasePasswordCredentialDto = $this->createKnowledgeBasePasswordCredentialDto(
$knowledgeBasePasswordOption
);
$openIdConfigurationCredentialDtos = $this->createOpenIdConfigurationCredentialDtos($openIdConfiguration);
$brokerConfigurationCredentialDtos = $this->createBrokerInputOutputCredentialDtos($brokerInputOutputs);
$accCredentialDtos = $this->createAccCredentialDtos($accs);
return new \ArrayIterator(array_merge(
$hostSNMPCommunityCredentialDtos,
$hostTemplateSNMPCommunityCredentialDtos,
$hostMacroCredentialDtos,
$serviceMacroCredentialDtos,
$pollerMacroCredentialDtos,
$knowledgeBasePasswordCredentialDto,
$openIdConfigurationCredentialDtos,
$brokerConfigurationCredentialDtos,
$accCredentialDtos,
));
}
/**
* @param Host[] $hosts
*
* @return CredentialDto[]
*/
private function createHostSNMPCommunityCredentialDtos(array $hosts): array
{
$credentials = [];
foreach ($hosts as $host) {
if ($host->getSnmpCommunity() === '' || str_starts_with($host->getSnmpCommunity(), VaultConfiguration::VAULT_PATH_PATTERN)) {
continue;
}
$credential = new CredentialDto();
$credential->resourceId = $host->getId();
$credential->type = CredentialTypeEnum::TYPE_HOST;
$credential->name = VaultConfiguration::HOST_SNMP_COMMUNITY_KEY;
$credential->value = $host->getSnmpCommunity();
$credentials[] = $credential;
}
return $credentials;
}
/**
* @param HostTemplate[] $hostTemplates
*
* @return CredentialDto[]
*/
private function createHostTemplateSNMPCommunityCredentialDtos(array $hostTemplates): array
{
$credentials = [];
foreach ($hostTemplates as $hostTemplate) {
if (
$hostTemplate->getSnmpCommunity() === ''
|| str_starts_with($hostTemplate->getSnmpCommunity(), VaultConfiguration::VAULT_PATH_PATTERN)) {
continue;
}
$credential = new CredentialDto();
$credential->resourceId = $hostTemplate->getId();
$credential->type = CredentialTypeEnum::TYPE_HOST_TEMPLATE;
$credential->name = VaultConfiguration::HOST_SNMP_COMMUNITY_KEY;
$credential->value = $hostTemplate->getSnmpCommunity();
$credentials[] = $credential;
}
return $credentials;
}
/**
* @param Macro[] $hostMacros
*
* @return CredentialDto[]
*/
private function createHostMacroCredentialDtos(array $hostMacros): array
{
$credentials = [];
foreach ($hostMacros as $hostMacro) {
if (
$hostMacro->getValue() === ''
|| str_starts_with($hostMacro->getValue(), VaultConfiguration::VAULT_PATH_PATTERN)
) {
continue;
}
$credential = new CredentialDto();
$credential->resourceId = $hostMacro->getOwnerId();
$credential->type = CredentialTypeEnum::TYPE_HOST;
$credential->name = $hostMacro->getName();
$credential->value = $hostMacro->getValue();
$credentials[] = $credential;
}
return $credentials;
}
/**
* @param Macro[] $serviceMacros
*
* @return CredentialDto[]
*/
private function createServiceMacroCredentialDtos(array $serviceMacros): array
{
$credentials = [];
foreach ($serviceMacros as $serviceMacro) {
if (
$serviceMacro->getValue() === ''
|| str_starts_with($serviceMacro->getValue(), VaultConfiguration::VAULT_PATH_PATTERN)
) {
continue;
}
$credential = new CredentialDto();
$credential->resourceId = $serviceMacro->getOwnerId();
$credential->type = CredentialTypeEnum::TYPE_SERVICE;
$credential->name = $serviceMacro->getName();
$credential->value = $serviceMacro->getValue();
$credentials[] = $credential;
}
return $credentials;
}
/**
* @param PollerMacro[] $pollerMacros
*
* @return CredentialDto[]
*/
private function createPollerMacroCredentialDtos(array $pollerMacros): array
{
$credentials = [];
foreach ($pollerMacros as $pollerMacro) {
if (
$pollerMacro->getValue() === ''
|| str_starts_with($pollerMacro->getValue(), VaultConfiguration::VAULT_PATH_PATTERN)
) {
continue;
}
$credential = new CredentialDto();
$credential->resourceId = $pollerMacro->getId();
$credential->type = CredentialTypeEnum::TYPE_POLLER_MACRO;
$credential->name = $pollerMacro->getName();
$credential->value = $pollerMacro->getValue();
$credentials[] = $credential;
}
return $credentials;
}
/**
* @param Option|null $knowledgeBasePasswordOption
*
* @return CredentialDto[]
*/
private function createKnowledgeBasePasswordCredentialDto(?Option $knowledgeBasePasswordOption): array
{
$credentials = [];
if (
$knowledgeBasePasswordOption === null
|| $knowledgeBasePasswordOption->getValue() === null
|| str_starts_with($knowledgeBasePasswordOption->getValue(), VaultConfiguration::VAULT_PATH_PATTERN)
) {
return $credentials;
}
$credential = new CredentialDto();
$credential->type = CredentialTypeEnum::TYPE_KNOWLEDGE_BASE_PASSWORD;
$credential->name = VaultConfiguration::KNOWLEDGE_BASE_KEY;
$credential->value = $knowledgeBasePasswordOption->getValue();
$credentials[] = $credential;
return $credentials;
}
/**
* @param Configuration $openIdConfiguration
*
* @return CredentialDto[]
*/
private function createOpenIdConfigurationCredentialDtos(Configuration $openIdConfiguration): array
{
$credentials = [];
/**
* @var CustomConfiguration $customConfiguration
*/
$customConfiguration = $openIdConfiguration->getCustomConfiguration();
if (
$customConfiguration->getClientId() !== null
&& ! str_starts_with($customConfiguration->getClientId(), VaultConfiguration::VAULT_PATH_PATTERN)
) {
$credential = new CredentialDto();
$credential->type = CredentialTypeEnum::TYPE_OPEN_ID;
$credential->name = VaultConfiguration::OPENID_CLIENT_ID_KEY;
$credential->value = $customConfiguration->getClientId();
$credentials[] = $credential;
}
if (
$customConfiguration->getClientSecret() !== null
&& ! str_starts_with($customConfiguration->getClientSecret(), VaultConfiguration::VAULT_PATH_PATTERN)
) {
$credential = new CredentialDto();
$credential->type = CredentialTypeEnum::TYPE_OPEN_ID;
$credential->name = VaultConfiguration::OPENID_CLIENT_SECRET_KEY;
$credential->value = $customConfiguration->getClientSecret();
$credentials[] = $credential;
}
return $credentials;
}
/**
* @param array<int,BrokerInputOutput[]> $inputOutputs
*
* @return CredentialDto[]
*/
private function createBrokerInputOutputCredentialDtos(array $inputOutputs): array
{
$credentials = [];
$fieldsCache = [];
foreach ($inputOutputs as $brokerId => $inputOutputConfigs) {
foreach ($inputOutputConfigs as $config) {
if (! isset($fieldsCache[$config->getType()->id])) {
$fieldsCache[$config->getType()->id]
= $this->readBrokerInputOutputRepository->findParametersByType($config->getType()->id);
}
$fields = $fieldsCache[$config->getType()->id];
$params = $config->getParameters();
foreach ($fields as $fieldName => $field) {
if (! isset($params[$fieldName])) {
continue;
}
if (is_array($field)) {
if (! is_array($params[$fieldName])) {
// for phpstan, should never happen.
throw new \Exception('unexpected error');
}
foreach ($params[$fieldName] as $groupedParams) {
if (
isset($groupedParams['type'])
&& $groupedParams['type'] === 'password'
&& isset($groupedParams['value'])
&& $groupedParams['value'] !== ''
&& ! str_starts_with((string) $groupedParams['value'], 'secret::')
) {
/** @var array{type:string,name:string,value:string|int} $groupedParams */
$credential = new CredentialDto();
$credential->resourceId = $brokerId;
$credential->type = CredentialTypeEnum::TYPE_BROKER_INPUT_OUTPUT;
$credential->name = $config->getName() . '_' . $fieldName . '_' . $groupedParams['name'];
$credential->value = (string) $groupedParams['value'];
$credentials[] = $credential;
}
}
} elseif ($field->getType() === 'password') {
/** @var string $value */
$value = $params[$fieldName];
if ($value === '' || str_starts_with($value, 'secret::')) {
continue;
}
$credential = new CredentialDto();
$credential->resourceId = $brokerId;
$credential->type = CredentialTypeEnum::TYPE_BROKER_INPUT_OUTPUT;
$credential->name = $config->getName() . '_' . $fieldName;
$credential->value = $value;
$credentials[] = $credential;
}
}
}
}
return $credentials;
}
/**
* @param Acc[] $accs
*
* @return CredentialDto[]
*/
private function createAccCredentialDtos(array $accs): array
{
$credentials = [];
foreach ($accs as $acc) {
$credentialDtos = [];
foreach ($this->accCredentialMigrators as $factory) {
if ($factory->isValidFor($acc->getType())) {
$credentialDtos = $factory->createCredentialDtos($acc);
}
}
$credentials = [...$credentials, ...$credentialDtos];
}
return $credentials;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentialsPresenterInterface.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentialsPresenterInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials;
use Core\Application\Common\UseCase\ResponseStatusInterface;
interface MigrateAllCredentialsPresenterInterface
{
public function presentResponse(MigrateAllCredentialsResponse|ResponseStatusInterface $response): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentialsResponse.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/MigrateAllCredentialsResponse.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials;
final class MigrateAllCredentialsResponse
{
/** @var \Traversable<CredentialRecordedDto|CredentialErrorDto> */
public \Traversable $results;
public function __construct()
{
$this->results = new \ArrayIterator([]);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/Migrator/VmWareV6CredentialMigrator.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/Migrator/VmWareV6CredentialMigrator.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials\Migrator;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\AdditionalConnectorConfiguration\Domain\Model\VmWareV6\VmWareV6Parameters;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialDto;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialTypeEnum;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Security\Interfaces\EncryptionInterface;
/**
* @phpstan-import-type _VmWareV6Parameters from VmWareV6Parameters
*/
class VmWareV6CredentialMigrator implements AccCredentialMigratorInterface
{
public function __construct(private readonly EncryptionInterface $encryption)
{
}
/**
* @inheritDoc
*/
public function isValidFor(Type $type): bool
{
return $type === Type::VMWARE_V6;
}
/**
* @inheritDoc
*/
public function createCredentialDtos(Acc $acc): array
{
/** @var _VmWareV6Parameters $parameters */
$parameters = $acc->getParameters()->getDecryptedData();
$credentials = [];
foreach ($parameters['vcenters'] as $vcenter) {
if (! str_starts_with($vcenter['username'], VaultConfiguration::VAULT_PATH_PATTERN)) {
$credential = new CredentialDto();
$credential->resourceId = $acc->getId();
$credential->type = CredentialTypeEnum::TYPE_ADDITIONAL_CONNECTOR_CONFIGURATION;
$credential->name = $vcenter['name'] . '_username';
$credential->value = $vcenter['username'];
$credentials[] = $credential;
}
if (! str_starts_with($vcenter['password'], VaultConfiguration::VAULT_PATH_PATTERN)) {
$credential = new CredentialDto();
$credential->resourceId = $acc->getId();
$credential->type = CredentialTypeEnum::TYPE_ADDITIONAL_CONNECTOR_CONFIGURATION;
$credential->name = $vcenter['name'] . '_password';
$credential->value = $vcenter['password'];
$credentials[] = $credential;
}
}
return $credentials;
}
/**
* @inheritDoc
*/
public function updateMigratedCredential(
Acc $acc,
CredentialDto $credential,
string $vaultPath,
): Acc {
/** @var _VmWareV6Parameters $parameters */
$parameters = $acc->getParameters()->getData();
foreach ($parameters['vcenters'] as $index => $vcenter) {
if ($credential->name === $vcenter['name'] . '_username') {
$parameters['vcenters'][$index]['username'] = $vaultPath;
} elseif ($credential->name === $vcenter['name'] . '_password') {
$parameters['vcenters'][$index]['password'] = $vaultPath;
}
}
return new Acc(
id: $acc->getId(),
name: $acc->getName(),
type: $acc->getType(),
createdBy: $acc->getCreatedBy(),
updatedBy: null,
createdAt: $acc->getCreatedAt(),
updatedAt: new \DateTimeImmutable(),
description: $acc->getDescription(),
parameters: new VmWareV6Parameters($this->encryption, $parameters)
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/Migrator/AccCredentialMigratorInterface.php | centreon/src/Core/Security/Vault/Application/UseCase/MigrateAllCredentials/Migrator/AccCredentialMigratorInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\MigrateAllCredentials\Migrator;
use Core\AdditionalConnectorConfiguration\Domain\Model\Acc;
use Core\AdditionalConnectorConfiguration\Domain\Model\Type;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialDto;
interface AccCredentialMigratorInterface
{
/**
* @param Type $type
*
* @return bool
*/
public function isValidFor(Type $type): bool;
/**
* @param Acc $acc
*
* @return CredentialDto[]
*/
public function createCredentialDtos(Acc $acc): array;
/**
* @param Acc $acc
* @param CredentialDto $credential
* @param string $vaultPath
*
* @return Acc
*/
public function updateMigratedCredential(
Acc $acc,
CredentialDto $credential,
string $vaultPath,
): Acc;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/DeleteVaultConfiguration/DeleteVaultConfiguration.php | centreon/src/Core/Security/Vault/Application/UseCase/DeleteVaultConfiguration/DeleteVaultConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\DeleteVaultConfiguration;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{
ErrorResponse,
ForbiddenResponse,
NoContentResponse,
NotFoundResponse,
PresenterInterface
};
use Core\Security\Vault\Application\Exceptions\VaultConfigurationException;
use Core\Security\Vault\Application\Repository\{
ReadVaultConfigurationRepositoryInterface,
WriteVaultConfigurationRepositoryInterface
};
final class DeleteVaultConfiguration
{
use LoggerTrait;
/**
* @param ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository
* @param WriteVaultConfigurationRepositoryInterface $writeVaultConfigurationRepository
* @param ContactInterface $user
*/
public function __construct(
readonly private ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository,
readonly private WriteVaultConfigurationRepositoryInterface $writeVaultConfigurationRepository,
readonly private ContactInterface $user,
) {
}
/**
* @param PresenterInterface $presenter
*/
public function __invoke(PresenterInterface $presenter): void
{
try {
if (! $this->user->isAdmin()) {
$this->error('User is not admin', ['user' => $this->user->getName()]);
$presenter->setResponseStatus(
new ForbiddenResponse(VaultConfigurationException::onlyForAdmin()->getMessage())
);
return;
}
if (! $this->readVaultConfigurationRepository->exists()) {
$this->error('Vault configuration not found');
$presenter->setResponseStatus(
new NotFoundResponse('Vault configuration')
);
return;
}
$this->writeVaultConfigurationRepository->delete();
$presenter->setResponseStatus(new NoContentResponse());
} catch (\Throwable $ex) {
$this->error(
'An error occurred in while deleting vault configuration',
['trace' => $ex->getTraceAsString()]
);
$presenter->setResponseStatus(
new ErrorResponse(VaultConfigurationException::impossibleToDelete()->getMessage())
);
return;
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/NewVaultConfigurationFactory.php | centreon/src/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/NewVaultConfigurationFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\UpdateVaultConfiguration;
use Assert\AssertionFailedException;
use Assert\InvalidArgumentException;
use Core\Security\Vault\Application\Exceptions\VaultException;
use Core\Security\Vault\Domain\Model\NewVaultConfiguration;
use Security\Interfaces\EncryptionInterface;
class NewVaultConfigurationFactory
{
/**
* @param EncryptionInterface $encryption
*/
public function __construct(private readonly EncryptionInterface $encryption)
{
}
/**
* This method will crypt $roleId and $secretId before instanciating NewVaultConfiguraiton.
*
* @param UpdateVaultConfigurationRequest $request
*
* @throws InvalidArgumentException
* @throws AssertionFailedException
* @throws VaultException
* @throws \Exception
* @throws \Throwable
*
* @return NewVaultConfiguration
*/
public function create(UpdateVaultConfigurationRequest $request): NewVaultConfiguration
{
return new NewVaultConfiguration(
$this->encryption,
$request->address,
$request->port,
$request->rootPath,
$request->roleId,
$request->secretId
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/UpdateVaultConfigurationRequest.php | centreon/src/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/UpdateVaultConfigurationRequest.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\UpdateVaultConfiguration;
final class UpdateVaultConfigurationRequest
{
/** @var string */
public string $address = '';
/** @var int */
public int $port = 0;
/** @var string */
public string $rootPath = '';
/** @var string */
public string $roleId = '';
/** @var string */
public string $secretId = '';
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/UpdateVaultConfiguration.php | centreon/src/Core/Security/Vault/Application/UseCase/UpdateVaultConfiguration/UpdateVaultConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\UseCase\UpdateVaultConfiguration;
use Assert\InvalidArgumentException;
use Centreon\Domain\Common\Assertion\AssertionException;
use Centreon\Domain\Contact\Interfaces\ContactInterface;
use Centreon\Domain\Log\LoggerTrait;
use Core\Application\Common\UseCase\{
ErrorResponse,
ForbiddenResponse,
InvalidArgumentResponse,
NoContentResponse,
NotFoundResponse,
PresenterInterface
};
use Core\Common\Application\Repository\ReadVaultRepositoryInterface;
use Core\Security\Vault\Application\Exceptions\VaultConfigurationException;
use Core\Security\Vault\Application\Repository\{
ReadVaultConfigurationRepositoryInterface,
WriteVaultConfigurationRepositoryInterface
};
use Core\Security\Vault\Domain\Model\VaultConfiguration;
final class UpdateVaultConfiguration
{
use LoggerTrait;
/**
* @param ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository
* @param WriteVaultConfigurationRepositoryInterface $writeVaultConfigurationRepository
* @param NewVaultConfigurationFactory $newVaultConfigurationFactory
* @param ReadVaultRepositoryInterface $readVaultRepository
* @param ContactInterface $user
*/
public function __construct(
private readonly ReadVaultConfigurationRepositoryInterface $readVaultConfigurationRepository,
private readonly WriteVaultConfigurationRepositoryInterface $writeVaultConfigurationRepository,
private readonly NewVaultConfigurationFactory $newVaultConfigurationFactory,
private readonly ReadVaultRepositoryInterface $readVaultRepository,
private readonly ContactInterface $user,
) {
}
/**
* @param PresenterInterface $presenter
* @param UpdateVaultConfigurationRequest $request
*/
public function __invoke(
PresenterInterface $presenter,
UpdateVaultConfigurationRequest $request,
): void {
try {
if (! $this->user->isAdmin()) {
$this->error('User is not admin', ['user' => $this->user->getName()]);
$presenter->setResponseStatus(
new ForbiddenResponse(VaultConfigurationException::onlyForAdmin()->getMessage())
);
return;
}
if ($this->readVaultConfigurationRepository->exists()) {
$vaultConfiguration = $this->readVaultConfigurationRepository->find();
if ($vaultConfiguration === null) {
$this->error('Vault configuration not found');
$presenter->setResponseStatus(new NotFoundResponse('Vault configuration'));
return;
}
$this->updateVaultConfiguration($request, $vaultConfiguration);
if (! $this->readVaultRepository->testVaultConnection($vaultConfiguration)) {
$presenter->setResponseStatus(
new InvalidArgumentResponse(VaultConfigurationException::invalidConfiguration())
);
return;
}
$this->writeVaultConfigurationRepository->update($vaultConfiguration);
} else {
$newVaultConfiguration = $this->newVaultConfigurationFactory->create($request);
if (! $this->readVaultRepository->testVaultConnection($newVaultConfiguration)) {
$presenter->setResponseStatus(
new InvalidArgumentResponse(VaultConfigurationException::invalidConfiguration())
);
return;
}
$this->writeVaultConfigurationRepository->create($newVaultConfiguration);
}
$presenter->setResponseStatus(new NoContentResponse());
} catch (InvalidArgumentException|AssertionException $ex) {
$this->error('Some parameters are not valid', ['trace' => $ex->getTraceAsString()]);
$presenter->setResponseStatus(
new InvalidArgumentResponse($ex->getMessage())
);
return;
} catch (\Throwable $ex) {
$this->error(
'An error occurred while updating vault configuration',
['trace' => $ex->getTraceAsString()]
);
$presenter->setResponseStatus(
new ErrorResponse(VaultConfigurationException::impossibleToUpdate()->getMessage())
);
return;
}
}
/**
* @param UpdateVaultConfigurationRequest $request
* @param VaultConfiguration $vaultConfiguration
*
* @throws \Exception
*/
private function updateVaultConfiguration(
UpdateVaultConfigurationRequest $request,
VaultConfiguration $vaultConfiguration,
): void {
$vaultConfiguration->setAddress($request->address);
$vaultConfiguration->setPort($request->port);
$vaultConfiguration->setRootPath($request->rootPath);
$vaultConfiguration->setNewRoleId($request->roleId);
$vaultConfiguration->setNewSecretId($request->secretId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/Exceptions/VaultConfigurationException.php | centreon/src/Core/Security/Vault/Application/Exceptions/VaultConfigurationException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\Exceptions;
class VaultConfigurationException extends \Exception
{
/**
* Exception thrown when vault configuration already exists.
*
* @return self
*/
public static function configurationExists(): self
{
return new self('Vault configuration with these properties already exists');
}
/**
* Exception thrown when unhandled error occurs.
*
* @return self
*/
public static function impossibleToCreate(): self
{
return new self('Impossible to create vault configuration');
}
/**
* @return self
*/
public static function impossibleToDelete(): self
{
return new self('Impossible to delete vault configuration');
}
/**
* @return self
*/
public static function impossibleToFind(): self
{
return new self('Impossible to find vault configuration(s)');
}
/**
* @return self
*/
public static function impossibleToUpdate(): self
{
return new self('Impossible to update vault configuration');
}
/**
* @return self
*/
public static function onlyForAdmin(): self
{
return new self('This operation requires an admin user');
}
/**
* @return self
*/
public static function invalidConfiguration(): self
{
return new self('Vault configuration is invalid');
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/Exceptions/VaultException.php | centreon/src/Core/Security/Vault/Application/Exceptions/VaultException.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\Exceptions;
class VaultException extends \Exception
{
public static function unableToMigrateCredentials(): self
{
return new self(_('Unable to migrate passwords'));
}
public static function noVaultConfigured(): self
{
return new self(_('No vault configured'));
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/Repository/WriteVaultConfigurationRepositoryInterface.php | centreon/src/Core/Security/Vault/Application/Repository/WriteVaultConfigurationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\Repository;
use Core\Security\Vault\Domain\Model\NewVaultConfiguration;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
interface WriteVaultConfigurationRepositoryInterface
{
/**
* @param NewVaultConfiguration $vaultConfiguration
*
* @throws \Throwable
*/
public function create(NewVaultConfiguration $vaultConfiguration): void;
/**
* @param VaultConfiguration $vaultConfiguration
*
* @throws \Throwable
*/
public function update(VaultConfiguration $vaultConfiguration): void;
/**
* @throws \Throwable
*/
public function delete(): void;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Application/Repository/ReadVaultConfigurationRepositoryInterface.php | centreon/src/Core/Security/Vault/Application/Repository/ReadVaultConfigurationRepositoryInterface.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Application\Repository;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
interface ReadVaultConfigurationRepositoryInterface
{
/**
* @throws \Throwable
*
* @return bool
*/
public function exists(): bool;
/**
* @throws \Throwable
*
* @return VaultConfiguration|null
*/
public function find(): ?VaultConfiguration;
/**
* @throws \Throwable
*
* @return string|null
*/
public function getLocation(): ?string;
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Domain/Model/NewVaultConfiguration.php | centreon/src/Core/Security/Vault/Domain/Model/NewVaultConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Domain\Model;
use Assert\AssertionFailedException;
use Centreon\Domain\Common\Assertion\Assertion;
use Security\Interfaces\EncryptionInterface;
/**
* This class represents vault configuration being created.
*/
class NewVaultConfiguration
{
public const MIN_LENGTH = 1;
public const MAX_LENGTH = 255;
public const NAME_MAX_LENGTH = 50;
public const MIN_PORT_VALUE = 1;
public const MAX_PORT_VALUE = 65535;
public const SALT_LENGTH = 128;
public const NAME_VALIDATION_REGEX = '/^[\w+\-\/]+$/';
public const DEFAULT_NAME = 'hashicorp_vault';
protected string $encryptedSecretId;
protected string $encryptedRoleId;
protected string $salt;
/**
* @param EncryptionInterface $encryption
* @param string $address
* @param int $port
* @param string $rootPath
* @param string $roleId
* @param string $secretId
* @param string $name
*
* @throws AssertionFailedException
* @throws \Exception
*/
public function __construct(
protected EncryptionInterface $encryption,
protected string $address,
protected int $port,
protected string $rootPath,
private string $roleId,
private string $secretId,
protected string $name = self::DEFAULT_NAME,
) {
Assertion::minLength($name, self::MIN_LENGTH, 'NewVaultConfiguration::name');
Assertion::maxLength($name, self::NAME_MAX_LENGTH, 'NewVaultConfiguration::name');
Assertion::regex($name, self::NAME_VALIDATION_REGEX, 'VaultConfiguration::name');
Assertion::minLength($address, self::MIN_LENGTH, 'NewVaultConfiguration::address');
Assertion::ipOrDomain($address, 'NewVaultConfiguration::address');
Assertion::max($port, self::MAX_PORT_VALUE, 'NewVaultConfiguration::port');
Assertion::min($port, self::MIN_PORT_VALUE, 'NewVaultConfiguration::port');
Assertion::minLength($rootPath, self::MIN_LENGTH, 'NewVaultConfiguration::rootPath');
Assertion::maxLength($rootPath, self::NAME_MAX_LENGTH, 'NewVaultConfiguration::rootPath');
Assertion::regex($rootPath, self::NAME_VALIDATION_REGEX, 'VaultConfiguration::name');
Assertion::minLength($this->roleId, self::MIN_LENGTH, 'NewVaultConfiguration::roleId');
Assertion::maxLength($this->roleId, self::MAX_LENGTH, 'NewVaultConfiguration::roleId');
Assertion::minLength($this->secretId, self::MIN_LENGTH, 'NewVaultConfiguration::secretId');
Assertion::maxLength($this->secretId, self::MAX_LENGTH, 'NewVaultConfiguration::secretId');
$this->salt = $this->encryption->generateRandomString(self::SALT_LENGTH);
$this->encryptedSecretId = $this->encrypt($this->secretId, $this->salt);
$this->encryptedRoleId = $this->encrypt($this->roleId, $this->salt);
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAddress(): string
{
return $this->address;
}
/**
* @return int
*/
public function getPort(): int
{
return $this->port;
}
/**
* @return string
*/
public function getRootPath(): string
{
return $this->rootPath;
}
/**
* @throws \Exception
*
* @return string
*/
public function getRoleId(): string
{
return $this->roleId;
}
/**
* @throws \Exception
*
* @return string
*/
public function getSecretId(): string
{
return $this->secretId;
}
/**
* @return string
*/
public function getEncryptedRoleId(): string
{
return $this->encryptedRoleId;
}
/**
* @return string
*/
public function getEncryptedSecretId(): string
{
return $this->encryptedSecretId;
}
/**
* @return string
*/
public function getSalt(): string
{
return $this->salt;
}
/**
* @param string $unencrypted
* @param string $salt
*
* @throws \Exception
*
* @return string
*/
private function encrypt(string $unencrypted, string $salt): string
{
return $this->encryption
->setSecondKey($salt)
->crypt($unencrypted);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Domain/Model/VaultConfiguration.php | centreon/src/Core/Security/Vault/Domain/Model/VaultConfiguration.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Domain\Model;
use Centreon\Domain\Common\Assertion\Assertion;
use Security\Interfaces\EncryptionInterface;
/**
* This class represents already existing vault configuration.
*/
class VaultConfiguration
{
/** Validation Constants */
public const MIN_LENGTH = 1;
public const MAX_LENGTH = 255;
public const NAME_MAX_LENGTH = NewVaultConfiguration::NAME_MAX_LENGTH;
public const MIN_PORT_VALUE = 1;
public const MAX_PORT_VALUE = 65535;
public const SALT_LENGTH = 128;
public const NAME_VALIDATION_REGEX = NewVaultConfiguration::NAME_VALIDATION_REGEX;
/** Static Vault Key Constants */
public const HOST_SNMP_COMMUNITY_KEY = '_HOSTSNMPCOMMUNITY';
public const OPENID_CLIENT_ID_KEY = '_OPENID_CLIENT_ID';
public const OPENID_CLIENT_SECRET_KEY = '_OPENID_CLIENT_SECRET';
public const DATABASE_USERNAME_KEY = '_DBUSERNAME';
public const DATABASE_PASSWORD_KEY = '_DBPASSWORD';
public const KNOWLEDGE_BASE_KEY = '_KBPASSWORD';
public const GORGONE_PASSWORD = '_GORGONE_PASSWORD';
/** Patterns Constants */
public const VAULT_PATH_PATTERN = 'secret::';
public const UUID_EXTRACTION_REGEX = '^(.*)\/(.*)::(.*)$';
private ?string $secretId = null;
private ?string $roleId = null;
/**
* @param EncryptionInterface $encryption
* @param string $name
* @param string $address
* @param int $port
* @param string $rootPath
* @param string $encryptedRoleId
* @param string $encryptedSecretId
* @param string $salt
*
* @throws \Exception
*/
public function __construct(
private EncryptionInterface $encryption,
private string $name,
private string $address,
private int $port,
private string $rootPath,
private string $encryptedRoleId,
private string $encryptedSecretId,
private string $salt,
) {
$this->setName($name);
$this->setAddress($address);
$this->setPort($port);
$this->setRootPath($rootPath);
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getAddress(): string
{
return $this->address;
}
/**
* @return int
*/
public function getPort(): int
{
return $this->port;
}
/**
* @return string
*/
public function getRootPath(): string
{
return $this->rootPath;
}
/**
* @throws \Exception
*
* @return string|null
*/
public function getRoleId(): ?string
{
$this->roleId = $this->encryption->setSecondKey($this->salt)->decrypt($this->encryptedRoleId);
return $this->roleId;
}
/**
* @throws \Exception
*
* @return string|null
*/
public function getSecretId(): ?string
{
$this->secretId = $this->encryption->setSecondKey($this->salt)->decrypt($this->encryptedSecretId);
return $this->secretId;
}
/**
* @return string
*/
public function getEncryptedRoleId(): string
{
return $this->encryptedRoleId;
}
/**
* @return string
*/
public function getEncryptedSecretId(): string
{
return $this->encryptedSecretId;
}
/**
* @param string $name
*/
public function setName(string $name): void
{
Assertion::minLength($name, self::MIN_LENGTH, 'VaultConfiguration::name');
Assertion::maxLength($name, self::NAME_MAX_LENGTH, 'VaultConfiguration::name');
Assertion::regex($name, self::NAME_VALIDATION_REGEX, 'VaultConfiguration::name');
$this->name = $name;
}
/**
* @param string $address
*/
public function setAddress(string $address): void
{
Assertion::minLength($address, self::MIN_LENGTH, 'VaultConfiguration::address');
Assertion::ipOrDomain($address, 'VaultConfiguration::address');
$this->address = $address;
}
/**
* @param int $port
*/
public function setPort(int $port): void
{
Assertion::max($port, self::MAX_PORT_VALUE, 'VaultConfiguration::port');
Assertion::min($port, self::MIN_PORT_VALUE, 'VaultConfiguration::port');
$this->port = $port;
}
/**
* @param string $rootPath
*/
public function setRootPath(string $rootPath): void
{
Assertion::minLength($rootPath, self::MIN_LENGTH, 'VaultConfiguration::rootPath');
Assertion::maxLength($rootPath, self::NAME_MAX_LENGTH, 'VaultConfiguration::rootPath');
Assertion::regex($rootPath, self::NAME_VALIDATION_REGEX, 'VaultConfiguration::rootPath');
$this->rootPath = $rootPath;
}
/**
* @param string|null $roleId
*/
public function setRoleId(?string $roleId): void
{
$this->roleId = $roleId;
}
/**
* @param string|null $secretId
*/
public function setSecretId(?string $secretId): void
{
$this->secretId = $secretId;
}
/**
* @param string $roleId
*
* @throws \Exception
*/
public function setNewRoleId(string $roleId): void
{
Assertion::minLength($roleId, self::MIN_LENGTH, 'VaultConfiguration::roleId');
Assertion::maxLength($roleId, self::MAX_LENGTH, 'VaultConfiguration::roleId');
$this->encryptedRoleId = $this->encryption->setSecondKey($this->salt)->crypt($roleId);
}
/**
* @param string $secretId
*
* @throws \Exception
*/
public function setNewSecretId(string $secretId): void
{
Assertion::minLength($secretId, self::MIN_LENGTH, 'VaultConfiguration::secretId');
Assertion::maxLength($secretId, self::MAX_LENGTH, 'VaultConfiguration::secretId');
$this->encryptedSecretId = $this->encryption->setSecondKey($this->salt)->crypt($secretId);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Infrastructure/Repository/FsVaultConfigurationFactory.php | centreon/src/Core/Security/Vault/Infrastructure/Repository/FsVaultConfigurationFactory.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Infrastructure\Repository;
use Assert\AssertionFailedException;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Security\Interfaces\EncryptionInterface;
class FsVaultConfigurationFactory
{
/**
* @param EncryptionInterface $encryption
*/
public function __construct(private EncryptionInterface $encryption)
{
}
/**
* @param array{
* name: string,
* url: string,
* port: int,
* root_path: string,
* role_id: string,
* secret_id: string,
* salt: string
* } $recordData
*
* @throws AssertionFailedException
* @throws \Exception
*
* @return VaultConfiguration
*/
public function createFromRecord(array $recordData): VaultConfiguration
{
return new VaultConfiguration(
$this->encryption,
(string) $recordData['name'],
(string) $recordData['url'],
(int) $recordData['port'],
(string) $recordData['root_path'],
(string) $recordData['role_id'],
(string) $recordData['secret_id'],
(string) $recordData['salt'],
);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Infrastructure/Repository/FsWriteVaultConfigurationRepository.php | centreon/src/Core/Security/Vault/Infrastructure/Repository/FsWriteVaultConfigurationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Core\Security\Vault\Application\Repository\WriteVaultConfigurationRepositoryInterface;
use Core\Security\Vault\Domain\Model\NewVaultConfiguration;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Yaml\Yaml;
class FsWriteVaultConfigurationRepository implements WriteVaultConfigurationRepositoryInterface
{
use LoggerTrait;
/**
* @param string $configurationFile
* @param Filesystem $filesystem
*/
public function __construct(
private readonly string $configurationFile,
private readonly Filesystem $filesystem,
) {
}
/**
* @inheritDoc
*/
public function create(NewVaultConfiguration $vaultConfiguration): void
{
$vaultConfigurationAsArray = [
'name' => $vaultConfiguration->getName(),
'url' => $vaultConfiguration->getAddress(),
'port' => $vaultConfiguration->getPort(),
'root_path' => $vaultConfiguration->getRootPath(),
'role_id' => $vaultConfiguration->getEncryptedRoleId(),
'secret_id' => $vaultConfiguration->getEncryptedSecretId(),
'salt' => $vaultConfiguration->getSalt(),
];
$vaultConfigurationEncoded = json_encode($vaultConfigurationAsArray)
?: throw new \Exception('Error encoding vault configuration');
$this->filesystem->dumpFile($this->configurationFile, $vaultConfigurationEncoded);
$this->filesystem->chmod($this->configurationFile, 0755);
}
/**
* @inheritDoc
*/
public function update(VaultConfiguration $vaultConfiguration): void
{
/**
* @var array<string, mixed> $vaultConfigurationAsArray
*/
$vaultConfigurationAsArray = Yaml::parseFile($this->configurationFile);
$vaultConfigurationUpdate = [
'name' => $vaultConfiguration->getName(),
'url' => $vaultConfiguration->getAddress(),
'port' => $vaultConfiguration->getPort(),
'root_path' => $vaultConfiguration->getRootPath(),
'role_id' => $vaultConfiguration->getEncryptedRoleId(),
'secret_id' => $vaultConfiguration->getEncryptedSecretId(),
];
$vaultConfigurationUpdated = json_encode(array_merge($vaultConfigurationAsArray, $vaultConfigurationUpdate))
?: throw new \Exception('Error encoding vault configuration');
$this->filesystem->dumpFile($this->configurationFile, $vaultConfigurationUpdated);
}
/**
* @inheritDoc
*/
public function delete(): void
{
$this->filesystem->remove($this->configurationFile);
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Infrastructure/Repository/FsReadVaultConfigurationRepository.php | centreon/src/Core/Security/Vault/Infrastructure/Repository/FsReadVaultConfigurationRepository.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Infrastructure\Repository;
use Centreon\Domain\Log\LoggerTrait;
use Core\Security\Vault\Application\Repository\{
ReadVaultConfigurationRepositoryInterface as ReadVaultConfigurationRepository
};
use Core\Security\Vault\Domain\Model\VaultConfiguration;
use Symfony\Component\Filesystem\Filesystem;
class FsReadVaultConfigurationRepository implements ReadVaultConfigurationRepository
{
use LoggerTrait;
public function __construct(
private readonly string $configurationFile,
private readonly Filesystem $filesystem,
private readonly FsVaultConfigurationFactory $factory,
) {
}
/**
* @inheritDoc
*/
public function exists(): bool
{
return $this->filesystem->exists($this->configurationFile);
}
/**
* @inheritDoc
*/
public function find(): ?VaultConfiguration
{
if (
! file_exists($this->configurationFile)
|| ! $vaultConfiguration = file_get_contents($this->configurationFile, true)
) {
return null;
}
$record = json_decode($vaultConfiguration, true)
?: throw new \Exception('Invalid vault configuration');
/**
* @var array{
* name: string,
* url: string,
* port: int,
* root_path: string,
* role_id: string,
* secret_id: string,
* salt: string
* } $record
*/
return $this->factory->createFromRecord($record);
}
/**
* @inheritDoc
*/
public function getLocation(): ?string
{
if (
! file_exists($this->configurationFile)
|| ! $vaultConfiguration = file_get_contents($this->configurationFile, true)
) {
return null;
}
return $this->configurationFile;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Infrastructure/API/FindVaultConfiguration/FindVaultConfigurationController.php | centreon/src/Core/Security/Vault/Infrastructure/API/FindVaultConfiguration/FindVaultConfigurationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Infrastructure\API\FindVaultConfiguration;
use Centreon\Application\Controller\AbstractController;
use Core\Security\Vault\Application\UseCase\FindVaultConfiguration\FindVaultConfiguration;
final class FindVaultConfigurationController extends AbstractController
{
/**
* @param FindVaultConfiguration $useCase
* @param FindVaultConfigurationPresenter $presenter
*
* @return object
*/
public function __invoke(
FindVaultConfiguration $useCase,
FindVaultConfigurationPresenter $presenter,
): object {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Infrastructure/API/FindVaultConfiguration/FindVaultConfigurationPresenter.php | centreon/src/Core/Security/Vault/Infrastructure/API/FindVaultConfiguration/FindVaultConfigurationPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Infrastructure\API\FindVaultConfiguration;
use Core\Application\Common\UseCase\AbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Security\Vault\Application\UseCase\FindVaultConfiguration\FindVaultConfigurationPresenterInterface;
use Core\Security\Vault\Application\UseCase\FindVaultConfiguration\FindVaultConfigurationResponse;
final class FindVaultConfigurationPresenter extends AbstractPresenter implements FindVaultConfigurationPresenterInterface
{
public function presentResponse(FindVaultConfigurationResponse|ResponseStatusInterface $data): void
{
if ($data instanceof ResponseStatusInterface) {
$this->setResponseStatus($data);
} else {
$this->present([
'address' => $data->address,
'port' => $data->port,
'root_path' => $data->rootPath,
]);
}
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Infrastructure/API/DeleteVaultConfiguration/DeleteVaultConfigurationController.php | centreon/src/Core/Security/Vault/Infrastructure/API/DeleteVaultConfiguration/DeleteVaultConfigurationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Infrastructure\API\DeleteVaultConfiguration;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Security\Vault\Application\UseCase\DeleteVaultConfiguration\DeleteVaultConfiguration;
final class DeleteVaultConfigurationController extends AbstractController
{
/**
* @param DeleteVaultConfiguration $useCase
* @param DefaultPresenter $presenter
*
* @return object
*/
public function __invoke(
DeleteVaultConfiguration $useCase,
DefaultPresenter $presenter,
): object {
$this->denyAccessUnlessGrantedForApiConfiguration();
$useCase($presenter);
return $presenter->show();
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Infrastructure/API/UpdateVaultConfiguration/UpdateVaultConfigurationController.php | centreon/src/Core/Security/Vault/Infrastructure/API/UpdateVaultConfiguration/UpdateVaultConfigurationController.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Infrastructure\API\UpdateVaultConfiguration;
use Centreon\Application\Controller\AbstractController;
use Core\Infrastructure\Common\Api\DefaultPresenter;
use Core\Security\Vault\Application\UseCase\UpdateVaultConfiguration\{
UpdateVaultConfiguration,
UpdateVaultConfigurationRequest
};
use Symfony\Component\HttpFoundation\Request;
final class UpdateVaultConfigurationController extends AbstractController
{
/**
* @param UpdateVaultConfiguration $useCase
* @param DefaultPresenter $presenter
* @param Request $request
*
* @return object
*/
public function __invoke(
UpdateVaultConfiguration $useCase,
DefaultPresenter $presenter,
Request $request,
): object {
$this->denyAccessUnlessGrantedForApiConfiguration();
/**
* @var array{
* "address": string,
* "port": integer,
* "root_path": string,
* "role_id": string,
* "secret_id": string
* } $decodedRequest
*/
$decodedRequest = $this->validateAndRetrieveDataSent(
$request,
__DIR__ . '/UpdateVaultConfigurationSchema.json'
);
$updateVaultConfigurationRequest = $this->createDtoRequest(
$decodedRequest
);
$useCase($presenter, $updateVaultConfigurationRequest);
return $presenter->show();
}
/**
* @param array{
* "address": string,
* "port": integer,
* "root_path": string,
* "role_id": string,
* "secret_id": string
* } $decodedRequest
*
* @return UpdateVaultConfigurationRequest
*/
private function createDtoRequest(
array $decodedRequest,
): UpdateVaultConfigurationRequest {
$updateVaultConfigurationRequest = new UpdateVaultConfigurationRequest();
$updateVaultConfigurationRequest->address = $decodedRequest['address'];
$updateVaultConfigurationRequest->port = $decodedRequest['port'];
$updateVaultConfigurationRequest->rootPath = $decodedRequest['root_path'];
$updateVaultConfigurationRequest->roleId = $decodedRequest['role_id'];
$updateVaultConfigurationRequest->secretId = $decodedRequest['secret_id'];
return $updateVaultConfigurationRequest;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Infrastructure/Command/MigrateAllCredentials/MigrateAllCredentialsCommand.php | centreon/src/Core/Security/Vault/Infrastructure/Command/MigrateAllCredentials/MigrateAllCredentialsCommand.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Infrastructure\Command\MigrateAllCredentials;
use Centreon\Domain\Log\LoggerTrait;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\MigrateAllCredentials;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(
name: 'vault:migrate-credentials:web',
description: 'Migrate passwords to vault',
)]
final class MigrateAllCredentialsCommand extends Command
{
use LoggerTrait;
public function __construct(
readonly private MigrateAllCredentials $useCase,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
try {
($this->useCase)(new MigrateAllCredentialsPresenter($output));
} catch (\Throwable $ex) {
$this->error($ex->getMessage(), ['trace' => (string) $ex]);
$output->writeln("<error>{(string) {$ex}}</error>");
return self::FAILURE;
}
return self::SUCCESS;
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
centreon/centreon | https://github.com/centreon/centreon/blob/6ae83001e94de0a4cec11e084780fcfa63f1c985/centreon/src/Core/Security/Vault/Infrastructure/Command/MigrateAllCredentials/MigrateAllCredentialsPresenter.php | centreon/src/Core/Security/Vault/Infrastructure/Command/MigrateAllCredentials/MigrateAllCredentialsPresenter.php | <?php
/*
* Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information : contact@centreon.com
*
*/
declare(strict_types=1);
namespace Core\Security\Vault\Infrastructure\Command\MigrateAllCredentials;
use Core\Application\Common\UseCase\CliAbstractPresenter;
use Core\Application\Common\UseCase\ResponseStatusInterface;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialErrorDto;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialRecordedDto;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\CredentialTypeEnum;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\MigrateAllCredentialsPresenterInterface;
use Core\Security\Vault\Application\UseCase\MigrateAllCredentials\MigrateAllCredentialsResponse;
use Core\Security\Vault\Domain\Model\VaultConfiguration;
class MigrateAllCredentialsPresenter extends CliAbstractPresenter implements MigrateAllCredentialsPresenterInterface
{
public function presentResponse(MigrateAllCredentialsResponse|ResponseStatusInterface $response): void
{
if ($response instanceof ResponseStatusInterface) {
$this->error($response->getMessage());
} else {
foreach ($response->results as $result) {
if ($result instanceof CredentialRecordedDto) {
$this->writeMultiLine([
"<ok> OK {{$this->prefixMacroName($result)}}</>",
"<ok> - Type: {$this->convertTypeToString($result->type)}</>",
"<ok> - Resource ID: {$result->resourceId}</>",
"<ok> - Vault Path: {$result->vaultPath}</>",
"<ok> - UUID: {$result->uuid}</>",
]);
} elseif ($result instanceof CredentialErrorDto) {
$this->writeMultiLine([
"<error> ERROR {{$this->prefixMacroName($result)}}</>",
"<error> - Type: {$this->convertTypeToString($result->type)}</>",
"<error> - Resource ID: {$result->resourceId}</>",
"<error> - Error: {$result->message}</>",
]);
}
}
}
}
/**
* Convert the enum into a string.
*
* @param CredentialTypeEnum $type
*
* @return string
*/
private function convertTypeToString(CredentialTypeEnum $type): string
{
return match ($type) {
CredentialTypeEnum::TYPE_HOST => 'host',
CredentialTypeEnum::TYPE_SERVICE => 'service',
CredentialTypeEnum::TYPE_HOST_TEMPLATE => 'host_template',
CredentialTypeEnum::TYPE_KNOWLEDGE_BASE_PASSWORD => 'knowledge_base',
CredentialTypeEnum::TYPE_POLLER_MACRO => 'poller_macro',
CredentialTypeEnum::TYPE_OPEN_ID => 'open_id',
CredentialTypeEnum::TYPE_BROKER_INPUT_OUTPUT => 'broker_input_output',
CredentialTypeEnum::TYPE_ADDITIONAL_CONNECTOR_CONFIGURATION => 'additional_connector_configuration',
};
}
/**
* Prefix the macro with _HOST or _SERVICE depending of the type.
*
* @param CredentialRecordedDto|CredentialErrorDto $dto
*
* @return string
*/
private function prefixMacroName(CredentialRecordedDto|CredentialErrorDto $dto): string
{
if ($dto->credentialName === VaultConfiguration::HOST_SNMP_COMMUNITY_KEY) {
return $dto->credentialName;
}
return match ($dto->type) {
CredentialTypeEnum::TYPE_HOST, CredentialTypeEnum::TYPE_HOST_TEMPLATE => '_HOST' . $dto->credentialName,
CredentialTypeEnum::TYPE_SERVICE => '_SERVICE' . $dto->credentialName,
default => $dto->credentialName,
};
}
}
| php | Apache-2.0 | 6ae83001e94de0a4cec11e084780fcfa63f1c985 | 2026-01-05T04:45:18.914281Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.