feat(auth): add user authentication with roles, HMAC-signed cookies, and login/register UI
- Add `users` PocketBase collection (username, password_hash, role, created) - Implement HMAC-SHA256 signed cookie auth in hooks.server.ts; token payload is userId:username:role - Add User type, getUserByUsername, createUser (scrypt), loginUser (timing-safe) to pocketbase.ts - Add login/register page with tabbed form UI and server actions - Add logout route that clears the auth cookie - Add layout.server.ts auth guard: redirect unauthenticated users to /login - Extend App.Locals and App.PageData with role field - Add AUTH_SECRET, POCKETBASE_ADMIN_EMAIL/PASSWORD to .env.example - Install @types/node for Node crypto/scrypt types
This commit is contained in:
15
ui/src/routes/+layout.server.ts
Normal file
15
ui/src/routes/+layout.server.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
// Routes that are accessible without being logged in
|
||||
const PUBLIC_ROUTES = new Set(['/login']);
|
||||
|
||||
export const load: LayoutServerLoad = async ({ locals, url }) => {
|
||||
if (!PUBLIC_ROUTES.has(url.pathname) && !locals.user) {
|
||||
redirect(302, `/login`);
|
||||
}
|
||||
|
||||
return {
|
||||
user: locals.user
|
||||
};
|
||||
};
|
||||
101
ui/src/routes/login/+page.server.ts
Normal file
101
ui/src/routes/login/+page.server.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
import { loginUser, createUser } from '$lib/server/pocketbase';
|
||||
import { createAuthToken } from '../../hooks.server';
|
||||
|
||||
const AUTH_COOKIE = 'libnovel_auth';
|
||||
const ONE_YEAR = 60 * 60 * 24 * 365;
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
// Already logged in — send to library
|
||||
if (locals.user) {
|
||||
redirect(302, '/books');
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
login: async ({ request, cookies }) => {
|
||||
const data = await request.formData();
|
||||
const username = (data.get('username') as string | null)?.trim() ?? '';
|
||||
const password = (data.get('password') as string | null) ?? '';
|
||||
|
||||
if (!username || !password) {
|
||||
return fail(400, { action: 'login', error: 'Username and password are required.' });
|
||||
}
|
||||
|
||||
let user;
|
||||
try {
|
||||
user = await loginUser(username, password);
|
||||
} catch {
|
||||
return fail(500, { action: 'login', error: 'An error occurred. Please try again.' });
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return fail(401, { action: 'login', error: 'Invalid username or password.' });
|
||||
}
|
||||
|
||||
const token = createAuthToken(user.id, user.username, user.role ?? 'user');
|
||||
cookies.set(AUTH_COOKIE, token, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
maxAge: ONE_YEAR
|
||||
});
|
||||
|
||||
redirect(302, '/books');
|
||||
},
|
||||
|
||||
register: async ({ request, cookies }) => {
|
||||
const data = await request.formData();
|
||||
const username = (data.get('username') as string | null)?.trim() ?? '';
|
||||
const password = (data.get('password') as string | null) ?? '';
|
||||
const confirm = (data.get('confirm') as string | null) ?? '';
|
||||
|
||||
if (!username || !password) {
|
||||
return fail(400, { action: 'register', error: 'Username and password are required.' });
|
||||
}
|
||||
if (username.length < 3 || username.length > 32) {
|
||||
return fail(400, {
|
||||
action: 'register',
|
||||
error: 'Username must be between 3 and 32 characters.'
|
||||
});
|
||||
}
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
|
||||
return fail(400, {
|
||||
action: 'register',
|
||||
error: 'Username may only contain letters, numbers, underscores and hyphens.'
|
||||
});
|
||||
}
|
||||
if (password.length < 8) {
|
||||
return fail(400, {
|
||||
action: 'register',
|
||||
error: 'Password must be at least 8 characters.'
|
||||
});
|
||||
}
|
||||
if (password !== confirm) {
|
||||
return fail(400, { action: 'register', error: 'Passwords do not match.' });
|
||||
}
|
||||
|
||||
let user;
|
||||
try {
|
||||
user = await createUser(username, password);
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Registration failed.';
|
||||
if (msg.includes('Username already taken')) {
|
||||
return fail(409, { action: 'register', error: 'That username is already taken.' });
|
||||
}
|
||||
return fail(500, { action: 'register', error: 'An error occurred. Please try again.' });
|
||||
}
|
||||
|
||||
const token = createAuthToken(user.id, user.username, user.role ?? 'user');
|
||||
cookies.set(AUTH_COOKIE, token, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
maxAge: ONE_YEAR
|
||||
});
|
||||
|
||||
redirect(302, '/books');
|
||||
}
|
||||
};
|
||||
136
ui/src/routes/login/+page.svelte
Normal file
136
ui/src/routes/login/+page.svelte
Normal file
@@ -0,0 +1,136 @@
|
||||
<script lang="ts">
|
||||
import type { ActionData } from './$types';
|
||||
|
||||
let { form }: { form: ActionData } = $props();
|
||||
|
||||
let mode: 'login' | 'register' = $state('login');
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Sign in — libnovel</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="flex items-center justify-center min-h-[60vh]">
|
||||
<div class="w-full max-w-sm">
|
||||
<!-- Tab switcher -->
|
||||
<div class="flex mb-6 border-b border-zinc-700">
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (mode = 'login')}
|
||||
class="flex-1 pb-3 text-sm font-medium transition-colors
|
||||
{mode === 'login'
|
||||
? 'text-amber-400 border-b-2 border-amber-400 -mb-px'
|
||||
: 'text-zinc-400 hover:text-zinc-100'}"
|
||||
>
|
||||
Sign in
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (mode = 'register')}
|
||||
class="flex-1 pb-3 text-sm font-medium transition-colors
|
||||
{mode === 'register'
|
||||
? 'text-amber-400 border-b-2 border-amber-400 -mb-px'
|
||||
: 'text-zinc-400 hover:text-zinc-100'}"
|
||||
>
|
||||
Create account
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if form?.error && (form?.action === mode || !form?.action)}
|
||||
<div class="mb-4 rounded bg-red-900/40 border border-red-700 px-4 py-3 text-sm text-red-300">
|
||||
{form.error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if mode === 'login'}
|
||||
<form method="POST" action="?/login" class="flex flex-col gap-4">
|
||||
<div>
|
||||
<label for="login-username" class="block text-xs text-zinc-400 mb-1">Username</label>
|
||||
<input
|
||||
id="login-username"
|
||||
name="username"
|
||||
type="text"
|
||||
autocomplete="username"
|
||||
required
|
||||
class="w-full rounded bg-zinc-800 border border-zinc-700 px-3 py-2 text-sm text-zinc-100
|
||||
placeholder-zinc-500 focus:outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400"
|
||||
placeholder="your_username"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="login-password" class="block text-xs text-zinc-400 mb-1">Password</label>
|
||||
<input
|
||||
id="login-password"
|
||||
name="password"
|
||||
type="password"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
class="w-full rounded bg-zinc-800 border border-zinc-700 px-3 py-2 text-sm text-zinc-100
|
||||
placeholder-zinc-500 focus:outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
class="w-full py-2 rounded bg-amber-400 text-zinc-900 font-semibold text-sm hover:bg-amber-300 transition-colors"
|
||||
>
|
||||
Sign in
|
||||
</button>
|
||||
</form>
|
||||
{:else}
|
||||
<form method="POST" action="?/register" class="flex flex-col gap-4">
|
||||
<div>
|
||||
<label for="reg-username" class="block text-xs text-zinc-400 mb-1">Username</label>
|
||||
<input
|
||||
id="reg-username"
|
||||
name="username"
|
||||
type="text"
|
||||
autocomplete="username"
|
||||
required
|
||||
minlength="3"
|
||||
maxlength="32"
|
||||
pattern="[a-zA-Z0-9_\-]+"
|
||||
class="w-full rounded bg-zinc-800 border border-zinc-700 px-3 py-2 text-sm text-zinc-100
|
||||
placeholder-zinc-500 focus:outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400"
|
||||
placeholder="your_username"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-zinc-500">3–32 characters: letters, numbers, _ or -</p>
|
||||
</div>
|
||||
<div>
|
||||
<label for="reg-password" class="block text-xs text-zinc-400 mb-1">Password</label>
|
||||
<input
|
||||
id="reg-password"
|
||||
name="password"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
required
|
||||
minlength="8"
|
||||
class="w-full rounded bg-zinc-800 border border-zinc-700 px-3 py-2 text-sm text-zinc-100
|
||||
placeholder-zinc-500 focus:outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-zinc-500">At least 8 characters</p>
|
||||
</div>
|
||||
<div>
|
||||
<label for="reg-confirm" class="block text-xs text-zinc-400 mb-1">Confirm password</label>
|
||||
<input
|
||||
id="reg-confirm"
|
||||
name="confirm"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
required
|
||||
class="w-full rounded bg-zinc-800 border border-zinc-700 px-3 py-2 text-sm text-zinc-100
|
||||
placeholder-zinc-500 focus:outline-none focus:border-amber-400 focus:ring-1 focus:ring-amber-400"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
class="w-full py-2 rounded bg-amber-400 text-zinc-900 font-semibold text-sm hover:bg-amber-300 transition-colors"
|
||||
>
|
||||
Create account
|
||||
</button>
|
||||
</form>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
11
ui/src/routes/logout/+page.server.ts
Normal file
11
ui/src/routes/logout/+page.server.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { Actions } from './$types';
|
||||
|
||||
const AUTH_COOKIE = 'libnovel_auth';
|
||||
|
||||
export const actions: Actions = {
|
||||
default: async ({ cookies }) => {
|
||||
cookies.delete(AUTH_COOKIE, { path: '/' });
|
||||
redirect(302, '/login');
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user