mirror of
https://github.com/vitodeploy/vito.git
synced 2025-07-02 14:36:17 +00:00
Export and Import vito settings (#606)
* Export and Import vito settings * fix tests
This commit is contained in:
131
app/Http/Controllers/VitoSettingController.php
Normal file
131
app/Http/Controllers/VitoSettingController.php
Normal file
@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Exception;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Spatie\RouteAttributes\Attributes\Get;
|
||||
use Spatie\RouteAttributes\Attributes\Middleware;
|
||||
use Spatie\RouteAttributes\Attributes\Post;
|
||||
use Spatie\RouteAttributes\Attributes\Prefix;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use ZipArchive;
|
||||
|
||||
#[Prefix('vito')]
|
||||
#[Middleware(['auth', 'must-be-admin'])]
|
||||
class VitoSettingController extends Controller
|
||||
{
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected array $paths = [
|
||||
'storage/database.sqlite' => 'file',
|
||||
'.env' => 'file',
|
||||
'storage/ssh-public.key' => 'file',
|
||||
'storage/ssh-private.pem' => 'file',
|
||||
'storage/app/key-pairs' => 'directory',
|
||||
'storage/app/server-logs' => 'directory',
|
||||
];
|
||||
|
||||
#[Get('/', name: 'vito-settings')]
|
||||
public function index(): Response
|
||||
{
|
||||
return Inertia::render('vito-settings/index');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
#[Get('/export', name: 'vito-settings.export')]
|
||||
public function downloadExport(): BinaryFileResponse
|
||||
{
|
||||
$exportName = 'vito-backup-'.date('Y-m-d').'.zip';
|
||||
$export = $this->export($exportName);
|
||||
|
||||
return response()->download($export, $exportName)->deleteFileAfterSend();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
private function export(string $zipFileName): string
|
||||
{
|
||||
$zipPath = Storage::disk('tmp')->path($zipFileName);
|
||||
|
||||
$zip = new ZipArchive;
|
||||
if ($zip->open($zipPath, ZipArchive::CREATE) !== true) {
|
||||
throw new Exception('Could not create zip file at '.$zipPath);
|
||||
}
|
||||
|
||||
foreach ($this->paths as $path => $type) {
|
||||
$path = base_path($path);
|
||||
if ($type === 'file' && File::exists($path)) {
|
||||
$zip->addFile($path, basename($path));
|
||||
} elseif ($type === 'directory' && File::exists($path)) {
|
||||
$this->addDirectoryToZip($zip, $path, basename($path));
|
||||
}
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
return $zipPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ValidationException
|
||||
* @throws Exception
|
||||
*/
|
||||
#[Post('/import', name: 'vito-settings.import')]
|
||||
public function import(Request $request): RedirectResponse
|
||||
{
|
||||
// set session driver to file
|
||||
config(['session.driver' => 'file']);
|
||||
|
||||
$request->validate([
|
||||
'backup_file' => 'required|file|mimes:zip',
|
||||
]);
|
||||
|
||||
$uploadedFile = $request->file('backup_file');
|
||||
$extractName = 'vito-backup-import-'.time();
|
||||
$extractPath = Storage::disk('tmp')->path($extractName);
|
||||
|
||||
// Create extraction directory
|
||||
File::makeDirectory($extractPath, 0755, true);
|
||||
|
||||
$zip = new ZipArchive;
|
||||
if ($zip->open($uploadedFile->getPathname()) !== true) {
|
||||
throw ValidationException::withMessages(['file' => 'The uploaded file is not a valid zip archive.']);
|
||||
}
|
||||
|
||||
// Extract files
|
||||
$zip->extractTo($extractPath);
|
||||
$zip->close();
|
||||
|
||||
// Replace files
|
||||
File::move($extractPath.'/database.sqlite', storage_path('database.sqlite'));
|
||||
File::copy($extractPath.'/.env', base_path('.env'));
|
||||
File::move($extractPath.'/ssh-public.key', storage_path('ssh-public.key'));
|
||||
File::move($extractPath.'/ssh-private.pem', storage_path('ssh-private.pem'));
|
||||
File::moveDirectory($extractPath.'/key-pairs', storage_path('app/key-pairs'));
|
||||
File::moveDirectory($extractPath.'/server-logs', storage_path('app/server-logs'));
|
||||
|
||||
return redirect()->route('vito-settings')
|
||||
->with('success', 'Settings imported successfully.');
|
||||
}
|
||||
|
||||
private function addDirectoryToZip(ZipArchive $zip, string $path, string $zipPath): void
|
||||
{
|
||||
$files = File::allFiles($path);
|
||||
|
||||
foreach ($files as $file) {
|
||||
$relativePath = $zipPath.'/'.$file->getRelativePathname();
|
||||
$zip->addFile($file->getRealPath(), $relativePath);
|
||||
}
|
||||
}
|
||||
}
|
@ -69,5 +69,6 @@ class Kernel extends HttpKernel
|
||||
'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,
|
||||
'has-project' => \App\Http\Middleware\HasProjectMiddleware::class,
|
||||
'can-see-project' => \App\Http\Middleware\CanSeeProjectMiddleware::class,
|
||||
'must-be-admin' => \App\Http\Middleware\MustBeAdminMiddleware::class,
|
||||
];
|
||||
}
|
||||
|
18
app/Http/Middleware/MustBeAdminMiddleware.php
Normal file
18
app/Http/Middleware/MustBeAdminMiddleware.php
Normal file
@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class MustBeAdminMiddleware
|
||||
{
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if (! user()->isAdmin()) {
|
||||
abort(403, 'You must be an admin to perform this action.');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
import { SVGAttributes } from 'react';
|
||||
import { Ref, SVGAttributes } from 'react';
|
||||
|
||||
export default function AppLogoIcon(props: SVGAttributes<SVGElement>) {
|
||||
export default function AppLogoIcon(props: SVGAttributes<SVGElement> & { ref?: Ref<SVGSVGElement> }) {
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="1024" height="1024" rx="50" fill="#312E81" />
|
||||
|
@ -26,4 +26,8 @@ function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-footer" className={cn('flex items-center border-t p-4', className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
|
||||
function CardRow({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
return <div data-slot="card-row" className={cn('flex min-h-20 items-center justify-between p-4', className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent, CardRow };
|
||||
|
10
resources/js/icons/vito.tsx
Normal file
10
resources/js/icons/vito.tsx
Normal file
@ -0,0 +1,10 @@
|
||||
import React from 'react';
|
||||
import { LucideProps } from 'lucide-react';
|
||||
import AppLogoIcon from '@/components/app-logo-icon';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export const VitoIcon = React.forwardRef<SVGSVGElement, LucideProps>(({ color = 'currentColor', strokeWidth = 30, className, ...rest }, ref) => {
|
||||
return <AppLogoIcon ref={ref} color={color} className={cn(className, 'rounded-xs')} strokeWidth={strokeWidth} {...rest} />;
|
||||
});
|
||||
|
||||
export default VitoIcon;
|
@ -2,6 +2,7 @@ import { type BreadcrumbItem, type NavItem } from '@/types';
|
||||
import { BellIcon, CloudIcon, CodeIcon, DatabaseIcon, KeyIcon, ListIcon, PlugIcon, TagIcon, UserIcon, UsersIcon } from 'lucide-react';
|
||||
import { ReactNode } from 'react';
|
||||
import Layout from '@/layouts/app/layout';
|
||||
import VitoIcon from '@/icons/vito';
|
||||
|
||||
const sidebarNavItems: NavItem[] = [
|
||||
{
|
||||
@ -54,6 +55,11 @@ const sidebarNavItems: NavItem[] = [
|
||||
href: route('api-keys'),
|
||||
icon: PlugIcon,
|
||||
},
|
||||
{
|
||||
title: 'Vito Settings',
|
||||
href: route('vito-settings'),
|
||||
icon: VitoIcon,
|
||||
},
|
||||
];
|
||||
|
||||
export default function SettingsLayout({ children, breadcrumbs }: { children: ReactNode; breadcrumbs?: BreadcrumbItem[] }) {
|
||||
|
15
resources/js/pages/vito-settings/components/export.tsx
Normal file
15
resources/js/pages/vito-settings/components/export.tsx
Normal file
@ -0,0 +1,15 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DownloadIcon } from 'lucide-react';
|
||||
|
||||
export default function ExportVito() {
|
||||
const submit = () => {
|
||||
window.open(route('vito-settings.export'), '_blank');
|
||||
};
|
||||
|
||||
return (
|
||||
<Button onClick={submit}>
|
||||
<DownloadIcon />
|
||||
Export
|
||||
</Button>
|
||||
);
|
||||
}
|
70
resources/js/pages/vito-settings/components/import.tsx
Normal file
70
resources/js/pages/vito-settings/components/import.tsx
Normal file
@ -0,0 +1,70 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { LoaderCircleIcon, UploadIcon } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Form, FormField, FormFields } from '@/components/ui/form';
|
||||
import { FormEvent } from 'react';
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import InputError from '@/components/ui/input-error';
|
||||
|
||||
export default function ImportVito() {
|
||||
const form = useForm({
|
||||
backup_file: null as File | null,
|
||||
});
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
form.post(route('vito-settings.import'));
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline">
|
||||
<UploadIcon />
|
||||
Import
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Import</DialogTitle>
|
||||
<DialogDescription className="sr-only">Import settings to Vito</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Form id="import-vito-form" className="p-4" onSubmit={submit}>
|
||||
<FormFields>
|
||||
<FormField>
|
||||
<Label htmlFor="backup_file">Backup file</Label>
|
||||
<Input
|
||||
type="file"
|
||||
id="backup_file"
|
||||
name="backup_file"
|
||||
accept=".zip"
|
||||
onChange={(e) => form.setData('backup_file', e.target.files?.[0] || null)}
|
||||
/>
|
||||
<InputError message={form.errors.backup_file} />
|
||||
</FormField>
|
||||
</FormFields>
|
||||
</Form>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button variant="outline">Cancel</Button>
|
||||
</DialogClose>
|
||||
<Button form="import-vito-form" disabled={form.processing}>
|
||||
{form.processing && <LoaderCircleIcon className="animate-spin" />}
|
||||
Import
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
37
resources/js/pages/vito-settings/index.tsx
Normal file
37
resources/js/pages/vito-settings/index.tsx
Normal file
@ -0,0 +1,37 @@
|
||||
import SettingsLayout from '@/layouts/settings/layout';
|
||||
import { Head } from '@inertiajs/react';
|
||||
import Container from '@/components/container';
|
||||
import Heading from '@/components/heading';
|
||||
import { Card, CardContent, CardRow } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import React from 'react';
|
||||
import ExportVito from '@/pages/vito-settings/components/export';
|
||||
import ImportVito from '@/pages/vito-settings/components/import';
|
||||
|
||||
export default function Users() {
|
||||
return (
|
||||
<SettingsLayout>
|
||||
<Head title="Vito Settings" />
|
||||
|
||||
<Container className="max-w-5xl">
|
||||
<div className="flex items-start justify-between">
|
||||
<Heading title="Vito Settings" description="Here you can manage general Vito settings" />
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<CardRow>
|
||||
<span>Export all data</span>
|
||||
<ExportVito />
|
||||
</CardRow>
|
||||
<Separator />
|
||||
<CardRow>
|
||||
<span>Import</span>
|
||||
<ImportVito />
|
||||
</CardRow>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Container>
|
||||
</SettingsLayout>
|
||||
);
|
||||
}
|
19
tests/Feature/VitoSettingsTest.php
Normal file
19
tests/Feature/VitoSettingsTest.php
Normal file
@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace Feature;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class VitoSettingsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_export_settings(): void
|
||||
{
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$this->get(route('vito-settings.export'))
|
||||
->assertDownload('vito-backup-'.date('Y-m-d').'.zip');
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user