♻️ Gate the app behind PocketBase authentication

Only signed-in users reach the working pages. Everyone else lands on
the login page and returns to the page they asked for after signing in.
The manifest link moves into the page template and the service worker
is registered only in production builds.
This commit is contained in:
2026-11-30 17:43:13 +00:00
parent 23cecdea80
commit f54e7238b4
3 changed files with 99 additions and 77 deletions
+2
View File
@@ -4,6 +4,8 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="text-scale" content="scale" />
<meta name="theme-color" content="#1a1a2e" />
<link rel="manifest" href="/manifest.webmanifest" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
+80 -56
View File
@@ -1,29 +1,45 @@
<script lang="ts">
import { pwaInfo } from 'virtual:pwa-info';
import { page } from '$app/state';
import { hasToken } from '$lib/api/client';
import { onMount, onDestroy } from 'svelte';
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { startSync, stopSync, triggerSync, syncState } from '$lib/stores/sync';
import { page } from '$app/state';
import { pendingCount, status, syncNow } from '$lib/db.svelte';
import { resolveGate, safeNext, session } from '$lib/session.svelte';
let { children } = $props();
let gate = $state<'login' | 'app' | null>(null);
onMount(async () => {
// Register the PWA service worker through SvelteKit's pipeline.
// vite-plugin-pwa's injectRegister option cannot inject into SvelteKit's
// HTML because SvelteKit intercepts Vite's transformIndexHtml hook.
if (pwaInfo) {
const { registerSW } = await import('virtual:pwa-register');
registerSW({ immediate: true });
async function route() {
if (!session.userId || gate === 'login') gate = await resolveGate();
const path = page.url.pathname;
if (gate === 'app') {
if (path === '/' || path === '/login') await goto(safeNext(page.url), { replaceState: true });
} else if (gate === 'login' && path !== '/login') {
await goto(
'/login' + (path === '/' ? '' : '?next=' + encodeURIComponent(path + page.url.search)),
{ replaceState: true }
);
}
}
if (!hasToken() && page.url.pathname !== '/settings') {
goto('/settings');
}
startSync();
$effect(() => {
page.url.pathname;
session.userId;
if (gate !== null) void route();
});
onDestroy(stopSync);
// Tick every 15s so "Xs ago" stays fresh.
let tick = $state(0);
onMount(() => {
void resolveGate().then((g) => (gate = g));
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(() => {});
}
const tickInterval = setInterval(() => tick++, 15_000);
return () => clearInterval(tickInterval);
});
const inApp = $derived(gate === 'app' && status.ready);
const todayActive = $derived(page.url.pathname === '/today');
@@ -31,29 +47,28 @@
page.url.pathname === '/week' && !todayActive
);
function formatLastSynced(d: Date | null): string {
if (!d) return 'never';
const diff = Math.floor((Date.now() - d.getTime()) / 1000);
const pending = $derived(status.ready ? pendingCount() : 0);
const error = $derived(status.error);
const online = $derived(status.online);
const lastSync = $derived(status.lastSync);
function formatLastSynced(ms: number): string {
if (!ms) return 'never';
const diff = Math.floor((Date.now() - ms) / 1000);
if (diff < 5) return 'just now';
if (diff < 60) return `${diff}s ago`;
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
return new Date(ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// Tick every 15s so "Xs ago" stays fresh.
let tick = $state(0);
let tickInterval: ReturnType<typeof setInterval>;
onMount(() => { tickInterval = setInterval(() => tick++, 15_000); });
onDestroy(() => clearInterval(tickInterval));
const syncTitle = $derived.by(() => {
tick;
return error ?? (!online ? 'Offline' : `Last synced: ${formatLastSynced(lastSync)}`);
});
</script>
<svelte:head>
{#if pwaInfo}
{@html pwaInfo.webManifest.linkTag}
{/if}
</svelte:head>
<nav>
{#if inApp}
<nav>
<div class="nav-links">
<a href="/today" class:active={todayActive}>Today</a>
<a href="/week" class:active={weekActive}>Week</a>
@@ -62,28 +77,32 @@
</div>
<button
class="sync-btn"
class:syncing={$syncState.status === 'syncing'}
class:error={$syncState.status === 'error'}
onclick={triggerSync}
title={$syncState.error ?? `Last synced: ${formatLastSynced($syncState.lastSynced)}`}
class:error={error !== null}
onclick={() => void syncNow()}
title={syncTitle}
aria-label="Sync"
>
{#if $syncState.status === 'syncing'}
<span class="spin">↻</span>
{:else if $syncState.status === 'error'}
{#if error}
<span>⚠</span>
{:else}
<span>↻</span>
{/if}
{#if $syncState.pendingCount > 0}
<span class="badge">{$syncState.pendingCount}</span>
{#if pending > 0}
<span class="badge">{pending}</span>
{/if}
</button>
</nav>
</nav>
<main>
<main>
{@render children()}
</main>
</main>
{:else if gate === 'login'}
<div class="auth-wrap">
{@render children()}
</div>
{:else}
<p class="loading">Loading…</p>
{/if}
<style>
:global(*, *::before, *::after) {
@@ -150,21 +169,10 @@
color: #e9ecef;
border-color: #555580;
}
.sync-btn.syncing {
color: #74c0fc;
border-color: #74c0fc55;
}
.sync-btn.error {
color: #ff6b6b;
border-color: #ff6b6b55;
}
.spin {
display: inline-block;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.badge {
font-size: 0.65rem;
font-weight: 700;
@@ -180,4 +188,20 @@
margin: 0 auto;
padding: 1.5rem 1rem;
}
.auth-wrap {
min-height: 100dvh;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
.loading {
min-height: 100dvh;
display: flex;
align-items: center;
justify-content: center;
margin: 0;
color: #6c757d;
}
</style>
+1 -5
View File
@@ -1,5 +1 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { onMount } from 'svelte';
onMount(() => goto('/today', { replaceState: true }));
</script>
<!-- The layout routes / to /today or /login. -->