feat(auth): implement session-based authentication and API token management
Server CI / Lint (push) Successful in 19s
Server CI / Build & Push Docker Image (push) Failing after 44s

- Introduced a new authentication system using session cookies for the web dashboard and API tokens for sync clients.
- Replaced the old SERVER_PASSWORD scheme with a more secure API token mechanism.
- Added routes for user setup, login, logout, and credential updates.
- Implemented middleware to require session and API token for protected routes.
- Updated web UI to handle authentication states and provide user feedback.
- Enhanced error handling in API requests and responses.
- Updated README to reflect new authentication flow and database requirements.
This commit is contained in:
Gabriel20xx committed 2026-08-01 12:51:02 +02:00
1 parent 240e1fda4a
commit b150d835a1
18 files changed
+1022 -982

No files matched your search

@@ -0,0 +1,97 @@
<script>
import { Table2 } from '@lucide/svelte';
import Button from '$lib/components/ui/button.svelte';
import { useAuth } from '$lib/features/auth/auth.svelte.js';
let { setupRequired } = $props();
const auth = useAuth();
let username = $state('');
let password = $state('');
let confirmPassword = $state('');
let submitting = $state(false);
let error = $state('');
async function submit(event) {
event.preventDefault();
error = '';
if (setupRequired && password !== confirmPassword) {
error = 'Passwords do not match.';
return;
}
submitting = true;
try {
if (setupRequired) {
await auth.setup(username, password);
} else {
await auth.login(username, password);
}
} catch (submitError) {
error = submitError instanceof Error ? submitError.message : 'Request failed.';
} finally {
submitting = false;
}
}
</script>
<main class="flex min-h-screen items-center justify-center bg-bg px-4 py-8">
<section class="w-full max-w-sm rounded-lg border border-border bg-surface p-6 shadow-sm">
<div class="mb-6 flex flex-col items-center gap-2 text-center">
<Table2 class="size-8 text-primary" />
<h1 class="text-xl font-semibold">CollabTable</h1>
<p class="text-sm text-muted-fg">
{setupRequired ? 'Create the admin account for this dashboard.' : 'Sign in to view this dashboard.'}
</p>
</div>
<form class="space-y-4" onsubmit={submit}>
<div>
<label for="auth-username" class="mb-1 block text-sm font-medium">Username</label>
<!-- svelte-ignore a11y_autofocus -->
<input
id="auth-username"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={username}
autocomplete="username"
required
autofocus
/>
</div>
<div>
<label for="auth-password" class="mb-1 block text-sm font-medium">Password</label>
<input
id="auth-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={password}
autocomplete={setupRequired ? 'new-password' : 'current-password'}
minlength={8}
required
/>
</div>
{#if setupRequired}
<div>
<label for="auth-confirm-password" class="mb-1 block text-sm font-medium">Confirm password</label>
<input
id="auth-confirm-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={confirmPassword}
autocomplete="new-password"
minlength={8}
required
/>
</div>
{/if}
{#if error}
<p class="text-sm text-danger">{error}</p>
{/if}
<Button type="submit" class="w-full" disabled={submitting}>
{submitting ? 'Working…' : setupRequired ? 'Create account' : 'Sign in'}
</Button>
</form>
</section>
</main>
@@ -0,0 +1,109 @@
<script>
import Button from '$lib/components/ui/button.svelte';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
import { useAuth } from '$lib/features/auth/auth.svelte.js';
let { open = $bindable(false), currentUsername } = $props();
const auth = useAuth();
let username = $state('');
let currentPassword = $state('');
let newPassword = $state('');
let confirmPassword = $state('');
let error = $state('');
let saving = $state(false);
$effect(() => {
if (open) username = currentUsername;
});
async function submit(event) {
event.preventDefault();
error = '';
if (newPassword !== confirmPassword) {
error = 'Passwords do not match.';
return;
}
saving = true;
try {
await auth.updateCredentials({
currentPassword,
newUsername: username.trim() || undefined,
newPassword: newPassword || undefined,
});
currentPassword = '';
newPassword = '';
confirmPassword = '';
open = false;
} catch (saveError) {
error = saveError instanceof Error ? saveError.message : 'Request failed.';
} finally {
saving = false;
}
}
</script>
<Dialog bind:open>
<DialogContent>
<DialogHeader>
<DialogTitle>Account</DialogTitle>
</DialogHeader>
<form class="space-y-4" onsubmit={submit}>
<p class="text-sm text-muted-fg">Changing your credentials will sign you out everywhere.</p>
<div>
<label for="credentials-username" class="mb-1 block text-sm font-medium">Username</label>
<input
id="credentials-username"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={username}
autocomplete="username"
/>
</div>
<div>
<label for="credentials-current-password" class="mb-1 block text-sm font-medium">Current password</label>
<input
id="credentials-current-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={currentPassword}
autocomplete="current-password"
required
/>
</div>
<div>
<label for="credentials-new-password" class="mb-1 block text-sm font-medium">New password</label>
<input
id="credentials-new-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={newPassword}
autocomplete="new-password"
minlength={8}
placeholder="Leave blank to keep current password"
/>
</div>
<div>
<label for="credentials-confirm-password" class="mb-1 block text-sm font-medium">Confirm new password</label>
<input
id="credentials-confirm-password"
type="password"
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
bind:value={confirmPassword}
autocomplete="new-password"
minlength={8}
/>
</div>
{#if error}
<p class="text-sm text-danger">{error}</p>
{/if}
<DialogFooter>
<Button type="submit" disabled={saving}>
{saving ? 'Saving…' : 'Save'}
</Button>
<Button type="button" variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
@@ -0,0 +1,68 @@
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { getContext, setContext } from 'svelte';
import { fetchAuthStatus, login, logout, setupAccount, updateCredentials } from '$lib/api.js';
const AUTH_STATUS_KEY = ['AuthStatus'];
const AUTH_CONTEXT_KEY = Symbol('auth');
export function createAuthStore() {
const queryClient = useQueryClient();
const statusQuery = createQuery(() => ({
queryKey: AUTH_STATUS_KEY,
queryFn: fetchAuthStatus,
}));
const setupMutation = createMutation(() => ({
mutationFn: ({ username, password }) => setupAccount(username, password),
}));
const loginMutation = createMutation(() => ({
mutationFn: ({ username, password }) => login(username, password),
}));
const logoutMutation = createMutation(() => ({
mutationFn: () => logout(),
}));
const updateCredentialsMutation = createMutation(() => ({
mutationFn: (input) => updateCredentials(input),
}));
const refresh = () => queryClient.invalidateQueries({ queryKey: AUTH_STATUS_KEY });
const store = {
get status() {
return statusQuery.data;
},
get loading() {
return statusQuery.isLoading;
},
get error() {
return statusQuery.error;
},
async setup(username, password) {
await setupMutation.mutateAsync({ username, password });
await refresh();
},
async login(username, password) {
await loginMutation.mutateAsync({ username, password });
await refresh();
},
async logout() {
await logoutMutation.mutateAsync();
await refresh();
},
async updateCredentials(input) {
await updateCredentialsMutation.mutateAsync(input);
await refresh();
},
};
setContext(AUTH_CONTEXT_KEY, store);
return store;
}
export function useAuth() {
const ctx = getContext(AUTH_CONTEXT_KEY);
if (!ctx) {
throw new Error('useAuth() must be called within the root layout that calls createAuthStore()');
}
return ctx;
}
@@ -1,15 +1,29 @@
<script>
import { Tooltip } from 'bits-ui';
import Header from '$lib/components/Header.svelte';
import AuthPage from '$lib/features/auth/AuthPage.svelte';
import { createAuthStore } from '$lib/features/auth/auth.svelte.js';
let { children } = $props();
const auth = createAuthStore();
</script>
<Tooltip.Provider delayDuration={300}>
<div class="flex min-h-screen flex-col">
<Header />
<main class="flex min-w-0 flex-1 flex-col">
{@render children?.()}
</main>
</div>
{#if auth.loading}
<div class="flex min-h-screen items-center justify-center text-sm text-muted-fg">Loading…</div>
{:else if auth.error}
<div class="flex min-h-screen items-center justify-center px-4 text-sm text-danger">
{auth.error instanceof Error ? auth.error.message : 'Request failed.'}
</div>
{:else if !auth.status || auth.status.setupRequired || !auth.status.authenticated}
<AuthPage setupRequired={auth.status?.setupRequired ?? true} />
{:else}
<div class="flex min-h-screen flex-col">
<Header />
<main class="flex min-w-0 flex-1 flex-col">
{@render children?.()}
</main>
</div>
{/if}
</Tooltip.Provider>
@@ -1,10 +1,28 @@
<script>
import { Moon, Sun, SunMoon } from '@lucide/svelte';
import { LogOut, Moon, Sun, SunMoon, UserCog } from '@lucide/svelte';
import Button from '$lib/components/ui/button.svelte';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
import { themeState } from '$lib/theme.svelte.js';
import { useAuth } from '$lib/features/auth/auth.svelte.js';
import CredentialsDialog from '$lib/features/auth/CredentialsDialog.svelte';
let { open = $bindable(false) } = $props();
const auth = useAuth();
let credentialsOpen = $state(false);
// bits-ui dialogs don't nest cleanly (focus-trap/z-index conflicts), so close this one
// before opening the next, matching the pattern used elsewhere in this project series.
function openCredentials() {
open = false;
credentialsOpen = true;
}
async function handleLogout() {
open = false;
await auth.logout();
}
</script>
<Dialog bind:open>
@@ -47,8 +65,23 @@
</Button>
</div>
</div>
<div>
<span class="mb-2 block text-sm font-medium">Account</span>
<div class="flex flex-col gap-2">
<Button type="button" variant="secondary" class="justify-start gap-2" onclick={openCredentials}>
<UserCog class="size-4" />
Change username / password
</Button>
<Button type="button" variant="secondary" class="justify-start gap-2" onclick={handleLogout}>
<LogOut class="size-4" />
Log out
</Button>
</div>
</div>
<DialogFooter>
<Button type="button" variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<CredentialsDialog bind:open={credentialsOpen} currentUsername={auth.status?.username ?? ''} />