feat: add initial skeleton for authentication in sveltekit with pocketbase

This commit is contained in:
Bart van der Braak 2024-01-28 22:21:47 +01:00
parent 69ccab8129
commit 88884a69ac
30 changed files with 682 additions and 197 deletions

View file

@ -0,0 +1,65 @@
import { redirect } from '@sveltejs/kit';
export const actions = {
default: 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');
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');
}
await locals.pocketBase.collection('users').create({
email,
password,
name,
passwordConfirm: password
});
await locals.pocketBase.collection('users').authWithPassword(email, password);
} 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, '/');
}
};

View file

@ -0,0 +1,23 @@
<script lang="ts">
import type { ActionData } from './$types';
export let form: ActionData;
</script>
<h1>Sign up</h1>
<form method="POST">
<input type="text" name="name" placeholder="name" value={form?.name ?? ''} />
<input type="email" name="email" placeholder="E-mail" value={form?.email ?? ''} />
<input type="password" name="password" placeholder="Password" value={form?.password ?? ''} />
<button type="submit">Sign up</button>
</form>
{#if form?.error}
<p>{form.error}</p>
{/if}
<p>Already have an account?</p>
<a href="/login">Log in</a>