feat(vikon): rewrite VikonIntegration from scratch — OAuth + core update

- HttpTask: Laravel Http facade with SSL enabled, retry, timeout
- ValidateTokenTask: token check via auth.db-nica.ru
- RefreshTokenTask: token refresh via db-nica.ru
- FilesystemTask: path traversal protection, blocked extensions (PHP/ASP/etc)
- AuthenticateAction: OAuth2 code→token exchange
- CheckAccessAction: token validation + filesystem writability check
- CheckVersionAction: version comparison against remote API
- UpdateCoreAction: ZIP download, Zip Slip protection, atomic sync with rollback
- VikonController: thin controller, 7 endpoints with Session-based token storage
- Routes: access-check, dashboard.auth, throttle:30,1 middleware
- Vue 3 Composition API frontend with progress bar
- Config: all secrets in .env via config/vikon.php
- vikon_core kept as fallback (not deleted)
This commit is contained in:
F4ilji
2026-07-04 12:53:28 +05:00
parent 82df1210c2
commit f4f8bc8e77
15 changed files with 990 additions and 1 deletions
@@ -0,0 +1,39 @@
<?php
namespace App\Containers\VikonIntegration\Actions\Auth;
use App\Containers\VikonIntegration\Tasks\HttpTask;
class AuthenticateAction
{
public function __construct(
private readonly HttpTask $http,
private readonly string $clientId,
private readonly string $clientSecret,
) {}
/**
* @return array{access_token: string, refresh_token: string}
*/
public function run(string $code, string $redirectUri): array
{
$response = $this->http->post('oauth2/authorize/token', [
'code' => $code,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'redirect_uri' => $redirectUri,
'grant_type' => 'authorization_code',
], 'auth');
$body = $response->json();
if (!isset($body['access_token'], $body['refresh_token'])) {
throw new \RuntimeException('Auth failed: ' . ($body['message'] ?? 'Unknown error'));
}
return [
'access_token' => $body['access_token'],
'refresh_token' => $body['refresh_token'],
];
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Containers\VikonIntegration\Actions;
use App\Containers\VikonIntegration\Tasks\HttpTask;
use App\Containers\VikonIntegration\Tasks\ValidateTokenTask;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
class CheckAccessAction
{
public function __construct(
private readonly ValidateTokenTask $validateToken,
private readonly HttpTask $http,
private readonly string $publicPath,
) {}
public function run(string $accessToken): array
{
if (!$this->validateToken->run($accessToken)) {
return ['has_access' => false, 'error' => 'Токен недействителен. Выполните повторную авторизацию.'];
}
$nonWritable = $this->findNonWritable($this->publicPath);
if (!empty($nonWritable)) {
return [
'has_access' => false,
'error' => 'Нет прав на запись: ' . implode(', ', array_slice($nonWritable, 0, 3)),
];
}
return ['has_access' => true, 'error' => null];
}
private function findNonWritable(string $path, int $depth = 0): array
{
if ($depth > 3 || !is_dir($path)) return [];
if (!is_writable($path)) {
return [str_replace(base_path() . '/', '', $path)];
}
$result = [];
foreach (File::directories($path) as $dir) {
$result = array_merge($result, $this->findNonWritable($dir, $depth + 1));
}
return $result;
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Containers\VikonIntegration\Actions;
use App\Containers\VikonIntegration\Tasks\HttpTask;
use Illuminate\Support\Facades\Log;
class CheckVersionAction
{
public function __construct(
private readonly HttpTask $http,
private readonly string $currentVersion,
) {}
public function run(string $accessToken): array
{
try {
$response = $this->http->getWithToken('pull_updates/getLatestVersion', $accessToken);
$body = $response->json();
$latest = $body['version'] ?? null;
return [
'current_version' => $this->currentVersion,
'latest_version' => $latest,
'has_update' => $latest && version_compare($latest, $this->currentVersion, '>'),
];
} catch (\Throwable $e) {
Log::warning('Version check failed', ['error' => $e->getMessage()]);
return [
'current_version' => $this->currentVersion,
'latest_version' => null,
'has_update' => false,
'error' => 'Не удалось проверить обновления',
];
}
}
}
@@ -0,0 +1,160 @@
<?php
namespace App\Containers\VikonIntegration\Actions;
use App\Containers\VikonIntegration\Tasks\HttpTask;
use App\Containers\VikonIntegration\Tasks\FilesystemTask;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use ZipArchive;
class UpdateCoreAction
{
private const NEW_SUFFIX = '_new';
private const OLD_SUFFIX = '_old';
public function __construct(
private readonly HttpTask $http,
private readonly FilesystemTask $fs,
private readonly array $modulesConfig,
private readonly string $storagePath,
private readonly string $basePath,
) {}
public function run(int $moduleId, string $accessToken): string
{
$config = $this->modulesConfig[$moduleId] ?? throw new \RuntimeException('Неизвестный модуль');
$modulePath = $this->basePath . '/' . $config['path'];
$tempPath = $this->storagePath . '/temp/' . $config['path'];
try {
Log::info('Vikon: downloading module core', ['module' => $moduleId]);
$zipContent = $this->http->downloadWithToken(
'pull_updates/generateEmptyModuleCore/' . $moduleId,
$accessToken
);
if (File::exists($tempPath)) File::deleteDirectory($tempPath);
File::makeDirectory($tempPath, 0755, true, true);
$zipFile = $tempPath . '/module.zip';
file_put_contents($zipFile, $zipContent);
$this->extractZip($zipFile, $tempPath);
$blocked = $this->fs->validateFileTypes($tempPath);
if (!empty($blocked)) {
throw new \RuntimeException(
'Запрещённые файлы: ' . implode(', ', $blocked) . '. Обновление отклонено.'
);
}
$vikonCorePath = $tempPath . '/vikon_core';
if (File::isDirectory($vikonCorePath)) {
File::deleteDirectory($vikonCorePath);
}
File::delete($zipFile);
$this->syncFiles($tempPath, $modulePath);
$this->cleanModule($modulePath, $config['allowed_folders']);
File::put($modulePath . '/.vikon', date('Y-m-d H:i:s'));
File::deleteDirectory($tempPath);
Log::info('Vikon: module updated', ['module' => $config['name']]);
return 'Модуль "' . $config['name'] . '" обновлён.';
} catch (\Throwable $e) {
Log::error('Vikon update failed', ['module' => $moduleId, 'error' => $e->getMessage()]);
$this->rollback($modulePath);
throw new \RuntimeException('Ошибка обновления: ' . $e->getMessage());
}
}
private function extractZip(string $zipPath, string $destination): void
{
$zip = new ZipArchive;
if ($zip->open($zipPath) !== true) {
throw new \RuntimeException('Не удалось открыть ZIP');
}
$realDest = realpath($destination);
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if (str_contains($name, '..')) {
$zip->close();
throw new \RuntimeException("Zip Slip: {$name}");
}
$full = realpath($realDest . '/' . $name);
if ($full !== false && !str_starts_with($full, $realDest)) {
$zip->close();
throw new \RuntimeException("Path escape: {$name}");
}
}
$zip->extractTo($destination);
$zip->close();
}
private function syncFiles(string $source, string $target): void
{
foreach (File::files($source) as $file) {
$name = $file->getFilename();
$targetPath = $target . '/' . $name;
if (File::exists($targetPath)) {
$oldPath = $targetPath . self::OLD_SUFFIX;
File::delete($oldPath);
rename($targetPath, $oldPath);
}
copy($file->getPathname(), $targetPath);
}
foreach (File::directories($source) as $dir) {
$name = basename($dir);
$targetPath = $target . '/' . $name;
if (File::exists($targetPath)) {
$oldPath = $targetPath . self::OLD_SUFFIX;
File::deleteDirectory($oldPath);
File::move($targetPath, $oldPath);
}
File::copyDirectory($dir, $targetPath);
}
}
private function cleanModule(string $modulePath, array $allowed): void
{
foreach (File::directories($modulePath) as $dir) {
$name = basename($dir);
if (!in_array($name, $allowed, true) && !is_link($dir)) {
File::deleteDirectory($dir);
}
}
foreach (File::files($modulePath) as $file) {
$name = $file->getFilename();
if (!in_array($name, $allowed, true) && !in_array($name, ['.vikon', '.htaccess'], true)) {
File::delete($file);
}
}
}
private function rollback(string $modulePath): void
{
foreach (File::directories($modulePath) as $dir) {
$old = $dir . self::OLD_SUFFIX;
if (File::exists($old)) {
File::deleteDirectory($dir);
File::move($old, $dir);
}
}
foreach (File::files($modulePath) as $file) {
$old = $file->getPathname() . self::OLD_SUFFIX;
if (File::exists($old)) {
File::delete($file);
rename($old, $file->getPathname());
}
}
}
}
@@ -0,0 +1,71 @@
<?php
namespace App\Containers\VikonIntegration\Providers;
use App\Containers\VikonIntegration\Actions\Auth\AuthenticateAction;
use App\Containers\VikonIntegration\Actions\CheckAccessAction;
use App\Containers\VikonIntegration\Actions\CheckVersionAction;
use App\Containers\VikonIntegration\Actions\UpdateCoreAction;
use App\Containers\VikonIntegration\Tasks\FilesystemTask;
use App\Containers\VikonIntegration\Tasks\HttpTask;
use App\Containers\VikonIntegration\Tasks\RefreshTokenTask;
use App\Containers\VikonIntegration\Tasks\ValidateTokenTask;
use Illuminate\Support\ServiceProvider;
class VikonServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->mergeConfigFrom(config_path('vikon.php'), 'vikon');
$this->app->singleton(HttpTask::class, fn () => new HttpTask(
apiDomain: config('vikon.api_domain'),
authDomain: config('vikon.auth_domain'),
filemanagerDomain: config('vikon.filemanager_domain'),
timeout: config('vikon.http_timeout', 60),
retries: config('vikon.http_retries', 3),
));
$this->app->singleton(ValidateTokenTask::class, fn ($app) => new ValidateTokenTask(
http: $app->make(HttpTask::class),
));
$this->app->singleton(RefreshTokenTask::class, fn ($app) => new RefreshTokenTask(
http: $app->make(HttpTask::class),
clientId: config('vikon.client_id'),
clientSecret: config('vikon.client_secret'),
));
$this->app->singleton(FilesystemTask::class, fn () => new FilesystemTask);
$this->app->singleton(AuthenticateAction::class, fn ($app) => new AuthenticateAction(
http: $app->make(HttpTask::class),
clientId: config('vikon.client_id'),
clientSecret: config('vikon.client_secret'),
));
$this->app->singleton(CheckAccessAction::class, fn ($app) => new CheckAccessAction(
validateToken: $app->make(ValidateTokenTask::class),
http: $app->make(HttpTask::class),
publicPath: public_path(),
));
$this->app->singleton(CheckVersionAction::class, fn ($app) => new CheckVersionAction(
http: $app->make(HttpTask::class),
currentVersion: config('vikon.current_version', '1.0.0'),
));
$this->app->singleton(UpdateCoreAction::class, fn ($app) => new UpdateCoreAction(
http: $app->make(HttpTask::class),
fs: $app->make(FilesystemTask::class),
modulesConfig: config('vikon.modules'),
storagePath: config('vikon.storage_path'),
basePath: public_path(),
));
}
public function boot(): void
{
$this->loadRoutesFrom(app_path('Containers/VikonIntegration/UI/WEB/Routes/web.php'));
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Containers\VikonIntegration\Tasks;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
class FilesystemTask
{
public function isPathSafe(string $path, string $base): bool
{
$realBase = realpath($base);
if ($realBase === false) return false;
$realPath = realpath($path);
if ($realPath !== false) {
return str_starts_with($realPath, $realBase);
}
$parent = realpath(dirname($path));
return $parent !== false && str_starts_with($parent, $realBase);
}
public function safeRemove(string $path, string $base, bool $recursive = false): bool
{
if (!$this->isPathSafe($path, $base)) {
Log::warning('Path traversal blocked', ['path' => $path, 'base' => $base]);
return false;
}
if (!file_exists($path)) return true;
if (!is_dir($path)) return File::delete($path);
return File::deleteDirectory($path);
}
public function safeMkdir(string $path): bool
{
if (File::isDirectory($path)) return true;
return File::makeDirectory($path, 0755, true, true);
}
public function replaceDirectory(string $source, string $target, string $base): bool
{
if (!$this->isPathSafe($source, $base) || !$this->isPathSafe($target, $base)) {
return false;
}
if (!File::exists($source)) return false;
if (File::exists($target)) return false;
$parent = dirname($target);
if (!is_writable($parent)) return false;
if (!File::makeDirectory($target, 0755, true, true)) return false;
foreach (File::allFiles($source) as $file) {
$relative = ltrim(str_replace($source, '', $file->getPathname()), '/');
$dest = $target . '/' . $relative;
$destDir = dirname($dest);
if (!File::isDirectory($destDir)) {
File::makeDirectory($destDir, 0755, true, true);
}
if (!copy($file->getPathname(), $dest)) return false;
}
return File::deleteDirectory($source);
}
public function validateFileTypes(string $directory): array
{
$blocked = [
'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phps',
'asp', 'aspx', 'jsp', 'jspx', 'cfm',
'pl', 'py', 'rb', 'cgi', 'sh', 'bash', 'bat', 'cmd', 'exe',
'ps1', 'htaccess', 'htpasswd',
];
$found = [];
foreach (File::allFiles($directory) as $file) {
$ext = strtolower($file->getExtension());
if (in_array($ext, $blocked, true)) {
$found[] = str_replace(base_path() . '/', '', $file->getPathname());
}
}
return $found;
}
}
@@ -0,0 +1,77 @@
<?php
namespace App\Containers\VikonIntegration\Tasks;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\PendingRequest;
class HttpTask
{
public function __construct(
private readonly string $apiDomain,
private readonly string $authDomain,
private readonly string $filemanagerDomain,
private readonly int $timeout,
private readonly int $retries,
) {}
public function get(string $endpoint, array $params = [], string $service = 'api'): \Illuminate\Http\Client\Response
{
$url = $this->url($endpoint, $service);
return $this->client()->get($url, $params);
}
public function post(string $endpoint, array $data = [], string $service = 'api'): \Illuminate\Http\Client\Response
{
$url = $this->url($endpoint, $service);
return $this->client()->post($url, $data);
}
public function getWithToken(string $endpoint, string $token, string $service = 'api'): \Illuminate\Http\Client\Response
{
$url = $this->url($endpoint, $service);
return $this->client()
->withToken($token)
->get($url);
}
public function postWithToken(string $endpoint, string $token, array $data = [], string $service = 'api'): \Illuminate\Http\Client\Response
{
$url = $this->url($endpoint, $service);
return $this->client()
->withToken($token)
->post($url, $data);
}
public function downloadWithToken(string $endpoint, string $token, string $service = 'api'): string
{
$url = $this->url($endpoint, $service);
$response = $this->client()
->withToken($token)
->withHeaders(['Accept-Encoding' => 'zip, gzip'])
->get($url);
if ($response->failed()) {
throw new \RuntimeException('Download failed: HTTP ' . $response->status());
}
return $response->body();
}
private function client(): PendingRequest
{
return Http::timeout($this->timeout)
->retry($this->retries, 500)
->withHeaders(['Accept' => 'application/json']);
}
private function url(string $endpoint, string $service): string
{
$base = match ($service) {
'auth' => $this->authDomain,
'filemanager' => $this->filemanagerDomain,
default => $this->apiDomain,
};
return rtrim($base, '/') . '/' . ltrim($endpoint, '/');
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Containers\VikonIntegration\Tasks;
class RefreshTokenTask
{
public function __construct(
private readonly HttpTask $http,
private readonly string $clientId,
private readonly string $clientSecret,
) {}
/**
* @return array{access_token: string, refresh_token: string}
*/
public function run(string $refreshToken): array
{
$response = $this->http->post('oauth2/RefreshToken', [
'refresh_token' => $refreshToken,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'grant_type' => 'refresh_token',
]);
$body = $response->json();
if (!isset($body['access_token'], $body['refresh_token'])) {
throw new \RuntimeException('Token refresh failed: ' . ($body['message'] ?? 'Unknown'));
}
return [
'access_token' => $body['access_token'],
'refresh_token' => $body['refresh_token'],
];
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Containers\VikonIntegration\Tasks;
use Illuminate\Support\Facades\Log;
class ValidateTokenTask
{
public function __construct(
private readonly HttpTask $http,
) {}
public function run(string $accessToken): bool
{
try {
$response = $this->http->getWithToken(
'api/profile_applicant/check_access_token',
$accessToken,
'auth'
);
return $response->successful();
} catch (\Throwable $e) {
Log::warning('Vikon token validation failed', ['error' => $e->getMessage()]);
return false;
}
}
}
@@ -0,0 +1,117 @@
<?php
namespace App\Containers\VikonIntegration\UI\WEB\Controllers;
use App\Containers\VikonIntegration\Actions\Auth\AuthenticateAction;
use App\Containers\VikonIntegration\Actions\CheckAccessAction;
use App\Containers\VikonIntegration\Actions\CheckVersionAction;
use App\Containers\VikonIntegration\Actions\UpdateCoreAction;
use App\Containers\VikonIntegration\Tasks\RefreshTokenTask;
use App\Containers\VikonIntegration\Tasks\ValidateTokenTask;
use App\Containers\VikonIntegration\UI\WEB\Requests\AuthenticateRequest;
use App\Containers\VikonIntegration\UI\WEB\Requests\UpdateModuleRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Session;
class VikonController extends Controller
{
public function __construct(
private readonly AuthenticateAction $auth,
private readonly CheckAccessAction $checkAccess,
private readonly CheckVersionAction $checkVersion,
private readonly UpdateCoreAction $updateCore,
private readonly RefreshTokenTask $refreshToken,
private readonly ValidateTokenTask $validateToken,
) {}
public function index(): \Inertia\Response
{
$token = Session::get('vikon_access_token');
$isAuth = $token ? $this->validateToken->run($token) : false;
return inertia()->render('Dashboard/VikonUpdates/Index', [
'is_authenticated' => $isAuth,
'current_version' => config('vikon.current_version'),
'modules' => config('vikon.modules'),
'vikon_auth_domain' => config('vikon.auth_domain'),
'vikon_client_id' => config('vikon.client_id'),
]);
}
public function authenticate(AuthenticateRequest $request): JsonResponse
{
try {
$tokens = $this->auth->run(
$request->validated('code'),
$request->validated('redirect_uri')
);
Session::put('vikon_access_token', $tokens['access_token']);
Session::put('vikon_refresh_token', $tokens['refresh_token']);
return response()->json(['success' => true]);
} catch (\Throwable $e) {
return response()->json(['success' => false, 'message' => 'Ошибка авторизации'], 422);
}
}
public function refreshToken(): JsonResponse
{
$refreshToken = Session::get('vikon_refresh_token');
if (!$refreshToken) {
return response()->json(['success' => false, 'message' => 'Нет refresh токена'], 401);
}
try {
$tokens = $this->refreshToken->run($refreshToken);
Session::put('vikon_access_token', $tokens['access_token']);
Session::put('vikon_refresh_token', $tokens['refresh_token']);
return response()->json(['success' => true]);
} catch (\Throwable $e) {
Session::forget(['vikon_access_token', 'vikon_refresh_token']);
return response()->json(['success' => false, 'message' => 'Токен истёк'], 401);
}
}
public function checkAccess(): JsonResponse
{
$token = Session::get('vikon_access_token');
if (!$token) {
return response()->json(['success' => false, 'requires_auth' => true], 401);
}
$result = $this->checkAccess->run($token);
return response()->json($result);
}
public function checkVersion(): JsonResponse
{
$token = Session::get('vikon_access_token');
if (!$token) {
return response()->json(['success' => false, 'requires_auth' => true], 401);
}
return response()->json($this->checkVersion->run($token));
}
public function updateModule(UpdateModuleRequest $request): JsonResponse
{
$token = Session::get('vikon_access_token');
if (!$token) {
return response()->json(['success' => false, 'requires_auth' => true], 401);
}
try {
$message = $this->updateCore->run($request->validated('module_id'), $token);
return response()->json(['success' => true, 'message' => $message]);
} catch (\Throwable $e) {
return response()->json(['success' => false, 'message' => 'Ошибка обновления'], 500);
}
}
public function logout(): JsonResponse
{
Session::forget(['vikon_access_token', 'vikon_refresh_token']);
return response()->json(['success' => true]);
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Containers\VikonIntegration\UI\WEB\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AuthenticateRequest extends FormRequest
{
public function authorize(): bool { return auth()->check(); }
public function rules(): array
{
return [
'code' => ['required', 'string', 'max:255'],
'redirect_uri' => ['required', 'url'],
];
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Containers\VikonIntegration\UI\WEB\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateModuleRequest extends FormRequest
{
public function authorize(): bool { return auth()->check(); }
public function rules(): array
{
return [
'module_id' => ['required', 'integer', Rule::in([1, 2, 6])],
];
}
}
@@ -0,0 +1,17 @@
<?php
use App\Containers\VikonIntegration\UI\WEB\Controllers\VikonController;
use Illuminate\Support\Facades\Route;
Route::prefix('/dashboard/vikon-updates')
->name('dashboard.vikon-updates.')
->middleware(['access-check', 'dashboard.auth', 'throttle:30,1'])
->group(function () {
Route::get('/', [VikonController::class, 'index'])->name('index');
Route::post('/authenticate', [VikonController::class, 'authenticate'])->name('authenticate');
Route::post('/refresh-token', [VikonController::class, 'refreshToken'])->name('refresh-token');
Route::post('/check-access', [VikonController::class, 'checkAccess'])->name('check-access');
Route::post('/check-version', [VikonController::class, 'checkVersion'])->name('check-version');
Route::post('/update-module', [VikonController::class, 'updateModule'])->name('update-module');
Route::post('/logout', [VikonController::class, 'logout'])->name('logout');
});
+1 -1
View File
@@ -172,7 +172,7 @@ return [
// App\Providers\Filament\DashboardPanelProvider::class,
App\Providers\RouteServiceProvider::class,
\App\Providers\ForceHttpsServiceProvider::class,
// \App\Containers\VikonIntegration\Providers\VikonServiceProvider::class, // will be re-added
\App\Containers\VikonIntegration\Providers\VikonServiceProvider::class,
])->toArray(),
/*
@@ -0,0 +1,240 @@
<template>
<DashboardLayout>
<template #header-icon>
<DashboardIcon name="arrow-down-tray" size="5" class="text-primary" />
</template>
<template #header-title>Обновления VIKON</template>
<template #header-subtitle>Управление модулями</template>
<FlashMessages />
<!-- Не авторизован -->
<div v-if="!isAuthenticated" class="bg-layer border border-layer-line rounded-lg p-8 text-center">
<DashboardIcon name="shield-exclamation" size="16" class="text-muted-foreground-1 mx-auto mb-4" />
<h3 class="text-lg font-medium mb-2">Требуется авторизация VIKON</h3>
<p class="text-sm text-muted-foreground-1 mb-6">Войдите через систему VIKON для управления обновлениями</p>
<a :href="authUrl" class="inline-flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary-hover">
<DashboardIcon name="arrow-right-on-rectangle" size="5" />
Войти через VIKON
</a>
</div>
<!-- Авторизован -->
<div v-else class="space-y-6">
<!-- Версия + Статус -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div class="bg-layer border border-layer-line rounded-lg p-6">
<div class="flex items-center gap-3 mb-4">
<DashboardIcon name="information-circle" size="6" class="text-primary" />
<div>
<h3 class="text-sm font-medium">Текущая версия</h3>
<p class="text-2xl font-semibold mt-1">{{ currentVersion }}</p>
</div>
</div>
<div v-if="versionInfo.has_update" class="p-3 bg-yellow-50 border border-yellow-200 rounded-lg mt-4">
<p class="text-sm font-medium text-yellow-800">Доступно обновление: {{ versionInfo.latest_version }}</p>
</div>
<div v-else-if="versionInfo.latest_version" class="p-3 bg-green-50 border border-green-200 rounded-lg mt-4">
<p class="text-sm font-medium text-green-800">Установлена последняя версия</p>
</div>
<button @click="checkVersion" :disabled="checkingVersion"
class="mt-4 w-full px-4 py-2 bg-surface border border-layer-line rounded-lg hover:bg-muted-hover disabled:opacity-50">
{{ checkingVersion ? 'Проверка...' : 'Проверить обновления' }}
</button>
</div>
<div class="bg-layer border border-layer-line rounded-lg p-6">
<div class="flex items-center gap-3 mb-4">
<DashboardIcon name="shield-check" size="6" class="text-primary" />
<div>
<h3 class="text-sm font-medium">Статус доступа</h3>
<p class="text-sm text-muted-foreground-1 mt-1">{{ accessInfo.has_access ? 'Доступ разрешён' : 'Доступ запрещён' }}</p>
</div>
</div>
<div v-if="accessInfo.error" class="p-3 bg-red-50 border border-red-200 rounded-lg mt-4">
<p class="text-sm text-red-800">{{ accessInfo.error }}</p>
</div>
<button @click="checkAccess" :disabled="checkingAccess"
class="mt-4 w-full px-4 py-2 bg-surface border border-layer-line rounded-lg hover:bg-muted-hover disabled:opacity-50">
{{ checkingAccess ? 'Проверка...' : 'Проверить права' }}
</button>
</div>
</div>
<!-- Модули -->
<div class="bg-layer border border-layer-line rounded-lg">
<div class="px-6 py-4 border-b border-layer-line">
<h3 class="text-sm font-medium">Модули для обновления</h3>
</div>
<div class="divide-y divide-line-2">
<div v-for="(mod, id) in modules" :key="id" class="px-6 py-4 flex items-center justify-between">
<div class="flex items-center gap-3">
<DashboardIcon name="cube" size="6" class="text-primary" />
<div>
<p class="text-sm font-medium">{{ mod.name }}</p>
<p class="text-xs text-muted-foreground-1">ID: {{ id }}</p>
</div>
</div>
<button @click="updateModule(id)" :disabled="updating || !accessInfo.has_access"
class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover disabled:opacity-50">
{{ updating ? 'Обновление...' : 'Обновить' }}
</button>
</div>
</div>
</div>
<!-- Прогресс -->
<div v-if="updating" class="bg-layer border border-layer-line rounded-lg p-6">
<div class="flex items-center gap-3 mb-3">
<DashboardIcon name="arrow-path" size="5" class="text-primary animate-spin" />
<p class="text-sm font-medium">Обновление...</p>
</div>
<div class="w-full bg-muted rounded-full h-2.5">
<div class="bg-primary h-2.5 rounded-full transition-all" :style="{ width: progress + '%' }"></div>
</div>
<p class="text-xs text-muted-foreground-1 mt-2">{{ progress }}%</p>
</div>
<!-- Ошибка -->
<div v-if="updateError" class="bg-layer border border-red-200 rounded-lg p-6">
<div class="flex items-start gap-3">
<DashboardIcon name="x-circle" size="6" class="text-red-600" />
<div>
<h4 class="text-sm font-medium text-red-800">Ошибка</h4>
<p class="text-sm text-red-700 mt-1">{{ updateError }}</p>
</div>
</div>
</div>
<div class="flex justify-end">
<button @click="logout" class="px-4 py-2 bg-surface border border-layer-line rounded-lg hover:bg-muted-hover">
Выйти из VIKON
</button>
</div>
</div>
</DashboardLayout>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import { router } from '@inertiajs/vue3';
import DashboardLayout from '../Components/DashboardLayout.vue';
import DashboardIcon from '../Components/DashboardIcon.vue';
import FlashMessages from '../Components/shared/FlashMessages.vue';
const props = defineProps({
is_authenticated: Boolean,
current_version: String,
modules: Object,
vikon_auth_domain: String,
vikon_client_id: String,
});
const isAuthenticated = ref(props.is_authenticated);
const currentVersion = ref(props.current_version);
const checkingVersion = ref(false);
const checkingAccess = ref(false);
const updating = ref(false);
const progress = ref(0);
const updateError = ref(null);
const versionInfo = ref({ current_version: props.current_version, has_update: false, latest_version: null });
const accessInfo = ref({ has_access: false, error: null });
const authUrl = computed(() => {
const redirect = encodeURIComponent(route('dashboard.vikon-updates.index'));
return `${props.vikon_auth_domain}oauth2/authorize?client_id=${props.vikon_client_id}&redirect_uri=${redirect}&response_type=code`;
});
onMounted(() => {
const code = new URLSearchParams(window.location.search).get('code');
if (code) {
authenticate(code);
return;
}
if (isAuthenticated.value) {
checkAccess();
checkVersion();
}
});
async function authenticate(code) {
try {
const res = await axios.post(route('dashboard.vikon-updates.authenticate'), {
code,
redirect_uri: window.location.origin + window.location.pathname,
});
if (res.data.success) {
isAuthenticated.value = true;
window.history.replaceState({}, document.title, window.location.pathname);
checkAccess();
checkVersion();
}
} catch (e) {
console.error('Auth failed:', e);
}
}
async function checkAccess() {
checkingAccess.value = true;
try {
const res = await axios.post(route('dashboard.vikon-updates.check-access'));
accessInfo.value = res.data;
} catch (e) {
accessInfo.value = { has_access: false, error: 'Ошибка проверки прав' };
} finally {
checkingAccess.value = false;
}
}
async function checkVersion() {
checkingVersion.value = true;
try {
const res = await axios.post(route('dashboard.vikon-updates.check-version'));
versionInfo.value = res.data;
} catch (e) {
console.error('Version check failed:', e);
} finally {
checkingVersion.value = false;
}
}
async function updateModule(moduleId) {
if (!confirm('Обновить модуль?')) return;
updating.value = true;
progress.value = 0;
updateError.value = null;
const timer = setInterval(() => {
if (progress.value < 90) progress.value += 10;
}, 500);
try {
const res = await axios.post(route('dashboard.vikon-updates.update-module'), { module_id: moduleId });
progress.value = 100;
clearInterval(timer);
if (res.data.success) {
setTimeout(() => router.reload({ preserveState: true }), 500);
} else {
updateError.value = res.data.message;
updating.value = false;
}
} catch (e) {
clearInterval(timer);
updating.value = false;
updateError.value = e.response?.data?.message || 'Ошибка обновления';
}
}
async function logout() {
try {
await axios.post(route('dashboard.vikon-updates.logout'));
isAuthenticated.value = false;
accessInfo.value = { has_access: false, error: null };
versionInfo.value = { current_version: currentVersion.value, has_update: false, latest_version: null };
} catch (e) {
console.error('Logout failed:', e);
}
}
</script>