refactor: replace admin bootstrap script with first-run setup
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
<script lang="ts">
|
||||
import GalleryVerticalEndIcon from '@lucide/svelte/icons/gallery-vertical-end';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { Field as FormField, Control, FieldErrors } from 'formsnap';
|
||||
import * as Field from '$lib/components/ui/field/index.js';
|
||||
import { superForm, type SuperValidated } from 'sveltekit-superforms';
|
||||
import { zod4Client } from 'sveltekit-superforms/adapters';
|
||||
import type { HTMLAttributes } from 'svelte/elements';
|
||||
import { Button } from '$lib/components/ui/button/index.js';
|
||||
import { Input } from '$lib/components/ui/input/index.js';
|
||||
import { cn, type WithElementRef } from '$lib/utils.js';
|
||||
import { firstAdminSchema, type FirstAdminSchema } from '$lib/schemas/auth';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
class: className,
|
||||
form: initialForm,
|
||||
...restProps
|
||||
}: WithElementRef<HTMLAttributes<HTMLDivElement>> & {
|
||||
form: SuperValidated<FirstAdminSchema['_output'], string>;
|
||||
} = $props();
|
||||
|
||||
const id = $props.id();
|
||||
// svelte-ignore state_referenced_locally
|
||||
const firstAdminForm = superForm(initialForm, {
|
||||
validators: zod4Client(firstAdminSchema),
|
||||
resetForm: false,
|
||||
onUpdated: ({ form }) => {
|
||||
if (!form.valid) {
|
||||
toast.error(form.message ?? firstError(form.errors), {
|
||||
id: 'first-admin-error',
|
||||
position: 'top-center'
|
||||
});
|
||||
}
|
||||
},
|
||||
onError: ({ result }) => {
|
||||
toast.error(result.error.message, {
|
||||
id: 'first-admin-error',
|
||||
position: 'top-center'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const { form: formData, enhance } = firstAdminForm;
|
||||
|
||||
function firstError(errors: Record<string, unknown>) {
|
||||
for (const value of Object.values(errors)) {
|
||||
if (Array.isArray(value) && typeof value[0] === 'string') {
|
||||
return value[0];
|
||||
}
|
||||
}
|
||||
|
||||
return 'Check the highlighted fields.';
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class={cn('flex flex-col gap-6', className)} bind:this={ref} {...restProps}>
|
||||
<form method="POST" action="?/bootstrap" use:enhance>
|
||||
<Field.Group>
|
||||
<div class="flex flex-col items-center gap-2 text-center">
|
||||
<div class="flex flex-col items-center gap-2 font-medium">
|
||||
<div
|
||||
class="flex size-9 items-center justify-center rounded-md bg-primary text-primary-foreground"
|
||||
>
|
||||
<GalleryVerticalEndIcon class="size-6" />
|
||||
</div>
|
||||
<span class="sr-only">Clearity</span>
|
||||
</div>
|
||||
<h1 class="text-xl font-bold">Create the first admin</h1>
|
||||
<Field.Description>
|
||||
Set up the initial Better Auth admin account for this workspace.
|
||||
</Field.Description>
|
||||
</div>
|
||||
<FormField form={firstAdminForm} name="name">
|
||||
<Field.Field>
|
||||
<Control id="name-{id}">
|
||||
{#snippet children({ props })}
|
||||
<Field.Label>Name</Field.Label>
|
||||
<Input
|
||||
{...props}
|
||||
autocomplete="name"
|
||||
placeholder="Administrator"
|
||||
bind:value={$formData.name}
|
||||
/>
|
||||
{/snippet}
|
||||
</Control>
|
||||
<Field.Error><FieldErrors /></Field.Error>
|
||||
</Field.Field>
|
||||
</FormField>
|
||||
<FormField form={firstAdminForm} name="email">
|
||||
<Field.Field>
|
||||
<Control id="email-{id}">
|
||||
{#snippet children({ props })}
|
||||
<Field.Label>Email</Field.Label>
|
||||
<Input
|
||||
{...props}
|
||||
type="email"
|
||||
autocomplete="email"
|
||||
placeholder="admin@example.com"
|
||||
bind:value={$formData.email}
|
||||
/>
|
||||
{/snippet}
|
||||
</Control>
|
||||
<Field.Error><FieldErrors /></Field.Error>
|
||||
</Field.Field>
|
||||
</FormField>
|
||||
<FormField form={firstAdminForm} name="password">
|
||||
<Field.Field>
|
||||
<Control id="password-{id}">
|
||||
{#snippet children({ props })}
|
||||
<Field.Label>Password</Field.Label>
|
||||
<Input
|
||||
{...props}
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
bind:value={$formData.password}
|
||||
/>
|
||||
{/snippet}
|
||||
</Control>
|
||||
<Field.Error><FieldErrors /></Field.Error>
|
||||
</Field.Field>
|
||||
</FormField>
|
||||
<Field.Field>
|
||||
<Button type="submit" class="w-full">Create admin</Button>
|
||||
</Field.Field>
|
||||
</Field.Group>
|
||||
</form>
|
||||
<Field.Description class="px-6 text-center">
|
||||
This setup screen disappears once the first user exists.
|
||||
</Field.Description>
|
||||
</div>
|
||||
@@ -5,4 +5,11 @@ export const loginSchema = z.object({
|
||||
password: z.string().min(1, 'Enter your password.')
|
||||
});
|
||||
|
||||
export const firstAdminSchema = z.object({
|
||||
name: z.string().trim().min(1, 'Enter your name.'),
|
||||
email: z.email('Enter a valid email address.').transform((value) => value.toLowerCase()),
|
||||
password: z.string().min(8, 'Password must be at least 8 characters.')
|
||||
});
|
||||
|
||||
export type LoginSchema = typeof loginSchema;
|
||||
export type FirstAdminSchema = typeof firstAdminSchema;
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import { APIError } from 'better-auth/api';
|
||||
import { count } from 'drizzle-orm';
|
||||
import { message, superValidate } from 'sveltekit-superforms/server';
|
||||
import { zod4 } from 'sveltekit-superforms/adapters';
|
||||
import { auth } from '$lib/server/auth';
|
||||
import { loginSchema } from '$lib/schemas/auth';
|
||||
import { db } from '$lib/server/db';
|
||||
import { user } from '$lib/server/db/schema';
|
||||
import { firstAdminSchema, loginSchema } from '$lib/schemas/auth';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
function getSafeRedirect(url: URL) {
|
||||
@@ -21,7 +24,11 @@ export const load: PageServerLoad = async ({ locals, url }) => {
|
||||
redirect(303, getSafeRedirect(url));
|
||||
}
|
||||
|
||||
const [{ total }] = await db.select({ total: count() }).from(user);
|
||||
const needsBootstrap = total === 0;
|
||||
|
||||
return {
|
||||
needsBootstrap,
|
||||
form: await superValidate(
|
||||
{
|
||||
email: url.searchParams.get('email') ?? '',
|
||||
@@ -29,11 +36,65 @@ export const load: PageServerLoad = async ({ locals, url }) => {
|
||||
},
|
||||
zod4(loginSchema),
|
||||
{ id: 'login' }
|
||||
),
|
||||
firstAdminForm: await superValidate(
|
||||
{
|
||||
name: '',
|
||||
email: url.searchParams.get('email') ?? '',
|
||||
password: ''
|
||||
},
|
||||
zod4(firstAdminSchema),
|
||||
{ id: 'first-admin' }
|
||||
)
|
||||
};
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
bootstrap: async (event) => {
|
||||
const form = await superValidate(event, zod4(firstAdminSchema), { id: 'first-admin' });
|
||||
|
||||
if (!form.valid) {
|
||||
return message(form, 'Check the highlighted fields.', { status: 400 });
|
||||
}
|
||||
|
||||
const [{ total }] = await db.select({ total: count() }).from(user);
|
||||
|
||||
if (total > 0) {
|
||||
return message(form, 'The first admin account has already been created.', { status: 409 });
|
||||
}
|
||||
|
||||
try {
|
||||
await auth.api.createUser({
|
||||
body: {
|
||||
name: form.data.name,
|
||||
email: form.data.email,
|
||||
password: form.data.password,
|
||||
role: 'admin'
|
||||
}
|
||||
});
|
||||
|
||||
await auth.api.signInEmail({
|
||||
body: {
|
||||
email: form.data.email,
|
||||
password: form.data.password,
|
||||
callbackURL: getSafeRedirect(event.url)
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof APIError) {
|
||||
return message(form, error.message || 'Unable to create the first admin account.', {
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
|
||||
return message(form, 'Something went wrong while creating the first admin account.', {
|
||||
status: 500
|
||||
});
|
||||
}
|
||||
|
||||
redirect(303, getSafeRedirect(event.url));
|
||||
},
|
||||
|
||||
default: async (event) => {
|
||||
const form = await superValidate(event, zod4(loginSchema), { id: 'login' });
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import FirstAdminForm from '$lib/components/first-admin-form.svelte';
|
||||
import LoginForm from '$lib/components/login-form.svelte';
|
||||
import type { PageData } from './$types';
|
||||
|
||||
@@ -7,6 +8,10 @@
|
||||
|
||||
<div class="flex min-h-svh flex-col items-center justify-center gap-6 bg-background p-6 md:p-10">
|
||||
<div class="w-full max-w-sm">
|
||||
<LoginForm form={data.form} />
|
||||
{#if data.needsBootstrap}
|
||||
<FirstAdminForm form={data.firstAdminForm} />
|
||||
{:else}
|
||||
<LoginForm form={data.form} />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user