Merge pull request 'feature-run-as-admin' (#80) from feature-run-as-admin into develop
testing/ogcore-api/pipeline/head This commit looks good
Details
testing/ogcore-api/pipeline/head This commit looks good
Details
Reviewed-on: #80pull/81/head^2
commit
7477abffba
|
|
@ -37,4 +37,5 @@ debian/files
|
|||
### Certificates
|
||||
certs/
|
||||
|
||||
|
||||
.venv/
|
||||
.vscode/
|
||||
|
|
|
|||
35
CHANGELOG.md
35
CHANGELOG.md
|
|
@ -1,4 +1,39 @@
|
|||
# Changelog
|
||||
## [1.2.8] - 2026-03-20
|
||||
### Added
|
||||
- Modificado MenuBrowserController para permitir la edición de las plantillas de menú en "raw", permitiendo modificar el código twig en lugar del html ya compilado por twig, de esta forma podemos editar el fichero twig y aplicar cambios para ver el resultado antes de guardar la plantilla.
|
||||
|
||||
## [1.2.7] - 2026-03-17
|
||||
### Fixed
|
||||
- Se ha corregido la lectura de la variable `OGCLIENT_API_KEY` desde `env.json` para inyectarla correctamente en la plantilla PXE generada por `ogBoot`.
|
||||
|
||||
## [1.2.6] - 2026-03-17
|
||||
### Added
|
||||
- Se ha añadido AssetsManagerController para la gestion de assets.
|
||||
|
||||
## [1.2.5] - 2026-03-16
|
||||
### Fixed
|
||||
- Se ha modificado el fichero security.yml para que el acceso a la api lo tenga el ROLE_USER en lugar de IS_AUTHENTICATED_FULLY, ya que de lo contrario cualquier cliente con rol ROLE_OGCLIENT_API podia acceder a la api, de esta forma se asegura que solo los usuarios con rol ROLE_USER puedan acceder a la api y el cliente solo pueda acceder a la ruta commands.
|
||||
|
||||
## [1.2.4] - 2026-03-16
|
||||
### Added
|
||||
- Se ha implementado un nuevo [ApiKeyAuthenticator] para dotar de acceso seguro al endpoint `/commands` mediante la cabecera `X-API-KEY`.
|
||||
- Incorporación de la variable global de entorno `OGCLIENT_API_KEY` en env.json para gestionar el token de acceso de clientes desde la interfaz gráfica.
|
||||
### Changed
|
||||
- Se ha modificado el controlador PostAction de `PxeBootFile` para inyectar y propagar la clave `ogclient_api_key` al payload que se envía a `ogBoot` durante la creación del arranque.
|
||||
|
||||
## [1.2.3] - 2026-03-11
|
||||
### Added
|
||||
- Se ha añadido una nueva funcionalidad en el DTO `MenuInput` (campo `menuHtmlContent`) para recibir la plantilla HTML íntegra del menú codificada en Base64.
|
||||
|
||||
### Improved
|
||||
- Se ha refactorizado y asegurado la lógica de creación de menús dentro de `MenuProcessor`, para decodificar estrictamente el payload en Base64 y sobreescribir físicamente la plantilla `.twig` descartando la plantilla por defecto.
|
||||
|
||||
## [1.2.2] - 2026-02-27
|
||||
### Improved
|
||||
- Nuevo menú por defecto en el cliente, organizando la información por discos
|
||||
|
||||
---
|
||||
## [1.2.1] - 2025-10-22
|
||||
### Fixed
|
||||
- Se ha corregido un error en el commando que se encarga de ejecutar tareas pendientes.
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ security:
|
|||
success_handler: lexik_jwt_authentication.handler.authentication_success
|
||||
failure_handler: lexik_jwt_authentication.handler.authentication_failure
|
||||
jwt: ~
|
||||
custom_authenticators:
|
||||
- App\Security\ApiKeyAuthenticator
|
||||
refresh_jwt:
|
||||
check_path: refresh_token
|
||||
|
||||
|
|
@ -29,6 +31,7 @@ security:
|
|||
- { path: ^/$, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI
|
||||
- { path: ^/docs, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI docs
|
||||
- { path: ^/auth/login, roles: PUBLIC_ACCESS }
|
||||
- { path: ^/commands, roles: [ROLE_OGCLIENT_API, ROLE_USER] }
|
||||
- { path: ^/opengnsys/rest, roles: PUBLIC_ACCESS }
|
||||
- { path: ^/og-repository/webhook, roles: PUBLIC_ACCESS }
|
||||
- { path: ^/og-lives/install/webhook, roles: PUBLIC_ACCESS }
|
||||
|
|
@ -36,7 +39,7 @@ security:
|
|||
- { path: ^/validate, roles: PUBLIC_ACCESS }
|
||||
- { path: ^/menu-browser, roles: PUBLIC_ACCESS }
|
||||
- { path: ^/menu/, roles: PUBLIC_ACCESS }
|
||||
- { path: ^/, roles: IS_AUTHENTICATED_FULLY }
|
||||
- { path: ^/, roles: ROLE_USER }
|
||||
|
||||
when@test:
|
||||
security:
|
||||
|
|
|
|||
3
env.json
3
env.json
|
|
@ -10,6 +10,7 @@
|
|||
"SSL_ENABLED": "false",
|
||||
"OG_BOOT_IP": "127.0.0.1",
|
||||
"OG_BOOT_API_PORT": "8082",
|
||||
"OG_BOOT_PXE_PORT": "8082"
|
||||
"OG_BOOT_PXE_PORT": "8082",
|
||||
"OGCLIENT_API_KEY": "ogclient-super-secret-token"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,160 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Filesystem\Filesystem;
|
||||
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
|
||||
use ZipArchive;
|
||||
|
||||
class AssetManagerController extends AbstractController {
|
||||
private function getSecureTargetPath(string $projectDir, string $requestedPath): ?string
|
||||
{
|
||||
$baseAssetsDir = $projectDir . '/public/assets';
|
||||
$result = null;
|
||||
|
||||
if (!is_dir($baseAssetsDir)) {
|
||||
mkdir($baseAssetsDir, 0755, true);
|
||||
}
|
||||
$realBase = realpath($baseAssetsDir);
|
||||
|
||||
if (strpos($requestedPath, '..') === false) {
|
||||
$theoreticalPath = rtrim($realBase . '/' . ltrim($requestedPath, '/\\'), '/');
|
||||
|
||||
if (!file_exists($theoreticalPath)) {
|
||||
$result = $theoreticalPath;
|
||||
} else {
|
||||
$realTarget = realpath($theoreticalPath);
|
||||
if ($realTarget !== false && str_starts_with($realTarget, $realBase)) {
|
||||
$result = $realTarget;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
#[Route('/ogassets/list', name: 'api_assets_list', methods: ['GET'])]
|
||||
public function listAssets(Request $request, ParameterBagInterface $params): JsonResponse
|
||||
{
|
||||
$requestedPath = $request->query->get('path', '');
|
||||
$targetPath = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath);
|
||||
$response = null;
|
||||
|
||||
if ($targetPath === null || !is_dir($targetPath)) {
|
||||
$response = new JsonResponse(['message' => 'Directorio inválido o no encontrado.'], Response::HTTP_NOT_FOUND);
|
||||
} else {
|
||||
$items = [];
|
||||
$iterator = new \DirectoryIterator($targetPath);
|
||||
foreach ($iterator as $fileinfo) {
|
||||
if ($fileinfo->isDot()) continue;
|
||||
|
||||
$items[] = [
|
||||
'name' => $fileinfo->getFilename(),
|
||||
'type' => $fileinfo->isDir() ? 'folder' : 'file',
|
||||
'size' => $fileinfo->isFile() ? $fileinfo->getSize() : null,
|
||||
'path' => ltrim($requestedPath . '/' . $fileinfo->getFilename(), '/')
|
||||
];
|
||||
}
|
||||
|
||||
usort($items, function($a, $b) {
|
||||
if ($a['type'] === $b['type']) {
|
||||
return strcasecmp($a['name'], $b['name']);
|
||||
}
|
||||
return $a['type'] === 'folder' ? -1 : 1;
|
||||
});
|
||||
|
||||
$response = new JsonResponse($items, Response::HTTP_OK);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
#[Route('/ogassets/upload', name: 'api_assets_upload', methods: ['POST'])]
|
||||
public function uploadAsset(Request $request, ParameterBagInterface $params, Filesystem $filesystem): JsonResponse
|
||||
{
|
||||
$file = $request->files->get('file');
|
||||
$requestedPath = $request->request->get('path', '');
|
||||
$extractZip = $request->request->getBoolean('extractZip', false);
|
||||
$response = null;
|
||||
|
||||
if (!$file) {
|
||||
$response = new JsonResponse(['message' => 'No file uploaded.'], Response::HTTP_BAD_REQUEST);
|
||||
} else {
|
||||
$targetDir = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath);
|
||||
|
||||
if ($targetDir === null) {
|
||||
$response = new JsonResponse(['message' => 'Ruta destino inválida.'], Response::HTTP_FORBIDDEN);
|
||||
} else {
|
||||
if (!is_dir($targetDir)) {
|
||||
mkdir($targetDir, 0755, true);
|
||||
$targetDir = realpath($targetDir);
|
||||
}
|
||||
|
||||
$originalName = $file->getClientOriginalName();
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
|
||||
if ($extractZip && $extension === 'zip') {
|
||||
$safeName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', pathinfo($originalName, PATHINFO_FILENAME));
|
||||
$extractDir = $targetDir . '/' . $safeName;
|
||||
|
||||
if (!$filesystem->exists($extractDir)) {
|
||||
$filesystem->mkdir($extractDir, 0755);
|
||||
}
|
||||
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($file->getPathname()) === true) {
|
||||
$zip->extractTo($extractDir);
|
||||
$zip->close();
|
||||
$response = new JsonResponse(['message' => 'ZIP extraído correctamente.']);
|
||||
} else {
|
||||
$response = new JsonResponse(['message' => 'Error al extraer ZIP.'], Response::HTTP_INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
$file->move($targetDir, $originalName);
|
||||
$response = new JsonResponse(['message' => 'Archivo subido correctamente.']);
|
||||
} catch (\Exception $e) {
|
||||
$response = new JsonResponse(['message' => 'Error al guardar el archivo.'], Response::HTTP_INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
#[Route('/ogassets/delete', name: 'api_assets_delete', methods: ['DELETE'])]
|
||||
public function deleteAsset(Request $request, ParameterBagInterface $params, Filesystem $filesystem): JsonResponse
|
||||
{
|
||||
$data = json_decode($request->getContent(), true);
|
||||
$requestedPath = $data['path'] ?? '';
|
||||
$response = null;
|
||||
|
||||
if (empty($requestedPath)) {
|
||||
$response = new JsonResponse(['message' => 'Ruta requerida.'], Response::HTTP_BAD_REQUEST);
|
||||
} else {
|
||||
$realBase = realpath($params->get('kernel.project_dir') . '/public/assets');
|
||||
$targetPath = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath);
|
||||
|
||||
if ($targetPath === null || !file_exists($targetPath) || $targetPath === $realBase) {
|
||||
$response = new JsonResponse(['message' => 'Ruta inválida o prohibida.'], Response::HTTP_FORBIDDEN);
|
||||
} else {
|
||||
try {
|
||||
$filesystem->remove($targetPath);
|
||||
$response = new JsonResponse(['message' => 'Elemento eliminado correctamente.']);
|
||||
} catch (\Exception $e) {
|
||||
$response = new JsonResponse(['message' => 'Error al eliminar el elemento.'], Response::HTTP_INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ use Doctrine\ORM\EntityManagerInterface;
|
|||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Twig\Environment;
|
||||
|
||||
|
|
@ -29,9 +30,42 @@ class MenuBrowserController extends AbstractController
|
|||
$partitions = [];
|
||||
|
||||
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $host]);
|
||||
|
||||
$disks = []; // Array nuevo estructurado
|
||||
|
||||
if ($client) {
|
||||
$partitions = $client->getPartitions();
|
||||
$rawPartitions = $client->getPartitions()->toArray();
|
||||
|
||||
foreach ($rawPartitions as $part) {
|
||||
$diskNum = $part->getDiskNumber();
|
||||
$partNum = $part->getPartitionNumber();
|
||||
|
||||
// Inicializamos el array del disco si no existe
|
||||
if (!isset($disks[$diskNum])) {
|
||||
$disks[$diskNum] = [
|
||||
'info' => null, // Aquí guardaremos la partición 0 (tamaño total)
|
||||
'parts' => [] // Aquí las particiones reales
|
||||
];
|
||||
}
|
||||
|
||||
if ($partNum == 0) {
|
||||
// Es la info del disco completo
|
||||
$disks[$diskNum]['info'] = $part;
|
||||
} else {
|
||||
// Es una partición normal
|
||||
$disks[$diskNum]['parts'][] = $part;
|
||||
}
|
||||
}
|
||||
|
||||
// Ordenamos los discos (1, 2, 3...)
|
||||
ksort($disks);
|
||||
|
||||
// Ordenamos las particiones dentro de cada disco (1, 2, 3...)
|
||||
foreach ($disks as &$diskData) {
|
||||
usort($diskData['parts'], function($a, $b) {
|
||||
return $a->getPartitionNumber() <=> $b->getPartitionNumber();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
$menuName = $client->getMenu()->getPublicUrl();
|
||||
|
|
@ -39,11 +73,11 @@ class MenuBrowserController extends AbstractController
|
|||
return $this->render('browser/' . $menuName . '.html.twig', [
|
||||
'ip' => $host,
|
||||
'mac' => $client ? $client->getMac() : null,
|
||||
'partitions' => $partitions,
|
||||
'disks' => $disks,
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/menu/{templateName}', name: 'render_menu_template')]
|
||||
#[Route('/menu/{templateName}', name: 'render_menu_template', requirements: ['templateName' => '.+'])]
|
||||
public function renderMenu(string $templateName, Request $request): Response
|
||||
{
|
||||
$templatePath = 'browser/' . $templateName . '.html.twig';
|
||||
|
|
@ -54,7 +88,49 @@ class MenuBrowserController extends AbstractController
|
|||
|
||||
return $this->render($templatePath, [
|
||||
'ip' => 'invitado',
|
||||
'partitions' => [],
|
||||
'disks' => [],
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/menu-raw/{templateName}', name: 'get_raw_menu_template', requirements: ['templateName' => '.+'], methods: ['GET'])]
|
||||
public function getRawMenu(string $templateName, Request $request): Response
|
||||
{
|
||||
$templatePath = 'browser/' . $templateName . '.html.twig';
|
||||
|
||||
if (!$this->twig->getLoader()->exists($templatePath)) {
|
||||
throw $this->createNotFoundException(sprintf('La plantilla "%s" no existe.', $templateName));
|
||||
}
|
||||
|
||||
$content = $this->twig->getLoader()->getSourceContext($templatePath)->getCode();
|
||||
|
||||
return new Response($content, Response::HTTP_OK, ['Content-Type' => 'text/plain; charset=utf-8']);
|
||||
}
|
||||
|
||||
#[Route('/menu-preview', name: 'preview_menu_template', methods: ['POST'])]
|
||||
public function previewMenu(Request $request): Response
|
||||
{
|
||||
$data = json_decode($request->getContent(), true);
|
||||
$base64Template = $data['templateBase64'] ?? '';
|
||||
|
||||
if (empty($base64Template)) {
|
||||
return new JsonResponse(['message' => 'Falta el contenido de la plantilla.'], Response::HTTP_BAD_REQUEST);
|
||||
}
|
||||
|
||||
$content = base64_decode($base64Template);
|
||||
if ($content === false) {
|
||||
return new JsonResponse(['message' => 'El contenido Base64 es inválido.'], Response::HTTP_BAD_REQUEST);
|
||||
}
|
||||
|
||||
try {
|
||||
$template = $this->twig->createTemplate($content);
|
||||
$rendered = $template->render([
|
||||
'ip' => '127.0.0.1 (Previsualización)',
|
||||
'mac' => '00:00:00:00:00:00',
|
||||
'disks' => [],
|
||||
]);
|
||||
return new Response($rendered, Response::HTTP_OK, ['Content-Type' => 'text/html; charset=utf-8']);
|
||||
} catch (\Exception $e) {
|
||||
return new JsonResponse(['message' => 'Error al compilar la plantilla Twig: ' . $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ class RunScriptAction extends AbstractOgAgentController
|
|||
throw new BadRequestHttpException('IP is required');
|
||||
}
|
||||
|
||||
$data = $this->buildRequestData($client, $input->script);
|
||||
$data = $this->buildRequestData($client, $input->script, $input->runAsAdmin);
|
||||
$response = $this->executeScript($client, $data);
|
||||
|
||||
if (isset($response['code']) && $response['code'] === 409) {
|
||||
|
|
@ -58,21 +58,14 @@ class RunScriptAction extends AbstractOgAgentController
|
|||
return new JsonResponse(data: $clientJobs, status: Response::HTTP_OK);
|
||||
}
|
||||
|
||||
private function buildRequestData(Client $client, string $script): array
|
||||
private function buildRequestData(Client $client, string $script, bool $runAsAdmin = false): array
|
||||
{
|
||||
$scriptBase64 = base64_encode($script);
|
||||
|
||||
if ($this->isLinuxOrWindows($client)) {
|
||||
if ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) {
|
||||
return [
|
||||
'script' => $scriptBase64,
|
||||
'client' => 'false'
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->isLinuxOrWindowsSession($client)) {
|
||||
return [
|
||||
'script' => $scriptBase64,
|
||||
'client' => 'true'
|
||||
'client' => $runAsAdmin ? 'false' : 'true'
|
||||
];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -41,6 +41,8 @@ abstract class AbstractOgBootController extends AbstractController
|
|||
protected readonly CreateService $createService,
|
||||
protected readonly SimplifyOgLiveFilenameService $simplifyOgLiveFilenameService,
|
||||
protected readonly ExtractOgLiveFilenameDateService $extractOgLiveFilenameDateService,
|
||||
#[Autowire(env: 'OGCLIENT_API_KEY')]
|
||||
protected string $ogClientApiKey,
|
||||
protected readonly LoggerInterface $logger,
|
||||
|
||||
)
|
||||
|
|
|
|||
|
|
@ -58,7 +58,8 @@ class PostAction extends AbstractOgBootController
|
|||
'ogntp' => $client->getOrganizationalUnit()->getNetworkSettings()?->getNtp(),
|
||||
'ogdns' => $client->getOrganizationalUnit()->getNetworkSettings()?->getDns(),
|
||||
'ogProxy' => $client->getOrganizationalUnit()->getNetworkSettings()?->getProxy(),
|
||||
'resolution' => $client->getResolution() ?? '791'
|
||||
'resolution' => $client->getResolution() ?? '791',
|
||||
'ogclient_api_key' => $this->ogClientApiKey
|
||||
]
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -34,4 +34,11 @@ final class CommandExecuteInput
|
|||
example: false
|
||||
)]
|
||||
public bool $queue = false;
|
||||
|
||||
#[Groups(['command:write'])]
|
||||
#[ApiProperty(
|
||||
description: 'Si ejecutar el script en modo administrador',
|
||||
example: false
|
||||
)]
|
||||
public bool $runAsAdmin = false;
|
||||
}
|
||||
|
|
@ -37,6 +37,10 @@ final class MenuInput
|
|||
#[ApiProperty(description: 'The default menu', example: "false")]
|
||||
public ?bool $isDefault = false;
|
||||
|
||||
#[Groups(['menu:write'])]
|
||||
#[ApiProperty(description: 'HTML Content of the menu in Base64', example: "PGh0bWw+PC9odG1sPg==")]
|
||||
public ?string $menuHtmlContent = null;
|
||||
|
||||
public function __construct(?Menu $menu = null)
|
||||
{
|
||||
if (!$menu) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
|
||||
namespace App\Security;
|
||||
|
||||
use App\Entity\User;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
|
||||
use Symfony\Component\Security\Core\Exception\AuthenticationException;
|
||||
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
|
||||
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
|
||||
use Symfony\Component\HttpKernel\KernelInterface;
|
||||
|
||||
class ApiKeyAuthenticator extends AbstractAuthenticator
|
||||
{
|
||||
private string $projectDir;
|
||||
|
||||
public function __construct(KernelInterface $kernel)
|
||||
{
|
||||
$this->projectDir = $kernel->getProjectDir();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called on every request to decide if this authenticator should be used for the request.
|
||||
* Returning `false` will cause this authenticator to be skipped.
|
||||
*/
|
||||
public function supports(Request $request): ?bool
|
||||
{
|
||||
return $request->headers->has('X-API-KEY');
|
||||
}
|
||||
|
||||
public function authenticate(Request $request): Passport
|
||||
{
|
||||
$apiToken = $request->headers->get('X-API-KEY');
|
||||
|
||||
$envFile = $this->projectDir . DIRECTORY_SEPARATOR . 'env.json';
|
||||
if (!is_file($envFile)) {
|
||||
throw new CustomUserMessageAuthenticationException('Configuration file not found.');
|
||||
}
|
||||
|
||||
$config = json_decode(file_get_contents($envFile), true);
|
||||
$expectedToken = $config['vars']['OGCLIENT_API_KEY'] ?? null;
|
||||
|
||||
if (null === $expectedToken || $apiToken !== $expectedToken) {
|
||||
throw new CustomUserMessageAuthenticationException('Invalid API Token.');
|
||||
}
|
||||
|
||||
// Usamos tu propia entidad User para crear un usuario virtual "al vuelo"
|
||||
return new SelfValidatingPassport(new UserBadge('ogclient_api_user', function() {
|
||||
$apiUser = new User();
|
||||
$apiUser->setUsername('ogclient_api_user');
|
||||
$apiUser->setRoles(['ROLE_OGCLIENT_API']);
|
||||
$apiUser->setPassword(''); // Evitamos nulos en propiedades requeridas si las hay
|
||||
|
||||
return $apiUser;
|
||||
}));
|
||||
}
|
||||
|
||||
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
|
||||
{
|
||||
// on success, let the request continue
|
||||
return null;
|
||||
}
|
||||
|
||||
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
|
||||
{
|
||||
$data = [
|
||||
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
|
||||
];
|
||||
|
||||
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
|
|
@ -12,12 +12,19 @@ use ApiPlatform\Validator\ValidatorInterface;
|
|||
use App\Dto\Input\MenuInput;
|
||||
use App\Dto\Output\MenuOutput;
|
||||
use App\Repository\MenuRepository;
|
||||
use App\Entity\Menu;
|
||||
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
|
||||
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
|
||||
use Symfony\Component\Filesystem\Filesystem;
|
||||
|
||||
|
||||
readonly class MenuProcessor implements ProcessorInterface
|
||||
{
|
||||
public function __construct(
|
||||
private MenuRepository $menuRepository,
|
||||
private ValidatorInterface $validator
|
||||
private ValidatorInterface $validator,
|
||||
private ParameterBagInterface $params,
|
||||
private Filesystem $filesystem
|
||||
)
|
||||
{
|
||||
}
|
||||
|
|
@ -47,12 +54,24 @@ readonly class MenuProcessor implements ProcessorInterface
|
|||
}
|
||||
|
||||
$entity = null;
|
||||
$oldPublicUrl = null;
|
||||
|
||||
if (isset($uriVariables['uuid'])) {
|
||||
$entity = $this->menuRepository->findOneByUuid($uriVariables['uuid']);
|
||||
if ($entity) {
|
||||
$oldPublicUrl = $entity->getPublicUrl();
|
||||
}
|
||||
}
|
||||
|
||||
$menu = $data->createOrUpdateEntity($entity);
|
||||
$this->validator->validate($menu);
|
||||
|
||||
// Extraemos el contenido base64 (asumiendo que $data es tu MenuInput)
|
||||
$base64HtmlContent = property_exists($data, 'menuHtmlContent') ? $data->menuHtmlContent : null;
|
||||
|
||||
// Sincronización de ficheros físicos y caché
|
||||
$this->syncMenuTemplateFile($menu, $operation, $oldPublicUrl, $base64HtmlContent);
|
||||
|
||||
$this->menuRepository->save($menu);
|
||||
|
||||
return new MenuOutput($menu);
|
||||
|
|
@ -60,9 +79,160 @@ readonly class MenuProcessor implements ProcessorInterface
|
|||
|
||||
private function processDelete($data, Operation $operation, array $uriVariables = [], array $context = []): null
|
||||
{
|
||||
$user = $this->menuRepository->findOneByUuid($uriVariables['uuid']);
|
||||
$this->menuRepository->delete($user);
|
||||
$entity = null;
|
||||
|
||||
if (isset($uriVariables['uuid'])) {
|
||||
$entity = $this->menuRepository->findOneByUuid($uriVariables['uuid']);
|
||||
|
||||
if ($entity) {
|
||||
// 1. Borrar el fichero físico y la caché antes de eliminar de BD
|
||||
$this->removeMenuTemplateFile($entity);
|
||||
|
||||
// 2. Eliminar de la base de datos
|
||||
$this->menuRepository->delete($entity);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates, renames, and updates the Twig file associated with the menu.
|
||||
* Throws \RuntimeException if any file system operation fails.
|
||||
*/
|
||||
private function syncMenuTemplateFile(Menu $menu, Operation $operation, ?string $oldPublicUrl, ?string $base64HtmlContent = null): void
|
||||
{
|
||||
$newPublicUrl = $menu->getPublicUrl();
|
||||
|
||||
if ($newPublicUrl) {
|
||||
$projectDir = $this->params->get('kernel.project_dir');
|
||||
$templatesDir = rtrim($projectDir, '/') . '/templates/browser/';
|
||||
$newTemplateName = preg_replace('#^/menu/#', '', parse_url($newPublicUrl, PHP_URL_PATH));
|
||||
|
||||
if (!empty($newTemplateName)) {
|
||||
$targetFile = $templatesDir . $newTemplateName . '.html.twig';
|
||||
$filesChanged = false;
|
||||
|
||||
try {
|
||||
// 1. RENAME OPERATION (Only for PUT/PATCH if URL changed)
|
||||
if (($operation instanceof Put || $operation instanceof Patch) && $newPublicUrl !== $oldPublicUrl && $oldPublicUrl) {
|
||||
$oldTemplateName = preg_replace('#^/menu/#', '', parse_url($oldPublicUrl, PHP_URL_PATH));
|
||||
$sourceFile = $templatesDir . $oldTemplateName . '.html.twig';
|
||||
|
||||
if ($this->filesystem->exists($sourceFile)) {
|
||||
$this->filesystem->mkdir(dirname($targetFile), 0755);
|
||||
$this->filesystem->rename($sourceFile, $targetFile, true);
|
||||
$this->cleanupEmptyDirectories(dirname($sourceFile), $templatesDir);
|
||||
$filesChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. DETERMINE CONTENT
|
||||
$contentToWrite = "{# Template for menu: {$menu->getName()} #}\n{% extends 'base.html.twig' %}\n{% block body %}\n <h1>{$menu->getName()}</h1>\n{% endblock %}\n";
|
||||
$hasCustomContent = false;
|
||||
|
||||
if (!empty($base64HtmlContent)) {
|
||||
$decodedContent = base64_decode($base64HtmlContent, true); // true = strict mode
|
||||
if ($decodedContent !== false) {
|
||||
$contentToWrite = $decodedContent;
|
||||
$hasCustomContent = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. WRITE OPERATION (If file doesn't exist, OR if we received explicit HTML content)
|
||||
if (!$this->filesystem->exists($targetFile) || $hasCustomContent) {
|
||||
$this->filesystem->mkdir(dirname($targetFile), 0755);
|
||||
$this->filesystem->dumpFile($targetFile, $contentToWrite);
|
||||
|
||||
$filesChanged = true;
|
||||
}
|
||||
|
||||
// 4. TWIG CACHE INVALIDATION
|
||||
if ($filesChanged) {
|
||||
$env = $this->params->get('kernel.environment');
|
||||
$twigCacheDir = $projectDir . '/var/cache/' . $env . '/twig';
|
||||
|
||||
if ($this->filesystem->exists($twigCacheDir)) {
|
||||
$this->filesystem->remove($twigCacheDir);
|
||||
}
|
||||
}
|
||||
} catch (IOExceptionInterface $exception) {
|
||||
throw new \RuntimeException(
|
||||
sprintf('Critical failure synchronizing menu template file. Reason: %s', $exception->getMessage()),
|
||||
0,
|
||||
$exception
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the Twig file associated with the menu, cleans up empty parent directories,
|
||||
* and clears the cache. Throws \RuntimeException if any file system operation fails.
|
||||
*/
|
||||
private function removeMenuTemplateFile(Menu $menu): void
|
||||
{
|
||||
$publicUrl = $menu->getPublicUrl();
|
||||
|
||||
if ($publicUrl) {
|
||||
$projectDir = $this->params->get('kernel.project_dir');
|
||||
$templatesDir = $projectDir . '/templates/browser/';
|
||||
$templateName = preg_replace('#^/menu/#', '', parse_url($publicUrl, PHP_URL_PATH));
|
||||
|
||||
if (!empty($templateName)) {
|
||||
$targetFile = $templatesDir . $templateName . '.html.twig';
|
||||
|
||||
try {
|
||||
if ($this->filesystem->exists($targetFile)) {
|
||||
// 1. Delete the actual file
|
||||
$this->filesystem->remove($targetFile);
|
||||
|
||||
$this->cleanupEmptyDirectories(dirname($targetFile), $templatesDir);
|
||||
|
||||
// 3. TWIG CACHE INVALIDATION
|
||||
$env = $this->params->get('kernel.environment');
|
||||
$twigCacheDir = $projectDir . '/var/cache/' . $env . '/twig';
|
||||
|
||||
if ($this->filesystem->exists($twigCacheDir)) {
|
||||
$this->filesystem->remove($twigCacheDir);
|
||||
}
|
||||
}
|
||||
} catch (IOExceptionInterface $exception) {
|
||||
throw new \RuntimeException(
|
||||
sprintf('Critical failure removing menu template file or directories. Reason: %s', $exception->getMessage()), 0, $exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Traverses upwards from a starting directory to a base directory, removing empty folders.
|
||||
*/
|
||||
private function cleanupEmptyDirectories(string $startDir, string $baseDir): void
|
||||
{
|
||||
$currentDir = $startDir;
|
||||
$baseDirExact = rtrim($baseDir, '/');
|
||||
$continueCleaning = true;
|
||||
|
||||
// La condición del while tiene el control absoluto del flujo
|
||||
while ($continueCleaning && $currentDir !== $baseDirExact && str_starts_with($currentDir, $baseDirExact)) {
|
||||
// Asumimos que pararemos, a menos que encontremos una carpeta vacía
|
||||
$continueCleaning = false;
|
||||
|
||||
if (is_dir($currentDir)) {
|
||||
$dirContents = array_diff(scandir($currentDir), ['.', '..']);
|
||||
|
||||
if (empty($dirContents)) {
|
||||
$this->filesystem->remove($currentDir);
|
||||
$currentDir = dirname($currentDir);
|
||||
|
||||
// Como hemos borrado esta, le decimos al bucle que siga mirando arriba
|
||||
$continueCleaning = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@
|
|||
background-color: var(--background-color);
|
||||
color: var(--text-color);
|
||||
line-height: 1.5;
|
||||
background-image:
|
||||
background-image:
|
||||
radial-gradient(at 0% 0%, rgba(37, 99, 235, 0.1) 0px, transparent 50%),
|
||||
radial-gradient(at 100% 100%, rgba(5, 150, 105, 0.1) 0px, transparent 50%);
|
||||
min-height: 100vh;
|
||||
|
|
@ -210,15 +210,15 @@
|
|||
.linux i { color: var(--success-color); }
|
||||
.apagar i { color: var(--danger-color); }
|
||||
|
||||
.windows a:hover {
|
||||
.windows a:hover {
|
||||
background-color: rgba(37, 99, 235, 0.1);
|
||||
color: var(--primary-color);
|
||||
}
|
||||
.linux a:hover {
|
||||
.linux a:hover {
|
||||
background-color: rgba(5, 150, 105, 0.1);
|
||||
color: var(--success-color);
|
||||
}
|
||||
.apagar a:hover {
|
||||
.apagar a:hover {
|
||||
background-color: rgba(220, 38, 38, 0.1);
|
||||
color: var(--danger-color);
|
||||
}
|
||||
|
|
@ -393,7 +393,6 @@
|
|||
border: 2px dashed #cbd5e1;
|
||||
}
|
||||
|
||||
/* Estados especiales para diferentes tipos de particiones */
|
||||
.partition-os {
|
||||
font-weight: 600;
|
||||
color: var(--success-color);
|
||||
|
|
@ -444,6 +443,57 @@
|
|||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- NUEVOS ESTILOS PARA LA AGRUPACIÓN POR DISCOS --- */
|
||||
.disk-container {
|
||||
margin-bottom: 2.5rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: var(--border-radius);
|
||||
overflow: hidden;
|
||||
background: white;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.02);
|
||||
}
|
||||
|
||||
.disk-header {
|
||||
background: #f8fafc;
|
||||
padding: 1rem 1.5rem;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.disk-header h3 {
|
||||
margin: 0;
|
||||
font-size: 1.1rem;
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.disk-total-badge {
|
||||
background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
|
||||
color: white;
|
||||
padding: 0.35rem 0.85rem;
|
||||
border-radius: 20px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 2px 4px rgba(37, 99, 235, 0.2);
|
||||
}
|
||||
|
||||
.empty-disk {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
color: #64748b;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.partition-number {
|
||||
font-weight: bold;
|
||||
font-size: 1.1rem;
|
||||
color: var(--text-color);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
|
@ -475,48 +525,81 @@
|
|||
</section>
|
||||
|
||||
<section class="partitions-section">
|
||||
<h2><i class="fas fa-hdd"></i> Particiones del sistema</h2>
|
||||
|
||||
{% if partitions|length > 0 %}
|
||||
<div class="partitions-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Disco</th>
|
||||
<th>Partición</th>
|
||||
<th>Tamaño</th>
|
||||
<th>Tipo</th>
|
||||
<th>SO</th>
|
||||
<th>Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for partition in partitions %}
|
||||
<tr>
|
||||
<td><strong>{{ partition.diskNumber }}</strong></td>
|
||||
<td><span class="partition-type">{{ partition.partitionNumber }}</span></td>
|
||||
<td class="partition-size">{{ (partition.size / 1024)|number_format(2) }} MB</td>
|
||||
<td><span class="partition-type">{{ partition.filesystem }}</span></td>
|
||||
<td class="partition-os">{{ partition.operativeSystem ? partition.operativeSystem.name : '-' }}</td>
|
||||
<td>
|
||||
{% if partition.operativeSystem %}
|
||||
<a href="command+output:/opt/opengnsys/scripts/bootOs {{ partition.diskNumber }} {{ partition.partitionNumber }}"
|
||||
class="partition-boot-btn"
|
||||
role="button">
|
||||
<i class="fas fa-play"></i>
|
||||
Arrancar {{ partition.operativeSystem.name }}
|
||||
</a>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<h2><i class="fas fa-hdd"></i> Almacenamiento del sistema</h2>
|
||||
|
||||
{% if disks is defined and disks|length > 0 %}
|
||||
|
||||
{% for diskNum, data in disks %}
|
||||
<div class="disk-container">
|
||||
|
||||
<div class="disk-header">
|
||||
<h3>
|
||||
<i class="fas fa-server"></i> Disco {{ diskNum }}
|
||||
</h3>
|
||||
{% if data.info %}
|
||||
<span class="disk-total-badge">
|
||||
Total: {{ (data.info.size / 1024 / 1024)|number_format(2) }} GB
|
||||
</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="partitions-table" style="box-shadow: none; border: none; border-radius: 0;">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 15%;">Partición</th>
|
||||
<th style="width: 20%;">Tamaño</th>
|
||||
<th style="width: 15%;">Tipo</th>
|
||||
<th style="width: 30%;">Sistema Operativo</th>
|
||||
<th style="width: 20%;">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for partition in data.parts %}
|
||||
<tr>
|
||||
<td style="text-align: center;">
|
||||
<span class="partition-number">{{ partition.partitionNumber }}</span>
|
||||
</td>
|
||||
|
||||
<td class="partition-size">
|
||||
{{ (partition.size / 1024)|number_format(0) }} MB
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<span class="partition-type">{{ partition.filesystem|default('-') }}</span>
|
||||
</td>
|
||||
|
||||
<td class="partition-os">
|
||||
{{ partition.operativeSystem ? partition.operativeSystem.name : '-' }}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
{% if partition.operativeSystem %}
|
||||
<a href="command+output:/opt/opengnsys/scripts/bootOs {{ partition.diskNumber }} {{ partition.partitionNumber }}"
|
||||
class="partition-boot-btn"
|
||||
role="button">
|
||||
<i class="fas fa-play"></i> Arrancar {{ partition.operativeSystem.name }}
|
||||
</a>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="5" class="empty-disk">
|
||||
No hay particiones utilizables en este disco.
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
{% else %}
|
||||
<p class="no-partitions">No hay particiones disponibles.</p>
|
||||
<p class="no-partitions">No hay discos detectados en el sistema.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
Loading…
Reference in New Issue