This commit is contained in:
Saeed Vaziry
2025-05-19 20:55:32 +02:00
parent cdc012c270
commit 04d52f6742
10 changed files with 333 additions and 21 deletions

View File

@ -5,6 +5,7 @@
use App\Models\SshKey;
use App\Models\User;
use App\ValidationRules\SshKeyRule;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class CreateSshKey
@ -16,6 +17,8 @@ class CreateSshKey
*/
public function create(User $user, array $input): SshKey
{
Validator::make($input, self::rules())->validate();
$key = new SshKey([
'user_id' => $user->id,
'name' => $input['name'],

View File

@ -65,7 +65,6 @@ public function create(Request $request, Project $project, Server $server): SshK
}
if (! $sshKey) {
$this->validate($request, CreateSshKey::rules());
/** @var SshKey $sshKey */
$sshKey = app(CreateSshKey::class)->create($user, $request->all());
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Http\Controllers;
use App\Actions\SshKey\CreateSshKey;
use App\Http\Resources\SshKeyResource;
use App\Models\SshKey;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Spatie\RouteAttributes\Attributes\Delete;
use Spatie\RouteAttributes\Attributes\Get;
use Spatie\RouteAttributes\Attributes\Middleware;
use Spatie\RouteAttributes\Attributes\Post;
use Spatie\RouteAttributes\Attributes\Prefix;
#[Prefix('settings/ssh-keys')]
#[Middleware(['auth'])]
class SSHKeyController extends Controller
{
#[Get('/', name: 'ssh-keys')]
public function index(): Response
{
$this->authorize('viewAny', SshKey::class);
return Inertia::render('ssh-keys/index', [
'sshKeys' => SshKeyResource::collection(user()->sshKeys()->simplePaginate(config('web.pagination_size'))),
]);
}
#[Post('/', name: 'ssh-keys.store')]
public function store(Request $request): RedirectResponse
{
$this->authorize('create', SshKey::class);
app(CreateSshKey::class)->create(user(), $request->input());
return back()->with('success', 'SSH key created.');
}
#[Delete('/{sshKey}', name: 'ssh-keys.destroy')]
public function destroy(SshKey $sshKey): RedirectResponse
{
$this->authorize('delete', $sshKey);
$sshKey->delete();
return back()->with('success', 'SSH key deleted.');
}
}

View File

@ -0,0 +1,18 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
return (
<textarea
data-slot="textarea"
className={cn(
'border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className,
)}
{...props}
/>
);
}
export { Textarea };

View File

@ -1,5 +1,5 @@
import { type BreadcrumbItem, type NavItem } from '@/types';
import { BellIcon, CloudIcon, CodeIcon, DatabaseIcon, ListIcon, UserIcon, UsersIcon } from 'lucide-react';
import { BellIcon, CloudIcon, CodeIcon, DatabaseIcon, KeyIcon, ListIcon, UserIcon, UsersIcon } from 'lucide-react';
import { ReactNode } from 'react';
import Layout from '@/layouts/app/layout';
@ -39,6 +39,11 @@ const sidebarNavItems: NavItem[] = [
href: route('notification-channels'),
icon: BellIcon,
},
{
title: 'SSH Keys',
href: route('ssh-keys'),
icon: KeyIcon,
},
];
export default function SettingsLayout({ children, breadcrumbs }: { children: ReactNode; breadcrumbs?: BreadcrumbItem[] }) {

View File

@ -0,0 +1,79 @@
import { LoaderCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { useForm } from '@inertiajs/react';
import { FormEventHandler, ReactNode, useState } from 'react';
import { Label } from '@/components/ui/label';
import InputError from '@/components/ui/input-error';
import { Form, FormField, FormFields } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
type SshKeyForm = {
name: string;
public_key: string;
};
export default function AddSshKey({ children }: { children: ReactNode }) {
const [open, setOpen] = useState(false);
const form = useForm<Required<SshKeyForm>>({
name: '',
public_key: '',
});
const submit: FormEventHandler = (e) => {
e.preventDefault();
form.post(route('ssh-keys.store'), {
onSuccess: () => {
setOpen(false);
},
});
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>{children}</DialogTrigger>
<DialogContent className="sm:max-w-xl">
<DialogHeader>
<DialogTitle>Add ssh key</DialogTitle>
<DialogDescription className="sr-only">Add new ssh key</DialogDescription>
</DialogHeader>
<Form id="add-ssh-key-form" onSubmit={submit} className="p-4">
<FormFields>
<FormField>
<Label htmlFor="name">Name</Label>
<Input type="text" name="name" id="name" value={form.data.name} onChange={(e) => form.setData('name', e.target.value)} />
<InputError message={form.errors.name} />
</FormField>
<FormField>
<Label htmlFor="key">Public key</Label>
<Textarea name="public_key" id="public_key" value={form.data.public_key} onChange={(e) => form.setData('public_key', e.target.value)} />
<InputError message={form.errors.public_key} />
</FormField>
</FormFields>
</Form>
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="outline">
Cancel
</Button>
</DialogClose>
<Button type="button" onClick={submit} disabled={form.processing}>
{form.processing && <LoaderCircle className="animate-spin" />}
Connect
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@ -0,0 +1,105 @@
import { ColumnDef } from '@tanstack/react-table';
import DateTime from '@/components/date-time';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
import { useForm } from '@inertiajs/react';
import { LoaderCircleIcon, MoreVerticalIcon } from 'lucide-react';
import FormSuccessful from '@/components/form-successful';
import { useState } from 'react';
import { SSHKey } from '@/types/ssh-key';
function Delete({ sshKey }: { sshKey: SSHKey }) {
const [open, setOpen] = useState(false);
const form = useForm();
const submit = () => {
form.delete(route('ssh-keys.destroy', sshKey.id), {
onSuccess: () => {
setOpen(false);
},
});
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<DropdownMenuItem variant="destructive" onSelect={(e) => e.preventDefault()}>
Delete
</DropdownMenuItem>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Delete {sshKey.name}</DialogTitle>
<DialogDescription className="sr-only">Delete ssh key</DialogDescription>
</DialogHeader>
<p className="p-4">Are you sure you want to delete this key?</p>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">Cancel</Button>
</DialogClose>
<Button variant="destructive" disabled={form.processing} onClick={submit}>
{form.processing && <LoaderCircleIcon className="animate-spin" />}
<FormSuccessful successful={form.recentlySuccessful} />
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export const columns: ColumnDef<SSHKey>[] = [
{
accessorKey: 'id',
header: 'ID',
enableColumnFilter: true,
enableSorting: true,
enableHiding: true,
},
{
accessorKey: 'name',
header: 'Name',
enableColumnFilter: true,
enableSorting: true,
},
{
accessorKey: 'created_at',
header: 'Created at',
enableColumnFilter: true,
enableSorting: true,
cell: ({ row }) => {
return <DateTime date={row.original.created_at} />;
},
},
{
id: 'actions',
enableColumnFilter: false,
enableSorting: false,
cell: ({ row }) => {
return (
<div className="flex items-center justify-end">
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreVerticalIcon />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<Delete sshKey={row.original} />
</DropdownMenuContent>
</DropdownMenu>
</div>
);
},
},
];

View File

@ -0,0 +1,38 @@
import SettingsLayout from '@/layouts/settings/layout';
import { Head, usePage } from '@inertiajs/react';
import Container from '@/components/container';
import Heading from '@/components/heading';
import { Button } from '@/components/ui/button';
import { DataTable } from '@/components/data-table';
import React from 'react';
import { SSHKey } from '@/types/ssh-key';
import { columns } from '@/pages/ssh-keys/components/columns';
import AddSshKey from '@/pages/ssh-keys/components/add-ssh-key';
type Page = {
sshKeys: {
data: SSHKey[];
};
};
export default function SshKeys() {
const page = usePage<Page>();
return (
<SettingsLayout>
<Head title="SSH Keys" />
<Container className="max-w-5xl">
<div className="flex items-start justify-between">
<Heading title="SSH Keys" description="Here you can manage all of your ssh keys" />
<div className="flex items-center gap-2">
<AddSshKey>
<Button>Add</Button>
</AddSshKey>
</div>
</div>
<DataTable columns={columns} data={page.props.sshKeys.data} />
</Container>
</SettingsLayout>
);
}

11
resources/js/types/ssh-key.d.ts vendored Normal file
View File

@ -0,0 +1,11 @@
import { User } from '@/types/user';
export interface SSHKey {
id: number;
user?: User;
name: string;
created_at: string;
updated_at: string;
[key: string]: unknown;
}

View File

@ -3,10 +3,8 @@
namespace Tests\Feature;
use App\Models\SshKey;
use App\Web\Pages\Settings\SSHKeys\Index;
use App\Web\Pages\Settings\SSHKeys\Widgets\SshKeysList;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Inertia\Testing\AssertableInertia;
use Tests\TestCase;
class SshKeysTest extends TestCase
@ -17,25 +15,28 @@ public function test_create_ssh_key(): void
{
$this->actingAs($this->user);
Livewire::test(Index::class)
->callAction('add', [
'name' => 'test',
'public_key' => 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSUGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XAt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/EnmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbxNrRFi9wrf+M7Q== test@test.local',
])
->assertSuccessful();
$this->post(route('ssh-keys.store'), [
'name' => 'test',
'public_key' => 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSUGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XAt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/EnmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbxNrRFi9wrf+M7Q== test@test.local',
])
->assertSessionDoesntHaveErrors();
$this->assertDatabaseHas('ssh_keys', [
'name' => 'test',
]);
}
public function test_get_public_keys_list(): void
{
$this->actingAs($this->user);
$key = SshKey::factory()->create([
SshKey::factory()->create([
'user_id' => $this->user->id,
]);
$this->get(Index::getUrl())
$this->get(route('ssh-keys'))
->assertSuccessful()
->assertSee($key->name);
->assertInertia(fn (AssertableInertia $page) => $page->component('ssh-keys/index'));
}
public function test_delete_key(): void
@ -46,9 +47,7 @@ public function test_delete_key(): void
'user_id' => $this->user->id,
]);
Livewire::test(SshKeysList::class)
->callTableAction('delete', $key->id)
->assertSuccessful();
$this->delete(route('ssh-keys.destroy', ['sshKey' => $key->id]));
$this->assertSoftDeleted('ssh_keys', [
'id' => $key->id,
@ -56,6 +55,8 @@ public function test_delete_key(): void
}
/**
* @param array<string, string> $postBody
*
* @dataProvider ssh_key_data_provider
*/
public function test_create_ssh_key_handles_invalid_or_partial_keys(array $postBody, bool $expectedToSucceed): void
@ -69,16 +70,18 @@ public function test_create_ssh_key_handles_invalid_or_partial_keys(array $postB
'public_key' => 'public-key-content',
]);
$response = Livewire::test(Index::class)
->callAction('add', $postBody);
$response = $this->post(route('ssh-keys.store'), $postBody);
if ($expectedToSucceed) {
$response->assertHasNoActionErrors();
$response->assertSessionDoesntHaveErrors();
} else {
$response->assertHasActionErrors();
$response->assertSessionHasErrors();
}
}
/**
* @return array<array{0: array<string, string>, 1: bool}>
*/
public static function ssh_key_data_provider(): array
{
return [