♻️ 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 charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="text-scale" content="scale" /> <meta name="text-scale" content="scale" />
<meta name="theme-color" content="#1a1a2e" />
<link rel="manifest" href="/manifest.webmanifest" />
%sveltekit.head% %sveltekit.head%
</head> </head>
<body data-sveltekit-preload-data="hover"> <body data-sveltekit-preload-data="hover">
+76 -52
View File
@@ -1,29 +1,45 @@
<script lang="ts"> <script lang="ts">
import { pwaInfo } from 'virtual:pwa-info'; import { onMount } from 'svelte';
import { page } from '$app/state';
import { hasToken } from '$lib/api/client';
import { onMount, onDestroy } from 'svelte';
import { goto } from '$app/navigation'; 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 { children } = $props();
let gate = $state<'login' | 'app' | null>(null);
onMount(async () => { async function route() {
// Register the PWA service worker through SvelteKit's pipeline. if (!session.userId || gate === 'login') gate = await resolveGate();
// vite-plugin-pwa's injectRegister option cannot inject into SvelteKit's const path = page.url.pathname;
// HTML because SvelteKit intercepts Vite's transformIndexHtml hook. if (gate === 'app') {
if (pwaInfo) { if (path === '/' || path === '/login') await goto(safeNext(page.url), { replaceState: true });
const { registerSW } = await import('virtual:pwa-register'); } else if (gate === 'login' && path !== '/login') {
registerSW({ immediate: true }); await goto(
'/login' + (path === '/' ? '' : '?next=' + encodeURIComponent(path + page.url.search)),
{ replaceState: true }
);
}
} }
if (!hasToken() && page.url.pathname !== '/settings') { $effect(() => {
goto('/settings'); page.url.pathname;
} session.userId;
startSync(); 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'); const todayActive = $derived(page.url.pathname === '/today');
@@ -31,28 +47,27 @@
page.url.pathname === '/week' && !todayActive page.url.pathname === '/week' && !todayActive
); );
function formatLastSynced(d: Date | null): string { const pending = $derived(status.ready ? pendingCount() : 0);
if (!d) return 'never'; const error = $derived(status.error);
const diff = Math.floor((Date.now() - d.getTime()) / 1000); 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 < 5) return 'just now';
if (diff < 60) return `${diff}s ago`; if (diff < 60) return `${diff}s ago`;
if (diff < 3600) return `${Math.floor(diff / 60)}m 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. const syncTitle = $derived.by(() => {
let tick = $state(0); tick;
let tickInterval: ReturnType<typeof setInterval>; return error ?? (!online ? 'Offline' : `Last synced: ${formatLastSynced(lastSync)}`);
onMount(() => { tickInterval = setInterval(() => tick++, 15_000); }); });
onDestroy(() => clearInterval(tickInterval));
</script> </script>
<svelte:head> {#if inApp}
{#if pwaInfo}
{@html pwaInfo.webManifest.linkTag}
{/if}
</svelte:head>
<nav> <nav>
<div class="nav-links"> <div class="nav-links">
<a href="/today" class:active={todayActive}>Today</a> <a href="/today" class:active={todayActive}>Today</a>
@@ -62,21 +77,18 @@
</div> </div>
<button <button
class="sync-btn" class="sync-btn"
class:syncing={$syncState.status === 'syncing'} class:error={error !== null}
class:error={$syncState.status === 'error'} onclick={() => void syncNow()}
onclick={triggerSync} title={syncTitle}
title={$syncState.error ?? `Last synced: ${formatLastSynced($syncState.lastSynced)}`}
aria-label="Sync" aria-label="Sync"
> >
{#if $syncState.status === 'syncing'} {#if error}
<span class="spin">↻</span>
{:else if $syncState.status === 'error'}
<span>⚠</span> <span>⚠</span>
{:else} {:else}
<span>↻</span> <span>↻</span>
{/if} {/if}
{#if $syncState.pendingCount > 0} {#if pending > 0}
<span class="badge">{$syncState.pendingCount}</span> <span class="badge">{pending}</span>
{/if} {/if}
</button> </button>
</nav> </nav>
@@ -84,6 +96,13 @@
<main> <main>
{@render children()} {@render children()}
</main> </main>
{:else if gate === 'login'}
<div class="auth-wrap">
{@render children()}
</div>
{:else}
<p class="loading">Loading…</p>
{/if}
<style> <style>
:global(*, *::before, *::after) { :global(*, *::before, *::after) {
@@ -150,21 +169,10 @@
color: #e9ecef; color: #e9ecef;
border-color: #555580; border-color: #555580;
} }
.sync-btn.syncing {
color: #74c0fc;
border-color: #74c0fc55;
}
.sync-btn.error { .sync-btn.error {
color: #ff6b6b; color: #ff6b6b;
border-color: #ff6b6b55; border-color: #ff6b6b55;
} }
.spin {
display: inline-block;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.badge { .badge {
font-size: 0.65rem; font-size: 0.65rem;
font-weight: 700; font-weight: 700;
@@ -180,4 +188,20 @@
margin: 0 auto; margin: 0 auto;
padding: 1.5rem 1rem; 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> </style>
+1 -5
View File
@@ -1,5 +1 @@
<script lang="ts"> <!-- The layout routes / to /today or /login. -->
import { goto } from '$app/navigation';
import { onMount } from 'svelte';
onMount(() => goto('/today', { replaceState: true }));
</script>