mirror of
https://github.com/bartvdbraak/omnidash.git
synced 2025-04-27 15:31:21 +00:00
feat: wip auth rework
This commit is contained in:
parent
f6c274b3cc
commit
82910e97e9
5 changed files with 270 additions and 230 deletions
|
@ -1,15 +1,44 @@
|
|||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { Icons } from '$lib/components/site/icons';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import { Label } from '$lib/components/ui/label';
|
||||
import * as Alert from '$lib/components/ui/alert';
|
||||
import { cn } from '$lib/utils';
|
||||
import type { ActionData } from '../$types';
|
||||
<script lang="ts" context="module">
|
||||
import { z } from 'zod';
|
||||
export const loginFormSchema = z.object({
|
||||
usernameEmail: z.string(),
|
||||
password: z.string()
|
||||
});
|
||||
export type LoginFormSchema = typeof loginFormSchema;
|
||||
</script>
|
||||
|
||||
export let form: ActionData;
|
||||
export let isLoading = false;
|
||||
<script lang="ts">
|
||||
import * as Form from '$lib/components/ui/form';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import { type SuperValidated, type Infer, superForm } from 'sveltekit-superforms';
|
||||
import SuperDebug from 'sveltekit-superforms';
|
||||
import { zodClient } from 'sveltekit-superforms/adapters';
|
||||
import { browser, dev } from '$app/environment';
|
||||
import { PUBLIC_DEBUG_FORMS } from '$env/static/public';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { Icons } from '$lib/components/site';
|
||||
import { cn } from '$lib/utils';
|
||||
|
||||
export let data: SuperValidated<Infer<LoginFormSchema>>;
|
||||
let isLoading = false;
|
||||
|
||||
const form = superForm(data, {
|
||||
validators: zodClient(loginFormSchema),
|
||||
onSubmit: () => {
|
||||
isLoading = true;
|
||||
toast.loading('Logging in...');
|
||||
},
|
||||
onUpdated: ({ form: f }) => {
|
||||
isLoading = false;
|
||||
if (f.valid) {
|
||||
toast.success('Succesfully logged in.');
|
||||
} else {
|
||||
toast.error('Please fix the errors.');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const { form: formData, enhance } = form;
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col space-y-2 text-center">
|
||||
|
@ -19,45 +48,32 @@
|
|||
</p>
|
||||
</div>
|
||||
<div class={cn('grid gap-6')} {...$$restProps}>
|
||||
<form
|
||||
method="POST"
|
||||
action="?/login"
|
||||
use:enhance={() => {
|
||||
isLoading = true;
|
||||
return async ({ update }) => {
|
||||
isLoading = false;
|
||||
update();
|
||||
};
|
||||
}}
|
||||
>
|
||||
<div class="grid gap-2">
|
||||
<div class="grid gap-2">
|
||||
<Label for="emailUsername">Email or username</Label>
|
||||
<Input
|
||||
id="emailUsername"
|
||||
name="emailUsername"
|
||||
type="text"
|
||||
autocapitalize="none"
|
||||
autocomplete="email"
|
||||
autocorrect="off"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
<div class="grid gap-2">
|
||||
<Label for="password">Password</Label>
|
||||
<Input id="password" name="password" type="password" disabled={isLoading} />
|
||||
</div>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{#if isLoading}
|
||||
<Icons.spinner class="mr-2 h-4 w-4 animate-spin" />
|
||||
{/if}
|
||||
Sign In
|
||||
</Button>
|
||||
</div>
|
||||
{#if form?.notVerified}
|
||||
<Alert.Root class="mt-4">
|
||||
<Alert.Description>You must verify your email before you can log in.</Alert.Description>
|
||||
</Alert.Root>
|
||||
{/if}
|
||||
<form method="POST" action="?/login" class="grid gap-2" use:enhance>
|
||||
<Form.Field {form} name="usernameEmail" class="grid gap-2">
|
||||
<Form.Control let:attrs>
|
||||
<Form.Label>Username or email</Form.Label>
|
||||
<Input {...attrs} bind:value={$formData.usernameEmail} />
|
||||
</Form.Control>
|
||||
<Form.FieldErrors />
|
||||
</Form.Field>
|
||||
<Form.Field {form} name="password" class="grid gap-2">
|
||||
<Form.Control let:attrs>
|
||||
<Form.Label>Password</Form.Label>
|
||||
<Input {...attrs} bind:value={$formData.password} type="password" />
|
||||
</Form.Control>
|
||||
<Form.FieldErrors />
|
||||
</Form.Field>
|
||||
<Form.Button disabled={isLoading}>
|
||||
{#if isLoading}
|
||||
<Icons.spinner class="mr-2 h-4 w-4 animate-spin" />
|
||||
{/if}
|
||||
Log in
|
||||
</Form.Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{#if dev && PUBLIC_DEBUG_FORMS == 'true' && browser}
|
||||
<div class="pt-4">
|
||||
<SuperDebug data={$formData} />
|
||||
</div>
|
||||
{/if}
|
||||
|
|
|
@ -1,11 +1,46 @@
|
|||
<script lang="ts" context="module">
|
||||
import { z } from 'zod';
|
||||
export const registerFormSchema = z.object({
|
||||
username: z.string().min(3).max(24),
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
passwordConfirm: z.string().min(8)
|
||||
});
|
||||
export type RegisterFormSchema = typeof registerFormSchema;
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { Icons } from '$lib/components/site/icons';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import * as Form from '$lib/components/ui/form';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import { Label } from '$lib/components/ui/label';
|
||||
import { type SuperValidated, type Infer, superForm } from 'sveltekit-superforms';
|
||||
import SuperDebug from 'sveltekit-superforms';
|
||||
import { zodClient } from 'sveltekit-superforms/adapters';
|
||||
import { browser, dev } from '$app/environment';
|
||||
import { PUBLIC_DEBUG_FORMS } from '$env/static/public';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { Icons } from '$lib/components/site';
|
||||
import { cn } from '$lib/utils';
|
||||
export let isLoading = false;
|
||||
|
||||
export let data: SuperValidated<Infer<RegisterFormSchema>>;
|
||||
let isLoading = false;
|
||||
|
||||
const form = superForm(data, {
|
||||
validators: zodClient(registerFormSchema),
|
||||
onSubmit: () => {
|
||||
isLoading = true;
|
||||
toast.loading('Creating account...');
|
||||
},
|
||||
onUpdated: ({ form: f }) => {
|
||||
isLoading = false;
|
||||
if (f.valid) {
|
||||
toast.success('Account created succesfully.');
|
||||
} else {
|
||||
toast.error('Please fix the errors.');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const { form: formData, enhance } = form;
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col space-y-2 text-center">
|
||||
|
@ -13,48 +48,46 @@
|
|||
<p class="pb-6 text-sm text-muted-foreground">Enter your details below to create a new account</p>
|
||||
</div>
|
||||
<div class={cn('grid gap-6')} {...$$restProps}>
|
||||
<form
|
||||
method="POST"
|
||||
action="?/register"
|
||||
use:enhance={() => {
|
||||
isLoading = true;
|
||||
return async ({ update }) => {
|
||||
isLoading = false;
|
||||
update();
|
||||
};
|
||||
}}
|
||||
>
|
||||
<div class="grid gap-2">
|
||||
<div class="grid gap-2">
|
||||
<Label for="email">Name</Label>
|
||||
<Input id="name" name="name" type="name" disabled={isLoading} />
|
||||
</div>
|
||||
<div class="grid gap-2">
|
||||
<Label for="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autocapitalize="none"
|
||||
autocomplete="email"
|
||||
autocorrect="off"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
<div class="grid gap-2">
|
||||
<Label for="password">Password</Label>
|
||||
<Input id="password" name="password" type="password" disabled={isLoading} />
|
||||
</div>
|
||||
<div class="grid gap-2">
|
||||
<Label for="passwordConfirm">Confirm password</Label>
|
||||
<Input id="passwordConfirm" name="passwordConfirm" type="password" disabled={isLoading} />
|
||||
</div>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
{#if isLoading}
|
||||
<Icons.spinner class="mr-2 h-4 w-4 animate-spin" />
|
||||
{/if}
|
||||
Register
|
||||
</Button>
|
||||
</div>
|
||||
<form method="POST" action="?/register" class="grid gap-2" use:enhance>
|
||||
<Form.Field {form} name="email" class="grid gap-2">
|
||||
<Form.Control let:attrs>
|
||||
<Form.Label>Email</Form.Label>
|
||||
<Input {...attrs} bind:value={$formData.email} />
|
||||
</Form.Control>
|
||||
<Form.FieldErrors />
|
||||
</Form.Field>
|
||||
<Form.Field {form} name="username" class="grid gap-2">
|
||||
<Form.Control let:attrs>
|
||||
<Form.Label>Username</Form.Label>
|
||||
<Input {...attrs} bind:value={$formData.username} />
|
||||
</Form.Control>
|
||||
<Form.FieldErrors />
|
||||
</Form.Field>
|
||||
<Form.Field {form} name="password" class="grid gap-2">
|
||||
<Form.Control let:attrs>
|
||||
<Form.Label>Password</Form.Label>
|
||||
<Input {...attrs} bind:value={$formData.password} type="password" />
|
||||
</Form.Control>
|
||||
<Form.FieldErrors />
|
||||
</Form.Field>
|
||||
<Form.Field {form} name="passwordConfirm" class="grid gap-2">
|
||||
<Form.Control let:attrs>
|
||||
<Form.Label>Confirm password</Form.Label>
|
||||
<Input {...attrs} bind:value={$formData.passwordConfirm} type="password" />
|
||||
</Form.Control>
|
||||
<Form.FieldErrors />
|
||||
</Form.Field>
|
||||
<Form.Button disabled={isLoading}>
|
||||
{#if isLoading}
|
||||
<Icons.spinner class="mr-2 h-4 w-4 animate-spin" />
|
||||
{/if}
|
||||
Log in
|
||||
</Form.Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{#if dev && PUBLIC_DEBUG_FORMS == 'true' && browser}
|
||||
<div class="pt-4">
|
||||
<SuperDebug data={$formData} />
|
||||
</div>
|
||||
{/if}
|
||||
|
|
|
@ -1,14 +1,49 @@
|
|||
<script lang="ts" context="module">
|
||||
import { z } from 'zod';
|
||||
export const ssoFormSchema = z.object({
|
||||
token: z.string()
|
||||
});
|
||||
export type SsoFormSchema = typeof ssoFormSchema;
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import * as Form from '$lib/components/ui/form';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import { type SuperValidated, type Infer, superForm } from 'sveltekit-superforms';
|
||||
import SuperDebug from 'sveltekit-superforms';
|
||||
import { zodClient } from 'sveltekit-superforms/adapters';
|
||||
import { browser, dev } from '$app/environment';
|
||||
import { PUBLIC_DEBUG_FORMS } from '$env/static/public';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { Icons } from '$lib/components/site';
|
||||
import { cn } from '$lib/utils';
|
||||
import PocketBase from 'pocketbase';
|
||||
import { PUBLIC_CLIENT_PB } from '$env/static/public';
|
||||
import { enhance } from '$app/forms';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Separator } from '$lib/components/ui/separator';
|
||||
import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
|
||||
import { ChevronDown } from 'radix-icons-svelte';
|
||||
|
||||
export let isLoading = false;
|
||||
export let data: SuperValidated<Infer<SsoFormSchema>>;
|
||||
let isLoading = false;
|
||||
|
||||
const form = superForm(data, {
|
||||
validators: zodClient(ssoFormSchema),
|
||||
onSubmit: () => {
|
||||
isLoading = true;
|
||||
toast.loading('Logging in...');
|
||||
},
|
||||
onUpdated: ({ form: f }) => {
|
||||
isLoading = false;
|
||||
if (f.valid) {
|
||||
toast.success('Succesfully logged in.');
|
||||
} else {
|
||||
toast.error('Please fix the errors.');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const { form: formData, enhance } = form;
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
export let providers: { name: string; icon?: any; displayName: string }[];
|
||||
|
@ -31,26 +66,14 @@
|
|||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
method="POST"
|
||||
action="?/oauth2"
|
||||
bind:this={oauth2Form}
|
||||
use:enhance={() => {
|
||||
isLoading = true;
|
||||
return async ({ update }) => {
|
||||
isLoading = false;
|
||||
update();
|
||||
};
|
||||
}}
|
||||
>
|
||||
<div class="relative">
|
||||
<div class="absolute inset-0 flex items-center">
|
||||
<span class="w-full border-t" />
|
||||
</div>
|
||||
<div class="relative flex justify-center text-xs uppercase">
|
||||
<span class="bg-background px-2 py-4 text-muted-foreground"> Or continue with </span>
|
||||
</div>
|
||||
</div>
|
||||
<form method="POST" action="?/sso" class="grid gap-2" use:enhance>
|
||||
<Form.Field {form} name="token" class="grid gap-2">
|
||||
<Form.Control let:attrs>
|
||||
<Input {...attrs} bind:value={$formData.token} class="hidden" />
|
||||
</Form.Control>
|
||||
<Form.FieldErrors />
|
||||
</Form.Field>
|
||||
|
||||
<div
|
||||
class="flex items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50"
|
||||
>
|
||||
|
@ -115,3 +138,9 @@
|
|||
{/if}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{#if dev && PUBLIC_DEBUG_FORMS == 'true' && browser}
|
||||
<div class="pt-4">
|
||||
<SuperDebug data={$formData} />
|
||||
</div>
|
||||
{/if}
|
||||
|
|
|
@ -1,118 +1,79 @@
|
|||
import { error, redirect, type Cookies } from '@sveltejs/kit';
|
||||
import type { Actions } from './$types';
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { superValidate } from 'sveltekit-superforms';
|
||||
import { zod } from 'sveltekit-superforms/adapters';
|
||||
import { loginFormSchema } from './(components)/login-form.svelte';
|
||||
import { registerFormSchema } from './(components)/register-form.svelte';
|
||||
import { ssoFormSchema } from './(components)/sso-form.svelte';
|
||||
import { fail, type Actions, redirect } from '@sveltejs/kit';
|
||||
|
||||
export const actions = {
|
||||
login: async ({
|
||||
request,
|
||||
locals,
|
||||
cookies
|
||||
}: {
|
||||
request: Request;
|
||||
locals: App.Locals;
|
||||
cookies: Cookies;
|
||||
}) => {
|
||||
const body = Object.fromEntries(await request.formData());
|
||||
export const load: PageServerLoad = async () => {
|
||||
return {
|
||||
loginForm: await superValidate(zod(loginFormSchema)),
|
||||
registerForm: await superValidate(zod(registerFormSchema)),
|
||||
ssoForm: await superValidate(zod(ssoFormSchema))
|
||||
};
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
login: async ({ request, locals, cookies }) => {
|
||||
const form = await superValidate(request, zod(loginFormSchema));
|
||||
if (!form.valid) {
|
||||
return fail(400, {
|
||||
form
|
||||
});
|
||||
}
|
||||
try {
|
||||
const emailUsername = body.emailUsername.toString();
|
||||
const password = body.password.toString();
|
||||
await locals.pocketBase.collection('users').authWithPassword(emailUsername, password);
|
||||
if (!locals.pocketBase?.authStore?.model?.verified) {
|
||||
locals.pocketBase.authStore.clear();
|
||||
return {
|
||||
notVerified: true
|
||||
};
|
||||
}
|
||||
await locals.pocketBase
|
||||
.collection('users')
|
||||
.authWithPassword(form.data.usernameEmail, form.data.password);
|
||||
} catch (err) {
|
||||
console.log('Error: ', err);
|
||||
throw error(500, 'Something went wrong logging in');
|
||||
return fail(500, {
|
||||
form
|
||||
});
|
||||
}
|
||||
cookies.set('pb_auth', JSON.stringify({ token: locals.pocketBase.authStore.token }), {
|
||||
path: '/'
|
||||
});
|
||||
|
||||
throw redirect(303, '/');
|
||||
},
|
||||
register: async ({ request, locals }: { request: Request; locals: App.Locals }) => {
|
||||
if (locals.pocketBase.authStore.isValid) {
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = await request.formData();
|
||||
|
||||
const name = formData.get('name');
|
||||
const email = formData.get('email');
|
||||
const password = formData.get('password');
|
||||
const passwordConfirm = formData.get('passwordConfirm');
|
||||
|
||||
try {
|
||||
if (typeof name !== 'string') {
|
||||
throw new Error('Name must be a string');
|
||||
}
|
||||
|
||||
if (name.length === 0) {
|
||||
throw new Error('Please enter a valid name');
|
||||
}
|
||||
|
||||
if (typeof email !== 'string') {
|
||||
throw new Error('Email must be a string');
|
||||
}
|
||||
|
||||
if (email.length < 5) {
|
||||
throw new Error('Please enter a valid e-mail address');
|
||||
}
|
||||
|
||||
if (typeof password !== 'string') {
|
||||
throw new Error('Password must be a string');
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
throw new Error('Password must be at least 8 characters in length');
|
||||
}
|
||||
|
||||
if (password !== passwordConfirm) {
|
||||
throw new Error('Passwords do not match');
|
||||
}
|
||||
|
||||
await locals.pocketBase.collection('users').create({
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
passwordConfirm
|
||||
register: async ({ request, locals }) => {
|
||||
const form = await superValidate(request, zod(registerFormSchema));
|
||||
if (!form.valid) {
|
||||
return fail(400, {
|
||||
form
|
||||
});
|
||||
}
|
||||
try {
|
||||
await locals.pocketBase.collection('users').create(form.data);
|
||||
return {
|
||||
form
|
||||
};
|
||||
} catch (err) {
|
||||
return fail(500, {
|
||||
form
|
||||
});
|
||||
|
||||
await locals.pocketBase.collection('users').authWithPassword(email, password);
|
||||
if (!locals.pocketBase?.authStore?.model?.verified) {
|
||||
locals.pocketBase.authStore.clear();
|
||||
return {
|
||||
showLogin: true,
|
||||
isLoading: false,
|
||||
notVerified: true
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
if (!(error instanceof Error)) {
|
||||
return {
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
error: 'Unknown error occured when signing up user'
|
||||
};
|
||||
}
|
||||
|
||||
return { error: error.message, name, email, password };
|
||||
}
|
||||
|
||||
throw redirect(303, '/');
|
||||
},
|
||||
oauth2: async ({ request, cookies }) => {
|
||||
const form = await request.formData();
|
||||
const token = form.get('token');
|
||||
if (!token || typeof token !== 'string') {
|
||||
throw redirect(303, '/auth');
|
||||
sso: async ({ request, cookies }) => {
|
||||
const form = await superValidate(request, zod(ssoFormSchema));
|
||||
if (!form.valid) {
|
||||
return fail(400, {
|
||||
form
|
||||
});
|
||||
}
|
||||
const token = form.data.token;
|
||||
try {
|
||||
if (!token || typeof token !== 'string') {
|
||||
throw redirect(303, '/auth');
|
||||
}
|
||||
cookies.set('pb_auth', JSON.stringify({ token: token }), { path: '/' });
|
||||
return {
|
||||
form
|
||||
};
|
||||
} catch (err) {
|
||||
return fail(500, {
|
||||
form
|
||||
});
|
||||
}
|
||||
cookies.set('pb_auth', JSON.stringify({ token: token }), { path: '/' });
|
||||
throw redirect(303, '/');
|
||||
}
|
||||
} satisfies Actions;
|
||||
};
|
||||
|
|
|
@ -4,8 +4,9 @@
|
|||
import * as Tabs from '$lib/components/ui/tabs';
|
||||
import type { PageData } from './$types.js';
|
||||
import { LoginForm, RegisterForm, SSOForm } from './(components)';
|
||||
export let form;
|
||||
|
||||
export let data: PageData;
|
||||
|
||||
const { providers } = data;
|
||||
const providersWithIcons = providers.map((provider) => ({
|
||||
...provider,
|
||||
|
@ -22,7 +23,7 @@
|
|||
|
||||
<div class="lg:p-8">
|
||||
<Tabs.Root
|
||||
value={form?.showLogin ? 'login' : tab}
|
||||
value={tab}
|
||||
class="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]"
|
||||
>
|
||||
<Tabs.List class="grid w-full grid-cols-2">
|
||||
|
@ -30,16 +31,16 @@
|
|||
<Tabs.Trigger value="register">Register</Tabs.Trigger>
|
||||
</Tabs.List>
|
||||
<Tabs.Content value="login">
|
||||
<LoginForm {form} />
|
||||
<LoginForm data={data.loginForm} />
|
||||
</Tabs.Content>
|
||||
<Tabs.Content value="register">
|
||||
<RegisterForm />
|
||||
<RegisterForm data={data.registerForm} />
|
||||
</Tabs.Content>
|
||||
<p class="px-8 text-center text-xs text-muted-foreground">
|
||||
Forgot password? <a class="text-primary underline" href="/reset-password">Reset password.</a>
|
||||
</p>
|
||||
{#if providers.length}
|
||||
<SSOForm providers={providersWithIcons} />
|
||||
<SSOForm data={data.ssoForm} providers={providersWithIcons} />
|
||||
{/if}
|
||||
</Tabs.Root>
|
||||
</div>
|
||||
|
|
Loading…
Reference in a new issue