diff --git a/AGENTS.md b/AGENTS.md
index 9bbfff8..57a8b2c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -19,7 +19,8 @@ Course milestones: working prototype for Business Angel Meeting II (December), p
- Supabase: Postgres, Auth (email/password, Google), private Storage
- Deployment target: Vercel (app) + Supabase (backend services), free tiers
- Backend prototype exists and is being hardened (see `docs/BACKLOG.md`).
- The frontend has an app shell (layout, navigation, design tokens, DE/EN/NL); the feature pages are placeholders.
+ The frontend has an app shell (layout, navigation, design tokens, DE/EN/NL) and sign-in (F2); the feature pages
+ are placeholders.
- Frontend stack from `docs/Lastenheft_Ons.md`: Pinia, `@nuxtjs/i18n` (DE/EN/NL), Tailwind or UnoCSS,
Leaflet or MapLibre, Chart.js or ECharts. The frontend dev decides between the "or" options and records the
choice here. A new dependency goes in `package.json`, a shared file: say why in the PR description.
@@ -27,7 +28,10 @@ Course milestones: working prototype for Business Angel Meeting II (December), p
variables, so the look can be changed without knowing Tailwind (see Frontend rules).
- Decided: `@nuxtjs/i18n` is pinned to exactly **10.2.3**. Later releases require `vue-router` 5, while Nuxt 3.21
ships version 4. Do not upgrade it without moving to a Nuxt version that matches.
-- Not installed yet: Pinia, the map library and the chart library.
+- Decided: **Pinia** (`pinia` 3 with `@pinia/nuxt` 0.11) holds client state, starting with the session.
+- Decided: **rendering.** Only the landing page (`/`, `/en`, `/nl`) is rendered on the server. Every other page is
+ rendered in the browser (`routeRules` in `nuxt.config.ts`), because the Supabase session is stored there.
+- Not installed yet: the map library and the chart library.
## Ownership (who works where)
@@ -104,6 +108,9 @@ no mocking of the unit under test. Keep tests fast and independent of each other
Vitest is the single runner for unit, component and database tests (`npm test`). Playwright for E2E is not set up yet.
Backend tests live in `tests/`. Frontend tests live in `__tests__/` folders next to the code: `*.nuxt.spec.ts`
runs inside a Nuxt runtime, other `*.spec.ts` files run in plain Node (see `vitest.config.ts`).
+Shared test helpers live in `composables/__tests__/` (for example `fake-auth.ts`, an in-memory Supabase Auth).
+Put only spec files into `pages/__tests__/` and `components/__tests__/`: Nuxt would register other files there as
+pages or components.
"Done" always includes: new behavior has a test, and `npm test` and `npm run build` pass.
## Backend rules (do not break these)
@@ -147,6 +154,14 @@ Rule 1 applies to everyone, including the frontend.
- **Date categories** are fixed keys from `shared/date-categories.ts`; their labels come from i18n by key.
- Auth: the Supabase client is provided as `useNuxtApp().$supabase` (client only, see `plugins/auth.client.ts`).
Protect pages with route middleware, not with `v-if` in components.
+ - `middleware/auth.global.ts` protects **every** page. A page opts out with
+ `definePageMeta({ access: 'public' })` or `access: 'guest'` (only for signed-out visitors).
+ - Reach Supabase Auth only through `composables/useSupabaseAuth.ts`. The session state is in `stores/session.ts`.
+ - Call the API only through `useApi()` and show a failure with `t(error.messageKey)`.
+ - A `redirect` query value goes through `useReturnTarget()`, which only accepts paths inside the app.
+ - Google sign-in and confirmation emails return to `/auth/callback` (one address, no language prefix).
+ - Passwords need at least 8 characters. `PASSWORD_MIN_LENGTH` in `composables/formRules.ts` and
+ `minimum_password_length` under `[auth]` in `supabase/config.toml` must match; a frontend test fails otherwise.
## Current data model
diff --git a/app.vue b/app.vue
index d14f9c4..6dbfd32 100644
--- a/app.vue
+++ b/app.vue
@@ -1,6 +1,9 @@
+
+
+
+
diff --git a/components/__tests__/AppNav.nuxt.spec.ts b/components/__tests__/AppNav.nuxt.spec.ts
index 9f1a718..9f3a94e 100644
--- a/components/__tests__/AppNav.nuxt.spec.ts
+++ b/components/__tests__/AppNav.nuxt.spec.ts
@@ -1,10 +1,18 @@
-import { mountSuspended } from '@nuxt/test-utils/runtime'
+import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
import { flushPromises } from '@vue/test-utils'
-import { beforeEach, describe, expect, test } from 'vitest'
+import { beforeEach, describe, expect, test, vi } from 'vitest'
import { RouterLink } from 'vue-router'
+import { createFakeAuth } from '../../composables/__tests__/fake-auth'
+import { resetSession } from '../../composables/__tests__/reset-session'
import AppNav from '../AppNav.vue'
+const supabase = vi.hoisted(() => ({ auth: undefined as unknown }))
+mockNuxtImport('useSupabaseAuth', () => () => supabase.auth)
+
+// Somebody is signed in, because some tests visit protected pages.
beforeEach(async () => {
+ supabase.auth = createFakeAuth({ signedInAs: 'ann@example.org' }).auth
+ resetSession()
await useNuxtApp().$i18n.setLocale('de')
await useRouter().push('/')
})
@@ -22,16 +30,16 @@ describe('AppNav', () => {
test('is a labelled navigation with one link per main page', async () => {
const wrapper = await mountOn('/')
expect(wrapper.get('nav').attributes('aria-label')).toBe('Hauptnavigation')
- expect(wrapper.findAll('a').map(link => link.text())).toEqual(['Start', 'Dates', 'Karte', 'Fotos'])
- expect(wrapper.findAll('a').map(link => link.attributes('href'))).toEqual(['/', '/dates', '/map', '/photos'])
+ expect(wrapper.findAll('a').map(link => link.text())).toEqual(['Übersicht', 'Dates', 'Karte', 'Fotos'])
+ expect(wrapper.findAll('a').map(link => link.attributes('href'))).toEqual(['/dashboard', '/dates', '/map', '/photos'])
})
test('keeps the active language in labels and links', async () => {
const wrapper = await mountOn('/nl')
await useNuxtApp().$i18n.setLocale('nl')
await flushPromises()
- expect(wrapper.findAll('a').map(link => link.text())).toEqual(['Home', 'Dates', 'Kaart', 'Foto\'s'])
- expect(wrapper.findAll('a').map(link => link.attributes('href'))).toEqual(['/nl', '/nl/dates', '/nl/map', '/nl/photos'])
+ expect(wrapper.findAll('a').map(link => link.text())).toEqual(['Overzicht', 'Dates', 'Kaart', 'Foto\'s'])
+ expect(wrapper.findAll('a').map(link => link.attributes('href'))).toEqual(['/nl/dashboard', '/nl/dates', '/nl/map', '/nl/photos'])
})
test('marks only the current page', async () => {
diff --git a/components/__tests__/LanguageSwitcher.nuxt.spec.ts b/components/__tests__/LanguageSwitcher.nuxt.spec.ts
index bb58f8d..31f0740 100644
--- a/components/__tests__/LanguageSwitcher.nuxt.spec.ts
+++ b/components/__tests__/LanguageSwitcher.nuxt.spec.ts
@@ -1,14 +1,22 @@
-import { mountSuspended } from '@nuxt/test-utils/runtime'
+import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
import { beforeEach, describe, expect, test, vi } from 'vitest'
+import { createFakeAuth } from '../../composables/__tests__/fake-auth'
+import { resetSession } from '../../composables/__tests__/reset-session'
import LanguageSwitcher from '../LanguageSwitcher.vue'
+const supabase = vi.hoisted(() => ({ auth: undefined as unknown }))
+mockNuxtImport('useSupabaseAuth', () => () => supabase.auth)
+
// Reads the saved language from the cookie that the server will see on the next visit.
function savedLanguage() {
return document.cookie.match(/(?:^|; )ons_locale=([^;]*)/)?.[1]
}
// Every test starts on the German home page.
+// Somebody is signed in, because some tests visit protected pages.
beforeEach(async () => {
+ supabase.auth = createFakeAuth({ signedInAs: 'ann@example.org' }).auth
+ resetSession()
await useNuxtApp().$i18n.setLocale('de')
await useRouter().push('/')
})
diff --git a/composables/__tests__/errorKeys.spec.ts b/composables/__tests__/errorKeys.spec.ts
new file mode 100644
index 0000000..0dfa0b8
--- /dev/null
+++ b/composables/__tests__/errorKeys.spec.ts
@@ -0,0 +1,60 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, test } from 'vitest'
+import { apiErrorCodeSchema } from '../../shared/api-errors'
+import { apiErrorKey, authErrorKey } from '../errorKeys'
+
+const german = JSON.parse(readFileSync(new URL('../../i18n/locales/de.json', import.meta.url), 'utf8'))
+
+// Finds the text of a key such as "errors.api.no_space". messages.spec.ts covers en and nl.
+function textFor(key: string): unknown {
+ return key.split('.').reduce((node, part) => node?.[part], german)
+}
+
+// Codes from Supabase Auth, plus "network" and "unavailable" from the session store.
+const authCodes = [
+ 'invalid_credentials',
+ 'email_not_confirmed',
+ 'user_already_exists',
+ 'email_exists',
+ 'email_address_invalid',
+ 'weak_password',
+ 'signup_disabled',
+ 'email_provider_disabled',
+ 'provider_disabled',
+ 'oauth_provider_not_supported',
+ 'validation_failed',
+ 'over_request_rate_limit',
+ 'over_email_send_rate_limit',
+ 'network',
+ 'unavailable',
+]
+
+describe('apiErrorKey', () => {
+ // The list comes from the backend contract, so a new code makes this test fail.
+ test.each(apiErrorCodeSchema.options)('the backend code %s has its own message', (code) => {
+ const key = apiErrorKey(code)
+ expect(key).not.toBe('errors.unexpected')
+ expect(textFor(key)).toBeTypeOf('string')
+ })
+
+ test.each([undefined, 'something_new', 'toString'])('%s gets the general message', (code) => {
+ expect(apiErrorKey(code)).toBe('errors.unexpected')
+ expect(textFor('errors.unexpected')).toBeTypeOf('string')
+ })
+
+ test('network problems have a message', () => {
+ expect(textFor('errors.network')).toBeTypeOf('string')
+ })
+})
+
+describe('authErrorKey', () => {
+ test.each(authCodes)('%s has a message', (code) => {
+ const key = authErrorKey(code)
+ expect(key).not.toBe('errors.unexpected')
+ expect(textFor(key)).toBeTypeOf('string')
+ })
+
+ test.each([undefined, 'unknown', 'constructor'])('%s gets the general message', (code) => {
+ expect(authErrorKey(code)).toBe('errors.unexpected')
+ })
+})
diff --git a/composables/__tests__/fake-auth.ts b/composables/__tests__/fake-auth.ts
new file mode 100644
index 0000000..f7c1c6d
--- /dev/null
+++ b/composables/__tests__/fake-auth.ts
@@ -0,0 +1,72 @@
+import type { Session } from '@supabase/supabase-js'
+import { vi } from 'vitest'
+
+// An in-memory stand-in for supabase.auth, limited to the parts the app uses.
+// It lives in a __tests__ folder, so Nuxt does not auto-import it.
+
+type Listener = (event: string, session: Session | null) => void
+
+export function fakeSession(email: string, accessToken: string) {
+ return {
+ access_token: accessToken,
+ refresh_token: `refresh-for-${accessToken}`,
+ user: { id: `id-of-${email}`, email },
+ } as Session
+}
+
+// Answers requests the way /auth/v1/settings does: which sign-in providers are switched on.
+// Call vi.unstubAllGlobals() after the test.
+export function stubProviderSettings(providers: { google: boolean }) {
+ const request = vi.fn(async (_url: string, _options?: object) => ({ external: { email: true, ...providers } }))
+ vi.stubGlobal('$fetch', request)
+ return request
+}
+
+export function createFakeAuth(options: { signedInAs?: string } = {}) {
+ let issued = 0
+ // Every new session gets a new token: token-1, token-2, and so on.
+ function newSession(email: string) {
+ issued += 1
+ return fakeSession(email, `token-${issued}`)
+ }
+
+ let session: Session | null = options.signedInAs ? newSession(options.signedInAs) : null
+ const listeners = new Set()
+
+ function change(event: string, next: Session | null) {
+ session = next
+ for (const listener of listeners) {
+ listener(event, next)
+ }
+ }
+
+ function signedIn(email: string) {
+ change('SIGNED_IN', newSession(email))
+ return { data: { session, user: session!.user }, error: null as Error | null }
+ }
+
+ const auth = {
+ getSession: vi.fn(async () => ({ data: { session }, error: null as Error | null })),
+ onAuthStateChange: vi.fn((listener: Listener) => {
+ listeners.add(listener)
+ return { data: { subscription: { unsubscribe: () => listeners.delete(listener) } } }
+ }),
+ signInWithPassword: vi.fn(async (credentials: { email: string, password: string }) => signedIn(credentials.email)),
+ signUp: vi.fn(async (credentials: { email: string, password: string, options?: object }) => signedIn(credentials.email)),
+ signInWithOAuth: vi.fn(async (_request: object) => ({ data: {}, error: null as Error | null })),
+ signOut: vi.fn(async (_options?: object) => {
+ change('SIGNED_OUT', null)
+ return { error: null as Error | null }
+ }),
+ refreshSession: vi.fn(async () => {
+ change('TOKEN_REFRESHED', newSession(session?.user.email ?? 'nobody@example.org'))
+ return { data: { session }, error: null as Error | null }
+ }),
+ }
+
+ return {
+ auth,
+ // A change that does not start in this tab, for example a sign-out somewhere else.
+ endSession: () => change('SIGNED_OUT', null),
+ }
+}
diff --git a/composables/__tests__/form-helpers.ts b/composables/__tests__/form-helpers.ts
new file mode 100644
index 0000000..1eba5c6
--- /dev/null
+++ b/composables/__tests__/form-helpers.ts
@@ -0,0 +1,25 @@
+import type { VueWrapper } from '@vue/test-utils'
+
+// Finds things the way a person does: by the visible label or button text.
+
+export function field(wrapper: VueWrapper, label: string) {
+ const found = wrapper.findAll('label').find(candidate => candidate.text() === label)
+ if (!found) {
+ throw new Error(`No field is labelled "${label}"`)
+ }
+ return wrapper.get(`[id="${found.attributes('for')}"]`)
+}
+
+export function button(wrapper: VueWrapper, text: string) {
+ const found = wrapper.findAll('button').find(candidate => candidate.text() === text)
+ if (!found) {
+ throw new Error(`There is no button "${text}"`)
+ }
+ return found
+}
+
+// The texts that screen readers announce for a field, taken from aria-describedby.
+export function description(wrapper: VueWrapper, label: string) {
+ const ids = field(wrapper, label).attributes('aria-describedby')?.split(' ') ?? []
+ return ids.map(id => wrapper.get(`[id="${id}"]`).text()).join(' ')
+}
diff --git a/composables/__tests__/formRules.spec.ts b/composables/__tests__/formRules.spec.ts
new file mode 100644
index 0000000..4725ef6
--- /dev/null
+++ b/composables/__tests__/formRules.spec.ts
@@ -0,0 +1,50 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, test } from 'vitest'
+import { emailError, newPasswordError, PASSWORD_MIN_LENGTH, passwordError } from '../formRules'
+
+describe('PASSWORD_MIN_LENGTH', () => {
+ // Supabase recommends at least 8 characters.
+ test('is 8', () => {
+ expect(PASSWORD_MIN_LENGTH).toBe(8)
+ })
+
+ // The browser check alone can be bypassed, so Supabase has to require the same length.
+ // supabase/ belongs to the backend: if this fails, ask for the change there.
+ test('is also required by the local Supabase configuration', () => {
+ const config = readFileSync(new URL('../../supabase/config.toml', import.meta.url), 'utf8')
+ // The key only counts inside the [auth] section.
+ const authSection = config.split(/^\[/m).find(section => section.startsWith('auth]')) ?? ''
+ const configured = authSection.match(/^minimum_password_length\s*=\s*(\d+)/m)?.[1]
+
+ const hint = `supabase/config.toml must set minimum_password_length = ${PASSWORD_MIN_LENGTH} under [auth]`
+ expect(Number(configured), hint).toBe(PASSWORD_MIN_LENGTH)
+ })
+})
+
+describe('emailError', () => {
+ test.each(['', ' '])('asks for an address when the field is %j', (value) => {
+ expect(emailError(value)).toBe('errors.form.emailRequired')
+ })
+
+ test.each(['ann', 'ann@', '@example.org', 'ann@example', 'ann smith@example.org'])('rejects %s', (value) => {
+ expect(emailError(value)).toBe('errors.form.emailInvalid')
+ })
+
+ test.each(['ann@example.org', ' ann+ons@mail.example.nl '])('accepts %j', (value) => {
+ expect(emailError(value)).toBeUndefined()
+ })
+})
+
+describe('passwords', () => {
+ test('an existing password only has to be filled in', () => {
+ expect(passwordError('')).toBe('errors.form.passwordRequired')
+ // The server decides whether it is right, also for short old passwords.
+ expect(passwordError('a')).toBeUndefined()
+ })
+
+ test('a new password needs the minimum length', () => {
+ expect(newPasswordError('')).toBe('errors.form.passwordRequired')
+ expect(newPasswordError('a'.repeat(PASSWORD_MIN_LENGTH - 1))).toBe('errors.form.passwordTooShort')
+ expect(newPasswordError('a'.repeat(PASSWORD_MIN_LENGTH))).toBeUndefined()
+ })
+})
diff --git a/composables/__tests__/reset-session.ts b/composables/__tests__/reset-session.ts
new file mode 100644
index 0000000..9ba7b72
--- /dev/null
+++ b/composables/__tests__/reset-session.ts
@@ -0,0 +1,9 @@
+import { useNuxtApp } from '#app'
+import { useSessionStore } from '../../stores/session'
+
+// The Nuxt test app lives for a whole test file, so each test needs a fresh session store.
+export function resetSession() {
+ const store = useSessionStore()
+ store.$dispose()
+ delete (useNuxtApp().$pinia as { state: { value: Record } }).state.value.session
+}
diff --git a/composables/__tests__/safeRedirect.spec.ts b/composables/__tests__/safeRedirect.spec.ts
new file mode 100644
index 0000000..5087982
--- /dev/null
+++ b/composables/__tests__/safeRedirect.spec.ts
@@ -0,0 +1,45 @@
+import { describe, expect, test } from 'vitest'
+import { safeRedirect } from '../safeRedirect'
+
+// The "redirect" query parameter can be written by anybody who sends a link.
+// It must never lead away from this app.
+describe('safeRedirect', () => {
+ test.each([
+ '/dashboard',
+ '/en/map',
+ '/dates?status=done#top',
+ ])('keeps the path %s', (path) => {
+ expect(safeRedirect(path, '/fallback')).toBe(path)
+ })
+
+ test.each([
+ undefined,
+ null,
+ '',
+ ['/dates', '/map'],
+ 'dashboard',
+ 'https://evil.example',
+ 'javascript:alert(1)',
+ '//evil.example',
+ '/\\evil.example',
+ '\\/evil.example',
+ // Browsers drop tabs and line breaks inside addresses.
+ '/\t/evil.example',
+ '/\n/evil.example',
+ // Normalises to a path that starts with two slashes.
+ '/.//evil.example',
+ ])('rejects %j', (value) => {
+ expect(safeRedirect(value, '/fallback')).toBe('/fallback')
+ })
+
+ test.each([
+ '/login',
+ '/en/login?redirect=/map',
+ '/register',
+ '/nl/register',
+ '/auth/callback?code=abc',
+ '/dashboard/../login',
+ ])('never leads back to a sign-in page: %s', (path) => {
+ expect(safeRedirect(path, '/fallback')).toBe('/fallback')
+ })
+})
diff --git a/composables/__tests__/useApi.nuxt.spec.ts b/composables/__tests__/useApi.nuxt.spec.ts
new file mode 100644
index 0000000..da9558e
--- /dev/null
+++ b/composables/__tests__/useApi.nuxt.spec.ts
@@ -0,0 +1,221 @@
+import { mockNuxtImport, registerEndpoint } from '@nuxt/test-utils/runtime'
+import { AuthApiError, AuthRetryableFetchError } from '@supabase/supabase-js'
+import { createError, getHeader, getQuery, readBody, setResponseStatus, type H3Event } from 'h3'
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+import { useSessionStore } from '../../stores/session'
+import { apiErrorKey } from '../errorKeys'
+import { useApi } from '../useApi'
+import { createFakeAuth } from './fake-auth'
+import { resetSession } from './reset-session'
+
+const supabase = vi.hoisted(() => ({ auth: undefined as unknown }))
+mockNuxtImport('useSupabaseAuth', () => () => supabase.auth)
+
+let fake: ReturnType
+// Removes the mocked endpoints of a test.
+let removals: (() => void)[] = []
+
+function mockEndpoint(path: string, handler: (event: H3Event) => unknown) {
+ const spy = vi.fn(handler)
+ removals.push(registerEndpoint(path, spy))
+ return spy
+}
+
+// An error response in the shape the backend sends: { data: { code } }.
+function apiFailure(statusCode: number, code: string) {
+ return createError({ statusCode, data: { code } })
+}
+
+// Accepts only the given token, like a backend after the old token has expired.
+function acceptOnly(token: string) {
+ return (event: H3Event) => {
+ if (getHeader(event, 'authorization') !== `Bearer ${token}`) {
+ throw apiFailure(401, 'unauthorized')
+ }
+ return { ok: true }
+ }
+}
+
+const currentRoute = () => useRouter().currentRoute.value
+
+async function signedInOnMapPage() {
+ fake = createFakeAuth({ signedInAs: 'ann@example.org' })
+ supabase.auth = fake.auth
+ resetSession()
+ await useRouter().push('/map')
+}
+
+beforeEach(async () => {
+ await useNuxtApp().$i18n.setLocale('de')
+ await signedInOnMapPage()
+})
+
+afterEach(() => {
+ removals.forEach(remove => remove())
+ removals = []
+ vi.unstubAllGlobals()
+})
+
+describe('requests', () => {
+ test('send the access token and ask for JSON', async () => {
+ const endpoint = mockEndpoint('/api/space', event => ({
+ authorization: getHeader(event, 'authorization'),
+ accept: getHeader(event, 'accept'),
+ }))
+
+ await expect(useApi()('/api/space')).resolves.toEqual({
+ authorization: 'Bearer token-1',
+ accept: 'application/json',
+ })
+ expect(endpoint).toHaveBeenCalledTimes(1)
+ })
+
+ test('pass on method, body and query', async () => {
+ mockEndpoint('/api/dates', async event => ({
+ method: event.method,
+ query: getQuery(event),
+ body: await readBody(event),
+ }))
+
+ await expect(useApi()('/api/dates', { method: 'POST', query: { status: 'done' }, body: { title: 'Picnic' } }))
+ .resolves.toEqual({ method: 'POST', query: { status: 'done' }, body: { title: 'Picnic' } })
+ })
+
+ test('work with an empty response', async () => {
+ mockEndpoint('/api/dates/1', (event) => {
+ setResponseStatus(event, 204)
+ return null
+ })
+
+ await expect(useApi()('/api/dates/1', { method: 'DELETE' })).resolves.toBeFalsy()
+ })
+})
+
+describe('an expired token (401)', () => {
+ test('is renewed once, and the request is repeated', async () => {
+ const endpoint = mockEndpoint('/api/space', acceptOnly('token-2'))
+
+ await expect(useApi()('/api/space')).resolves.toEqual({ ok: true })
+
+ expect(fake.auth.refreshSession).toHaveBeenCalledTimes(1)
+ expect(endpoint).toHaveBeenCalledTimes(2)
+ expect(useSessionStore().isSignedIn).toBe(true)
+ })
+
+ test('is renewed only once for requests that run at the same time', async () => {
+ mockEndpoint('/api/space', acceptOnly('token-2'))
+ const api = useApi()
+
+ await Promise.all([api('/api/space'), api('/api/space'), api('/api/space')])
+
+ expect(fake.auth.refreshSession).toHaveBeenCalledTimes(1)
+ })
+
+ test('ends the session when the new token is rejected too', async () => {
+ const endpoint = mockEndpoint('/api/space', () => {
+ throw apiFailure(401, 'unauthorized')
+ })
+
+ await expect(useApi()('/api/space')).rejects.toMatchObject({ code: 'unauthorized', status: 401 })
+
+ expect(endpoint).toHaveBeenCalledTimes(2)
+ expect(useSessionStore().isSignedIn).toBe(false)
+ expect(currentRoute().path).toBe('/login')
+ expect(currentRoute().query.redirect).toBe('/map')
+ })
+
+ test('keeps the return page when several requests fail at the same time', async () => {
+ mockEndpoint('/api/space', () => {
+ throw apiFailure(401, 'unauthorized')
+ })
+ const api = useApi()
+
+ await Promise.allSettled([api('/api/space'), api('/api/space'), api('/api/space')])
+
+ expect(currentRoute().path).toBe('/login')
+ expect(currentRoute().query.redirect).toBe('/map')
+ })
+
+ test('ends the session when the token cannot be renewed', async () => {
+ const endpoint = mockEndpoint('/api/space', acceptOnly('token-2'))
+ fake.auth.refreshSession.mockResolvedValueOnce({
+ data: { session: null },
+ error: new AuthApiError('Invalid refresh token', 400, 'refresh_token_not_found'),
+ })
+
+ await expect(useApi()('/api/space')).rejects.toMatchObject({ code: 'unauthorized' })
+
+ expect(endpoint).toHaveBeenCalledTimes(1)
+ expect(useSessionStore().isSignedIn).toBe(false)
+ expect(currentRoute().path).toBe('/login')
+ })
+
+ test('keeps the session when renewing fails because the server is unreachable', async () => {
+ mockEndpoint('/api/space', acceptOnly('token-2'))
+ fake.auth.refreshSession.mockResolvedValueOnce({
+ data: { session: null },
+ error: new AuthRetryableFetchError('offline', 0),
+ })
+
+ await expect(useApi()('/api/space')).rejects.toMatchObject({ messageKey: 'errors.network' })
+
+ expect(useSessionStore().isSignedIn).toBe(true)
+ expect(currentRoute().path).toBe('/map')
+ })
+})
+
+describe('without a session', () => {
+ test('goes to the login page without calling the API', async () => {
+ const endpoint = mockEndpoint('/api/space', () => ({ ok: true }))
+ const api = useApi()
+ fake.endSession()
+ fake.auth.getSession.mockResolvedValue({ data: { session: null }, error: null })
+
+ await expect(api('/api/space')).rejects.toMatchObject({ code: 'unauthorized' })
+
+ expect(endpoint).not.toHaveBeenCalled()
+ expect(currentRoute().path).toBe('/login')
+ })
+})
+
+describe('errors', () => {
+ test.each([
+ [400, 'invite_invalid'],
+ [409, 'already_paired'],
+ [403, 'no_space'],
+ [404, 'not_found'],
+ [400, 'validation_failed'],
+ [500, 'internal'],
+ ])('%i %s is translated through its code', async (status, code) => {
+ mockEndpoint('/api/space', () => {
+ throw apiFailure(status, code)
+ })
+
+ await expect(useApi()('/api/space')).rejects.toMatchObject({
+ name: 'ApiError',
+ code,
+ status,
+ messageKey: apiErrorKey(code),
+ })
+ expect(currentRoute().path).toBe('/map')
+ })
+
+ test('without a code from the backend get the general message', async () => {
+ // Hosting limits, for example, answer without the error envelope.
+ mockEndpoint('/api/photos', () => {
+ throw createError({ statusCode: 413 })
+ })
+
+ await expect(useApi()('/api/photos')).rejects.toMatchObject({
+ code: undefined,
+ status: 413,
+ messageKey: 'errors.unexpected',
+ })
+ })
+
+ test('from an unreachable API are reported as a network problem', async () => {
+ vi.stubGlobal('$fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')))
+
+ await expect(useApi()('/api/space')).rejects.toMatchObject({ messageKey: 'errors.network' })
+ })
+})
diff --git a/composables/__tests__/useLeaveWhenSignedOut.nuxt.spec.ts b/composables/__tests__/useLeaveWhenSignedOut.nuxt.spec.ts
new file mode 100644
index 0000000..4ce1e9a
--- /dev/null
+++ b/composables/__tests__/useLeaveWhenSignedOut.nuxt.spec.ts
@@ -0,0 +1,67 @@
+import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
+import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+import { useSessionStore } from '../../stores/session'
+import { useLeaveWhenSignedOut } from '../useLeaveWhenSignedOut'
+import { createFakeAuth } from './fake-auth'
+import { resetSession } from './reset-session'
+
+const supabase = vi.hoisted(() => ({ auth: undefined as unknown }))
+mockNuxtImport('useSupabaseAuth', () => () => supabase.auth)
+
+// Stops the watchers of one test before the next one starts.
+enableAutoUnmount(afterEach)
+
+let fake: ReturnType
+
+beforeEach(async () => {
+ fake = createFakeAuth({ signedInAs: 'ann@example.org' })
+ supabase.auth = fake.auth
+ resetSession()
+ await useNuxtApp().$i18n.setLocale('de')
+ await useRouter().push('/')
+})
+
+// Any component that uses the composable; the app calls it once in app.vue.
+const Host = defineComponent({
+ setup() {
+ useLeaveWhenSignedOut()
+ return () => null
+ },
+})
+
+async function openPage(path: string) {
+ await mountSuspended(Host, { route: path })
+ await useSessionStore().init()
+}
+
+const currentRoute = () => useRouter().currentRoute.value
+
+describe('useLeaveWhenSignedOut', () => {
+ test('leaves a protected page when the session ends elsewhere, and remembers the page', async () => {
+ await openPage('/map')
+
+ fake.endSession()
+
+ await vi.waitFor(() => expect(currentRoute().path).toBe('/login'))
+ expect(currentRoute().query.redirect).toBe('/map')
+ })
+
+ test('goes to a plain login page after pressing sign out', async () => {
+ await openPage('/en/map')
+
+ await useSessionStore().signOut()
+
+ await vi.waitFor(() => expect(currentRoute().path).toBe('/en/login'))
+ expect(currentRoute().query.redirect).toBeUndefined()
+ })
+
+ test('stays on a public page', async () => {
+ await openPage('/')
+
+ fake.endSession()
+ await flushPromises()
+
+ expect(currentRoute().path).toBe('/')
+ })
+})
diff --git a/composables/errorKeys.ts b/composables/errorKeys.ts
new file mode 100644
index 0000000..73108fe
--- /dev/null
+++ b/composables/errorKeys.ts
@@ -0,0 +1,48 @@
+import type { ApiErrorCode } from '../shared/api-errors'
+
+// Maps error codes to message keys. Text sent by a server is never shown.
+const unexpected = 'errors.unexpected'
+
+// Codes of our backend (shared/api-errors.ts). Only the type is imported,
+// so the validation library behind it stays out of the browser bundle.
+const apiMessages: Record = {
+ invite_invalid: 'errors.api.inviteInvalid',
+ already_paired: 'errors.api.alreadyPaired',
+ no_space: 'errors.api.noSpace',
+ not_found: 'errors.api.notFound',
+ validation_failed: 'errors.api.validationFailed',
+ unauthorized: 'errors.api.unauthorized',
+ internal: 'errors.api.internal',
+}
+
+// Codes of Supabase Auth, plus "network" and "unavailable" from the session store.
+const authMessages: Record = {
+ invalid_credentials: 'errors.auth.invalidCredentials',
+ email_not_confirmed: 'errors.auth.emailNotConfirmed',
+ user_already_exists: 'errors.auth.userExists',
+ email_exists: 'errors.auth.userExists',
+ email_address_invalid: 'errors.auth.emailInvalid',
+ weak_password: 'errors.auth.weakPassword',
+ signup_disabled: 'errors.auth.signupDisabled',
+ email_provider_disabled: 'errors.auth.methodDisabled',
+ provider_disabled: 'errors.auth.methodDisabled',
+ oauth_provider_not_supported: 'errors.auth.methodDisabled',
+ validation_failed: 'errors.auth.rejected',
+ over_request_rate_limit: 'errors.auth.tooManyAttempts',
+ over_email_send_rate_limit: 'errors.auth.tooManyAttempts',
+ network: 'errors.network',
+ unavailable: 'errors.auth.unavailable',
+}
+
+function lookUp(messages: Record, code: string | undefined) {
+ // hasOwn keeps names such as "toString" from matching.
+ return code && Object.hasOwn(messages, code) ? messages[code]! : unexpected
+}
+
+export function apiErrorKey(code: string | undefined) {
+ return lookUp(apiMessages, code)
+}
+
+export function authErrorKey(code: string | undefined) {
+ return lookUp(authMessages, code)
+}
diff --git a/composables/formRules.ts b/composables/formRules.ts
new file mode 100644
index 0000000..e7c44f7
--- /dev/null
+++ b/composables/formRules.ts
@@ -0,0 +1,28 @@
+// Checks that run in the browser before anything is sent. Supabase checks again.
+// Each function returns a message key, or undefined if the value is fine.
+
+// Supabase recommends at least 8 characters. minimum_password_length in
+// supabase/config.toml has to say the same; a test compares both.
+export const PASSWORD_MIN_LENGTH = 8
+
+// Something, an @, something, a dot, something; no spaces.
+const emailShape = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
+
+export function emailError(value: string) {
+ const email = value.trim()
+ if (!email) {
+ return 'errors.form.emailRequired'
+ }
+ return emailShape.test(email) ? undefined : 'errors.form.emailInvalid'
+}
+
+// For signing in: old passwords are not measured against today's rules.
+export function passwordError(value: string) {
+ return value ? undefined : 'errors.form.passwordRequired'
+}
+
+// For choosing a password.
+export function newPasswordError(value: string) {
+ return passwordError(value)
+ ?? (value.length < PASSWORD_MIN_LENGTH ? 'errors.form.passwordTooShort' : undefined)
+}
diff --git a/composables/safeRedirect.ts b/composables/safeRedirect.ts
new file mode 100644
index 0000000..943b175
--- /dev/null
+++ b/composables/safeRedirect.ts
@@ -0,0 +1,20 @@
+// Pages that are part of signing in, with or without a language prefix.
+const signInPage = /^(\/(en|nl))?\/(login|register|auth)(\/|$)/
+
+// A made-up address that only serves to resolve paths. It never receives a request.
+const base = 'http://app.invalid'
+
+// Returns the "redirect" query value if it is a path inside this app, otherwise the fallback.
+// Anybody can write that value into a link, so everything unusual is rejected.
+export function safeRedirect(value: unknown, fallback: string): string {
+ // A path inside the app starts with exactly one slash and contains no backslash.
+ if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') || value.includes('\\')) {
+ return fallback
+ }
+ // URL parsing removes tabs, line breaks and "..", the same way the browser does.
+ const url = new URL(value, base)
+ if (url.origin !== base || url.pathname.startsWith('//') || signInPage.test(url.pathname)) {
+ return fallback
+ }
+ return `${url.pathname}${url.search}${url.hash}`
+}
diff --git a/composables/useApi.ts b/composables/useApi.ts
new file mode 100644
index 0000000..195dec3
--- /dev/null
+++ b/composables/useApi.ts
@@ -0,0 +1,120 @@
+import type { ApiErrorCode } from '../shared/api-errors'
+
+// A failed API call. Show it with t(error.messageKey).
+export class ApiError extends Error {
+ readonly messageKey: string
+
+ constructor(
+ // The backend code, if the response carried one.
+ readonly code: ApiErrorCode | undefined,
+ // The HTTP status, or undefined if no response arrived.
+ readonly status: number | undefined,
+ messageKey?: string,
+ ) {
+ super(code ?? `request failed with status ${status ?? 'unknown'}`)
+ this.name = 'ApiError'
+ this.messageKey = messageKey ?? apiErrorKey(code)
+ }
+}
+
+export interface ApiOptions {
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
+ query?: Record
+ body?: Record | Blob
+ headers?: Record
+}
+
+// The shape of the errors that $fetch throws.
+interface FetchFailure {
+ status?: number
+ data?: { data?: { code?: ApiErrorCode } }
+}
+
+const unauthorized = () => new ApiError('unauthorized', 401)
+const networkProblem = () => new ApiError(undefined, undefined, 'errors.network')
+
+function toApiError(error: unknown) {
+ const { status, data } = error as FetchFailure
+ // Without a status there was no response at all.
+ return status ? new ApiError(data?.data?.code, status) : networkProblem()
+}
+
+// The only way the app calls /api/*: it adds the access token and handles 401 and errors.
+// const api = useApi()
+// const dates = await api('/api/dates', { query: { status: 'done' } })
+export function useApi() {
+ const session = useSessionStore()
+ const router = useRouter()
+ const goToLogin = useLoginRedirect()
+
+ function send(path: `/api/${string}`, options: ApiOptions, token: string) {
+ return $fetch(path, {
+ ...options,
+ headers: { ...options.headers, Accept: 'application/json', Authorization: `Bearer ${token}` },
+ }) as Promise
+ }
+
+ // The session is over: forget it and ask to sign in again.
+ async function leave() {
+ const page = router.currentRoute.value
+ await session.expire()
+ // Another request may already have sent us to the login page.
+ // Going there again would lose the page to return to.
+ if (router.currentRoute.value.meta.access !== 'guest') {
+ await goToLogin(page.fullPath)
+ }
+ return unauthorized()
+ }
+
+ // Returns a token that differs from the rejected one, or null if there is none.
+ async function newerToken(rejected: string) {
+ // Another request may have renewed the token in the meantime.
+ const current = await session.accessToken()
+ if (current && current !== rejected) {
+ return current
+ }
+ return session.refresh()
+ }
+
+ // Turns problems while talking to Supabase into the same error type.
+ async function reachable(step: Promise) {
+ try {
+ return await step
+ }
+ catch {
+ throw networkProblem()
+ }
+ }
+
+ return async function api(path: `/api/${string}`, options: ApiOptions = {}): Promise {
+ await session.init()
+ const token = await reachable(session.accessToken())
+ if (!token) {
+ throw await leave()
+ }
+
+ try {
+ return await send(path, options, token)
+ }
+ catch (error) {
+ if ((error as FetchFailure).status !== 401) {
+ throw toApiError(error)
+ }
+ }
+
+ // One attempt with a renewed token.
+ const renewed = await reachable(newerToken(token))
+ if (!renewed) {
+ throw await leave()
+ }
+ try {
+ return await send(path, options, renewed)
+ }
+ catch (error) {
+ if ((error as FetchFailure).status === 401) {
+ throw await leave()
+ }
+ throw toApiError(error)
+ }
+ }
+}
diff --git a/composables/useLeaveWhenSignedOut.ts b/composables/useLeaveWhenSignedOut.ts
new file mode 100644
index 0000000..3a2ccdf
--- /dev/null
+++ b/composables/useLeaveWhenSignedOut.ts
@@ -0,0 +1,17 @@
+// Leaves a protected page as soon as its session ends: after "sign out",
+// after a sign-out in another tab, or when the session expires. app.vue calls this once.
+export function useLeaveWhenSignedOut() {
+ const session = useSessionStore()
+ const router = useRouter()
+ const goToLogin = useLoginRedirect()
+
+ watch(() => session.status, (status, previous) => {
+ const route = router.currentRoute.value
+ // Pages that set "access" are open to signed-out visitors.
+ if (previous !== 'signedIn' || status !== 'signedOut' || route.meta.access) {
+ return
+ }
+ // After pressing "sign out" nobody expects to be brought back to this page.
+ goToLogin(session.signedOutByUser ? undefined : route.fullPath)
+ })
+}
diff --git a/composables/useLoginRedirect.ts b/composables/useLoginRedirect.ts
new file mode 100644
index 0000000..cc2093d
--- /dev/null
+++ b/composables/useLoginRedirect.ts
@@ -0,0 +1,13 @@
+// The one way to send somebody to the login page.
+export function useLoginRedirect() {
+ const localePath = useLocalePath()
+
+ // returnTo is the page to come back to after signing in.
+ // language is needed during a navigation, before the app has switched to the target language.
+ return function goToLogin(returnTo?: string, language?: 'de' | 'en' | 'nl') {
+ return navigateTo({
+ path: localePath('/login', language),
+ query: returnTo ? { redirect: returnTo } : {},
+ })
+ }
+}
diff --git a/composables/useReturnTarget.ts b/composables/useReturnTarget.ts
new file mode 100644
index 0000000..1baa21d
--- /dev/null
+++ b/composables/useReturnTarget.ts
@@ -0,0 +1,22 @@
+// Where to go after signing in: the page named in "?redirect=", or else the dashboard,
+// in the language of the page the person signed in on.
+export function useReturnTarget() {
+ const router = useRouter()
+ const localePath = useLocalePath()
+ const routeBaseName = useRouteBaseName()
+
+ // language is needed during a navigation, before the app has switched to it.
+ return function returnTarget(requested: unknown, language?: 'de' | 'en' | 'nl') {
+ const path = safeRedirect(requested, '')
+ if (!path) {
+ return localePath('/dashboard', language)
+ }
+ const target = router.resolve(path)
+ // The page name without its language, for example "map". Unknown addresses have none.
+ const name = routeBaseName(target)
+ if (!name) {
+ return path
+ }
+ return localePath({ name, params: target.params, query: target.query, hash: target.hash }, language)
+ }
+}
diff --git a/composables/useSupabaseAuth.ts b/composables/useSupabaseAuth.ts
new file mode 100644
index 0000000..ea6a900
--- /dev/null
+++ b/composables/useSupabaseAuth.ts
@@ -0,0 +1,23 @@
+import type { SupabaseClient } from '@supabase/supabase-js'
+
+// This file is the one place that reaches Supabase Auth.
+
+// The client comes from plugins/auth.client.ts, so it exists only in the browser
+// and only when the app is configured.
+export function useSupabaseAuth(): SupabaseClient['auth'] | undefined {
+ const supabase = useNuxtApp().$supabase as SupabaseClient | undefined
+ return supabase?.auth
+}
+
+// Asks whether a sign-in provider is switched on. supabase-js has no call for this, and
+// without the check a switched-off provider leaves the browser on a page with a raw error.
+export function useProviderCheck() {
+ const { supabaseUrl, supabaseKey } = useRuntimeConfig().public
+
+ return async function isProviderEnabled(provider: 'google') {
+ const settings = await $fetch<{ external?: Record }>(`${supabaseUrl}/auth/v1/settings`, {
+ headers: { apikey: supabaseKey },
+ })
+ return settings.external?.[provider] === true
+ }
+}
diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md
index 15a1f66..a1fd25c 100644
--- a/docs/BACKLOG.md
+++ b/docs/BACKLOG.md
@@ -1,4 +1,10 @@
-# Backend backlog
+# Backlog
+
+## Frontend
+
+- **F2 Auth** (register, login, Google sign-in, logout, route protection): claimed by `Filionus`, branch `feat/auth`, in progress.
+
+## Backend
Findings from the first backend review, in the order we want to work through them.
Status of the backend at review time: `npm test` and `npm run build` pass; API not yet tested against a real Supabase project.
diff --git a/i18n/__tests__/persistence.spec.ts b/i18n/__tests__/persistence.spec.ts
index c1decd8..d115c17 100644
--- a/i18n/__tests__/persistence.spec.ts
+++ b/i18n/__tests__/persistence.spec.ts
@@ -61,25 +61,29 @@ describe('returning visit', () => {
})
test('a saved German choice stays German in a foreign-language browser', async () => {
- const response = await visit('/dates', { saved: 'de', browser: 'en-GB' })
- expect(response.status).toBe(200)
- expect(response.body).toContain('lang="de-DE"')
+ const landing = await visit('/', { saved: 'de', browser: 'en-GB' })
+ expect(landing.status).toBe(200)
+ expect(landing.body).toContain('lang="de-DE"')
+
+ const appPage = await visit('/dates', { saved: 'de', browser: 'en-GB' })
+ expect(appPage.status).toBe(200)
+ expect(appPage.location).toBeNull()
})
test('a language prefix in the URL wins and becomes the saved language', async () => {
- const response = await visit('/en/dates', { saved: 'nl' })
+ const response = await visit('/en', { saved: 'nl' })
expect(response.status).toBe(200)
expect(response.body).toContain('lang="en-GB"')
expect(response.cookie).toContain('ons_locale=en')
})
})
-describe('server-rendered pages', () => {
+describe('the landing page', () => {
test.each([
- ['/map', 'de-DE', 'Karte'],
- ['/en/map', 'en-GB', 'Map'],
- ['/nl/map', 'nl-NL', 'Kaart'],
- ])('%s is rendered in %s', async (path, language, heading) => {
+ ['/', 'de-DE', 'Start'],
+ ['/en', 'en-GB', 'Home'],
+ ['/nl', 'nl-NL', 'Home'],
+ ])('%s is rendered on the server in %s', async (path, language, heading) => {
const response = await visit(path, { saved: language.slice(0, 2) })
expect(response.status).toBe(200)
expect(response.body).toContain(`lang="${language}"`)
@@ -87,14 +91,39 @@ describe('server-rendered pages', () => {
expect(response.body).toContain(`${heading} · Ons`)
})
- test.each(['/', '/dates', '/map', '/photos'])('%s exists', async (path) => {
- const response = await visit(path, { saved: 'de' })
+ test('contains no SEO link tags yet, because those need a fixed base URL (F10)', async () => {
+ const response = await visit('/', { saved: 'de' })
+ expect(response.body).not.toMatch(/]+rel="(alternate|canonical)"/)
+ })
+})
+
+describe('app and sign-in pages', () => {
+ // Only the browser knows the session, so the server sends an empty page shell.
+ test.each([
+ '/dashboard',
+ '/dates',
+ '/map',
+ '/photos',
+ '/en/dates',
+ '/login',
+ '/register',
+ ])('%s is rendered in the browser only', async (path) => {
+ const response = await visit(path, { saved: path.startsWith('/en/') ? 'en' : 'de' })
expect(response.status).toBe(200)
+ expect(response.body).not.toContain('
{
- const response = await visit('/', { saved: 'de' })
- expect(response.body).not.toMatch(/]+rel="(alternate|canonical)"/)
+describe('the sign-in return page', () => {
+ // Supabase only returns to addresses on its allow list, so there is just one.
+ test.each([
+ ['a saved English choice', { saved: 'en', browser: 'en-GB' }],
+ ['a saved Dutch choice', { saved: 'nl' }],
+ ['a Dutch browser on the first visit', { browser: 'nl-NL' }],
+ ])('is not redirected to a language prefix: %s', async (_visitor, visitor) => {
+ const response = await visit('/auth/callback?code=abc', visitor)
+ expect(response.status).toBe(200)
+ expect(response.location).toBeNull()
})
})
diff --git a/i18n/__tests__/route-macro.spec.ts b/i18n/__tests__/route-macro.spec.ts
new file mode 100644
index 0000000..eaeaf33
--- /dev/null
+++ b/i18n/__tests__/route-macro.spec.ts
@@ -0,0 +1,31 @@
+import { readdirSync, readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { expect, test } from 'vitest'
+
+// The route macro of @nuxtjs/i18n rewrites a page and leaves two versions of its source
+// behind. On Linux the test build then stops with "Multiple conflicting contents for
+// sourcemap source". Windows does not show this, so this check reads the files.
+// To leave a page without language prefixes, list it under i18n.pages in nuxt.config.ts.
+
+// The plugin also rewrites a call that only appears in a comment.
+const macroCall = /\bdefineI18nRoute\s*\(/
+
+const root = fileURLToPath(new URL('../../', import.meta.url))
+
+const vueFiles = [
+ 'app.vue',
+ ...['components', 'layouts', 'pages'].flatMap(folder =>
+ readdirSync(join(root, folder), { recursive: true, encoding: 'utf8' })
+ .filter(name => name.endsWith('.vue'))
+ .map(name => `${folder}/${name.replaceAll('\\', '/')}`),
+ ),
+]
+
+test('no page or component calls the i18n route macro', () => {
+ // Makes sure the search really looked at the pages.
+ expect(vueFiles).toContain('pages/auth/callback.vue')
+
+ const callers = vueFiles.filter(file => macroCall.test(readFileSync(join(root, file), 'utf8')))
+ expect(callers, 'list the page under i18n.pages in nuxt.config.ts instead').toEqual([])
+})
diff --git a/i18n/locales/de.json b/i18n/locales/de.json
index 3ea0ba5..7c16bee 100644
--- a/i18n/locales/de.json
+++ b/i18n/locales/de.json
@@ -4,7 +4,7 @@
},
"nav": {
"label": "Hauptnavigation",
- "home": "Start",
+ "dashboard": "Übersicht",
"dates": "Dates",
"map": "Karte",
"photos": "Fotos"
@@ -32,6 +32,67 @@
},
"photos": {
"title": "Fotos"
+ },
+ "dashboard": {
+ "title": "Übersicht"
+ },
+ "login": {
+ "title": "Anmelden"
+ },
+ "register": {
+ "title": "Registrieren"
+ },
+ "callback": {
+ "title": "Anmeldung"
+ }
+ },
+ "errors": {
+ "unexpected": "Etwas ist schiefgelaufen. Bitte versuche es erneut.",
+ "network": "Keine Verbindung zum Server. Prüfe deine Internetverbindung und versuche es erneut.",
+ "api": {
+ "inviteInvalid": "Diese Einladung ist ungültig oder wurde schon benutzt.",
+ "alreadyPaired": "Du gehörst bereits zu einem gemeinsamen Bereich.",
+ "noSpace": "Erstelle zuerst einen gemeinsamen Bereich oder tritt einem bei.",
+ "notFound": "Dieser Eintrag wurde nicht gefunden.",
+ "validationFailed": "Bitte prüfe deine Eingaben.",
+ "unauthorized": "Deine Anmeldung ist abgelaufen. Bitte melde dich erneut an.",
+ "internal": "Der Server hat gerade ein Problem. Bitte versuche es später erneut."
+ },
+ "auth": {
+ "invalidCredentials": "E-Mail-Adresse oder Passwort ist falsch.",
+ "emailNotConfirmed": "Bitte bestätige zuerst deine E-Mail-Adresse über den Link in unserer E-Mail.",
+ "userExists": "Für diese E-Mail-Adresse gibt es schon ein Konto. Melde dich stattdessen an.",
+ "emailInvalid": "Diese E-Mail-Adresse wird nicht akzeptiert.",
+ "weakPassword": "Dieses Passwort ist zu schwach. Wähle ein längeres.",
+ "signupDisabled": "Neue Registrierungen sind derzeit nicht möglich.",
+ "methodDisabled": "Diese Anmeldeart ist derzeit nicht verfügbar.",
+ "rejected": "Die Anmeldung wurde abgelehnt. Bitte prüfe deine Eingaben.",
+ "tooManyAttempts": "Zu viele Versuche. Bitte warte kurz und versuche es erneut.",
+ "unavailable": "Die Anmeldung ist derzeit nicht verfügbar."
+ },
+ "form": {
+ "emailRequired": "Bitte gib deine E-Mail-Adresse ein.",
+ "emailInvalid": "Das ist keine gültige E-Mail-Adresse.",
+ "passwordRequired": "Bitte gib dein Passwort ein.",
+ "passwordTooShort": "Das Passwort braucht mindestens {min} Zeichen."
+ }
+ },
+ "auth": {
+ "email": "E-Mail-Adresse",
+ "password": "Passwort",
+ "passwordHint": "Mindestens {min} Zeichen.",
+ "signIn": "Anmelden",
+ "createAccount": "Konto erstellen",
+ "google": "Mit Google fortfahren",
+ "noAccount": "Noch kein Konto? Registrieren",
+ "haveAccount": "Schon ein Konto? Anmelden",
+ "confirmationSent": "Fast geschafft: Wir haben einen Bestätigungslink an {email} geschickt. Öffne ihn am besten in diesem Browser.",
+ "signOut": "Abmelden",
+ "callback": {
+ "working": "Anmeldung wird abgeschlossen …",
+ "rejected": "Die Anmeldung wurde abgebrochen oder abgelehnt.",
+ "incomplete": "Wir konnten dich nicht automatisch anmelden. Wenn du gerade deine E-Mail-Adresse bestätigt hast, melde dich jetzt einfach an.",
+ "toLogin": "Zur Anmeldung"
}
}
}
diff --git a/i18n/locales/en.json b/i18n/locales/en.json
index 61e5ef3..cd16991 100644
--- a/i18n/locales/en.json
+++ b/i18n/locales/en.json
@@ -4,7 +4,7 @@
},
"nav": {
"label": "Main navigation",
- "home": "Home",
+ "dashboard": "Overview",
"dates": "Dates",
"map": "Map",
"photos": "Photos"
@@ -32,6 +32,67 @@
},
"photos": {
"title": "Photos"
+ },
+ "dashboard": {
+ "title": "Overview"
+ },
+ "login": {
+ "title": "Sign in"
+ },
+ "register": {
+ "title": "Create account"
+ },
+ "callback": {
+ "title": "Signing in"
+ }
+ },
+ "errors": {
+ "unexpected": "Something went wrong. Please try again.",
+ "network": "The server cannot be reached. Check your internet connection and try again.",
+ "api": {
+ "inviteInvalid": "This invitation is invalid or has already been used.",
+ "alreadyPaired": "You already belong to a shared space.",
+ "noSpace": "Create or join a shared space first.",
+ "notFound": "This entry was not found.",
+ "validationFailed": "Please check what you entered.",
+ "unauthorized": "Your session has ended. Please sign in again.",
+ "internal": "The server has a problem right now. Please try again later."
+ },
+ "auth": {
+ "invalidCredentials": "The email address or password is wrong.",
+ "emailNotConfirmed": "Please confirm your email address first, using the link we sent you.",
+ "userExists": "There is already an account for this email address. Sign in instead.",
+ "emailInvalid": "This email address is not accepted.",
+ "weakPassword": "This password is too weak. Choose a longer one.",
+ "signupDisabled": "New registrations are not possible at the moment.",
+ "methodDisabled": "This way of signing in is not available at the moment.",
+ "rejected": "Sign-in was rejected. Please check what you entered.",
+ "tooManyAttempts": "Too many attempts. Please wait a moment and try again.",
+ "unavailable": "Sign-in is not available at the moment."
+ },
+ "form": {
+ "emailRequired": "Please enter your email address.",
+ "emailInvalid": "That is not a valid email address.",
+ "passwordRequired": "Please enter your password.",
+ "passwordTooShort": "The password needs at least {min} characters."
+ }
+ },
+ "auth": {
+ "email": "Email address",
+ "password": "Password",
+ "passwordHint": "At least {min} characters.",
+ "signIn": "Sign in",
+ "createAccount": "Create account",
+ "google": "Continue with Google",
+ "noAccount": "No account yet? Create one",
+ "haveAccount": "Already have an account? Sign in",
+ "confirmationSent": "Almost done: we sent a confirmation link to {email}. Open it in this browser if you can.",
+ "signOut": "Sign out",
+ "callback": {
+ "working": "Finishing your sign-in …",
+ "rejected": "The sign-in was cancelled or rejected.",
+ "incomplete": "We could not sign you in automatically. If you have just confirmed your email address, simply sign in now.",
+ "toLogin": "Go to sign-in"
}
}
}
diff --git a/i18n/locales/nl.json b/i18n/locales/nl.json
index 580b348..b7d031b 100644
--- a/i18n/locales/nl.json
+++ b/i18n/locales/nl.json
@@ -4,7 +4,7 @@
},
"nav": {
"label": "Hoofdnavigatie",
- "home": "Home",
+ "dashboard": "Overzicht",
"dates": "Dates",
"map": "Kaart",
"photos": "Foto's"
@@ -32,6 +32,67 @@
},
"photos": {
"title": "Foto's"
+ },
+ "dashboard": {
+ "title": "Overzicht"
+ },
+ "login": {
+ "title": "Inloggen"
+ },
+ "register": {
+ "title": "Account aanmaken"
+ },
+ "callback": {
+ "title": "Inloggen"
+ }
+ },
+ "errors": {
+ "unexpected": "Er is iets misgegaan. Probeer het opnieuw.",
+ "network": "De server is niet bereikbaar. Controleer je internetverbinding en probeer het opnieuw.",
+ "api": {
+ "inviteInvalid": "Deze uitnodiging is ongeldig of al gebruikt.",
+ "alreadyPaired": "Je hoort al bij een gedeelde ruimte.",
+ "noSpace": "Maak eerst een gedeelde ruimte aan of sluit je bij een aan.",
+ "notFound": "Dit item is niet gevonden.",
+ "validationFailed": "Controleer je invoer.",
+ "unauthorized": "Je sessie is verlopen. Log opnieuw in.",
+ "internal": "De server heeft nu een probleem. Probeer het later opnieuw."
+ },
+ "auth": {
+ "invalidCredentials": "Het e-mailadres of wachtwoord klopt niet.",
+ "emailNotConfirmed": "Bevestig eerst je e-mailadres via de link die we je hebben gestuurd.",
+ "userExists": "Er bestaat al een account voor dit e-mailadres. Log in plaats daarvan in.",
+ "emailInvalid": "Dit e-mailadres wordt niet geaccepteerd.",
+ "weakPassword": "Dit wachtwoord is te zwak. Kies een langer wachtwoord.",
+ "signupDisabled": "Nieuwe registraties zijn op dit moment niet mogelijk.",
+ "methodDisabled": "Deze manier van inloggen is nu niet beschikbaar.",
+ "rejected": "Het inloggen is geweigerd. Controleer je invoer.",
+ "tooManyAttempts": "Te veel pogingen. Wacht even en probeer het opnieuw.",
+ "unavailable": "Inloggen is op dit moment niet beschikbaar."
+ },
+ "form": {
+ "emailRequired": "Vul je e-mailadres in.",
+ "emailInvalid": "Dit is geen geldig e-mailadres.",
+ "passwordRequired": "Vul je wachtwoord in.",
+ "passwordTooShort": "Het wachtwoord moet minstens {min} tekens hebben."
+ }
+ },
+ "auth": {
+ "email": "E-mailadres",
+ "password": "Wachtwoord",
+ "passwordHint": "Minstens {min} tekens.",
+ "signIn": "Inloggen",
+ "createAccount": "Account aanmaken",
+ "google": "Doorgaan met Google",
+ "noAccount": "Nog geen account? Maak er een aan",
+ "haveAccount": "Heb je al een account? Log in",
+ "confirmationSent": "Bijna klaar: we hebben een bevestigingslink naar {email} gestuurd. Open die het liefst in deze browser.",
+ "signOut": "Uitloggen",
+ "callback": {
+ "working": "Het inloggen wordt afgerond …",
+ "rejected": "Het inloggen is geannuleerd of geweigerd.",
+ "incomplete": "We konden je niet automatisch inloggen. Heb je net je e-mailadres bevestigd? Log dan nu gewoon in.",
+ "toLogin": "Naar inloggen"
}
}
}
diff --git a/layouts/__tests__/default.nuxt.spec.ts b/layouts/__tests__/default.nuxt.spec.ts
index fa0f606..a1624c7 100644
--- a/layouts/__tests__/default.nuxt.spec.ts
+++ b/layouts/__tests__/default.nuxt.spec.ts
@@ -1,25 +1,44 @@
-import { mountSuspended } from '@nuxt/test-utils/runtime'
-import { enableAutoUnmount } from '@vue/test-utils'
-import { afterEach, beforeEach, describe, expect, test } from 'vitest'
+import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
+import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+import { createFakeAuth } from '../../composables/__tests__/fake-auth'
+import { button } from '../../composables/__tests__/form-helpers'
+import { resetSession } from '../../composables/__tests__/reset-session'
import DefaultLayout from '../default.vue'
+const supabase = vi.hoisted(() => ({ auth: undefined as unknown }))
+mockNuxtImport('useSupabaseAuth', () => () => supabase.auth)
+
// The tests attach the layout to the page, so remove it again after each one.
enableAutoUnmount(afterEach)
+let fake: ReturnType
+
+function signInAs(email: string | undefined) {
+ fake = createFakeAuth({ signedInAs: email })
+ supabase.auth = fake.auth
+ resetSession()
+}
+
beforeEach(async () => {
+ signInAs(undefined)
await useNuxtApp().$i18n.setLocale('de')
await useRouter().push('/')
})
-function mountLayout() {
- return mountSuspended(DefaultLayout, {
+async function mountLayout() {
+ const wrapper = await mountSuspended(DefaultLayout, {
route: '/',
// Focus only works for elements that are part of the document.
attachTo: document.body,
slots: { default: () => 'page content' },
})
+ await flushPromises()
+ return wrapper
}
+const mainNavigation = 'nav[aria-label="Hauptnavigation"]'
+
describe('default layout', () => {
test('starts with a skip link to the main content', async () => {
const wrapper = await mountLayout()
@@ -42,10 +61,60 @@ describe('default layout', () => {
expect(wrapper.get('main').text()).toContain('page content')
})
- test('has a header with home link and language switcher, and one main navigation', async () => {
+ test.each([
+ ['signed out', undefined],
+ ['signed in', 'ann@example.org'],
+ ])('the language switcher in the header changes the language when %s', async (_state, email) => {
+ signInAs(email)
+ const wrapper = await mountLayout()
+
+ await wrapper.get('header a[data-locale="en"]').trigger('click')
+
+ await vi.waitFor(() => {
+ expect(wrapper.get('a[href="#main"]').text()).toBe('Skip to content')
+ expect(wrapper.get('header a[data-locale="en"]').attributes('aria-current')).toBe('true')
+ expect(useRouter().currentRoute.value.path).toBe('/en')
+ })
+ })
+
+ test('has a header with a home link and the language switcher', async () => {
const wrapper = await mountLayout()
expect(wrapper.get('header a[href="/"]').text()).toBe('Ons')
expect(wrapper.find('header nav[aria-label="Sprache"]').exists()).toBe(true)
- expect(wrapper.findAll('nav[aria-label="Hauptnavigation"]')).toHaveLength(1)
+ })
+
+ test('offers signing in, and no app navigation, to signed-out visitors', async () => {
+ const wrapper = await mountLayout()
+ expect(wrapper.get('header a[href="/login"]').text()).toBe('Anmelden')
+ expect(wrapper.find(mainNavigation).exists()).toBe(false)
+ expect(wrapper.findAll('header button')).toHaveLength(0)
+ })
+
+ test('shows one app navigation and a sign-out button when signed in', async () => {
+ signInAs('ann@example.org')
+ const wrapper = await mountLayout()
+ expect(wrapper.findAll(mainNavigation)).toHaveLength(1)
+ expect(button(wrapper, 'Abmelden').attributes('type')).toBe('button')
+ expect(wrapper.find('header a[href="/login"]').exists()).toBe(false)
+ })
+
+ test('signs out with the button', async () => {
+ signInAs('ann@example.org')
+ const wrapper = await mountLayout()
+
+ await button(wrapper, 'Abmelden').trigger('click')
+ await flushPromises()
+
+ expect(fake.auth.signOut).toHaveBeenCalledWith({ scope: 'local' })
+ expect(wrapper.find(mainNavigation).exists()).toBe(false)
+ expect(wrapper.find('header a[href="/login"]').exists()).toBe(true)
+ })
+
+ test('shows neither sign-in nor sign-out while the session is still unknown', async () => {
+ fake.auth.getSession.mockReturnValue(new Promise(() => {}))
+ fake.auth.onAuthStateChange.mockReturnValue({ data: { subscription: { unsubscribe: () => true } } })
+ const wrapper = await mountLayout()
+ expect(wrapper.find('header a[href="/login"]').exists()).toBe(false)
+ expect(wrapper.findAll('header button')).toHaveLength(0)
})
})
diff --git a/layouts/default.vue b/layouts/default.vue
index ccd52f7..233f33b 100644
--- a/layouts/default.vue
+++ b/layouts/default.vue
@@ -1,5 +1,10 @@
@@ -13,15 +18,20 @@ const { t } = useI18n()
>
{{ t('app.name') }}
-
+
+
+
+
-
+
+
diff --git a/middleware/__tests__/auth.nuxt.spec.ts b/middleware/__tests__/auth.nuxt.spec.ts
new file mode 100644
index 0000000..918e216
--- /dev/null
+++ b/middleware/__tests__/auth.nuxt.spec.ts
@@ -0,0 +1,89 @@
+import { mockNuxtImport } from '@nuxt/test-utils/runtime'
+import { beforeEach, describe, expect, test, vi } from 'vitest'
+import { createFakeAuth } from '../../composables/__tests__/fake-auth'
+import { resetSession } from '../../composables/__tests__/reset-session'
+
+const supabase = vi.hoisted(() => ({ auth: undefined as unknown }))
+mockNuxtImport('useSupabaseAuth', () => () => supabase.auth)
+
+const someone = 'ann@example.org'
+
+function signInAs(email: string | undefined) {
+ supabase.auth = createFakeAuth({ signedInAs: email }).auth
+ resetSession()
+}
+
+// Navigates like a link click and returns where the app ended up.
+async function visit(path: string) {
+ await useRouter().push(path)
+ return useRouter().currentRoute.value
+}
+
+// Every test starts signed out on the German landing page.
+beforeEach(async () => {
+ signInAs(undefined)
+ await useNuxtApp().$i18n.setLocale('de')
+ await useRouter().push('/')
+})
+
+describe('signed out', () => {
+ test.each(['/dashboard', '/dates', '/map', '/photos'])('%s leads to the login page and remembers the target', async (path) => {
+ const route = await visit(path)
+ expect(route.path).toBe('/login')
+ expect(route.query.redirect).toBe(path)
+ })
+
+ test.each([
+ ['/en/dates', '/en/login'],
+ ['/nl/map', '/nl/login'],
+ ])('%s keeps its language: %s', async (path, login) => {
+ const route = await visit(path)
+ expect(route.path).toBe(login)
+ expect(route.query.redirect).toBe(path)
+ })
+
+ test('remembers the query of the target', async () => {
+ const route = await visit('/dates?status=done')
+ expect(route.query.redirect).toBe('/dates?status=done')
+ })
+
+ test.each(['/', '/en', '/login', '/en/register', '/auth/callback'])('%s is open', async (path) => {
+ expect((await visit(path)).path).toBe(path)
+ })
+
+ test('protects pages when Supabase is not configured', async () => {
+ supabase.auth = undefined
+ resetSession()
+ expect((await visit('/dashboard')).path).toBe('/login')
+ })
+})
+
+describe('signed in', () => {
+ beforeEach(() => {
+ signInAs(someone)
+ })
+
+ test.each(['/dashboard', '/dates', '/en/map', '/nl/photos', '/', '/auth/callback'])('%s is open', async (path) => {
+ expect((await visit(path)).path).toBe(path)
+ })
+
+ test.each([
+ ['/login', '/dashboard'],
+ ['/register', '/dashboard'],
+ ['/en/login', '/en/dashboard'],
+ ])('%s leads on to %s', async (path, target) => {
+ expect((await visit(path)).path).toBe(target)
+ })
+
+ test('the login page leads on to the remembered target', async () => {
+ expect((await visit('/login?redirect=/map')).path).toBe('/map')
+ })
+
+ test('the login page leads on to the target in its own language', async () => {
+ expect((await visit('/en/login?redirect=/map')).path).toBe('/en/map')
+ })
+
+ test('the login page ignores a target outside the app', async () => {
+ expect((await visit('/login?redirect=https://evil.example')).path).toBe('/dashboard')
+ })
+})
diff --git a/middleware/auth.global.ts b/middleware/auth.global.ts
new file mode 100644
index 0000000..1c63032
--- /dev/null
+++ b/middleware/auth.global.ts
@@ -0,0 +1,40 @@
+// Every page needs a signed-in user, unless it says otherwise:
+// definePageMeta({ access: 'public' }) everybody
+// definePageMeta({ access: 'guest' }) only signed-out visitors (login, register)
+declare module '#app' {
+ interface PageMeta {
+ access?: 'public' | 'guest'
+ }
+}
+
+export default defineNuxtRouteMiddleware(async (to) => {
+ // The session lives in the browser, so the server cannot judge it.
+ // Protected pages are rendered in the browser only (see routeRules in nuxt.config.ts).
+ if (import.meta.server) {
+ return
+ }
+ // Public pages and unknown addresses (404) need no check.
+ if (to.meta.access === 'public' || to.matched.length === 0) {
+ return
+ }
+
+ // Composables must be called before the first "await".
+ const session = useSessionStore()
+ const returnTarget = useReturnTarget()
+ const goToLogin = useLoginRedirect()
+ // Route names end in the language, for example "dates___en".
+ const language = String(to.name).split('___')[1] as 'de' | 'en' | 'nl' | undefined
+
+ await session.init()
+
+ if (to.meta.access === 'guest') {
+ if (session.isSignedIn) {
+ return navigateTo(returnTarget(to.query.redirect, language))
+ }
+ return
+ }
+
+ if (!session.isSignedIn) {
+ return goToLogin(to.fullPath, language)
+ }
+})
diff --git a/nuxt.config.ts b/nuxt.config.ts
index 0c96639..ae5abf3 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -3,7 +3,7 @@ import tailwindcss from '@tailwindcss/vite'
export default defineNuxtConfig({
compatibilityDate: '2025-01-01',
devtools: { enabled: false },
- modules: ['@nuxtjs/i18n'],
+ modules: ['@nuxtjs/i18n', '@pinia/nuxt'],
css: ['~/assets/css/main.css'],
vite: { plugins: [tailwindcss()] },
i18n: {
@@ -16,6 +16,13 @@ export default defineNuxtConfig({
{ code: 'en', language: 'en-GB', name: 'English', file: 'en.json' },
{ code: 'nl', language: 'nl-NL', name: 'Nederlands', file: 'nl.json' },
],
+ // Pages without language prefixes are listed here. The route macro in the page itself
+ // breaks the build on Linux.
+ customRoutes: 'config',
+ pages: {
+ // Supabase only returns to addresses on its allow list, so there is just /auth/callback.
+ 'auth/callback': false,
+ },
// First visit: browser language, otherwise German. Later visits: the saved cookie.
detectBrowserLanguage: {
useCookie: true,
@@ -24,5 +31,13 @@ export default defineNuxtConfig({
fallbackLocale: 'de',
},
},
+ // The sign-in session lives in the browser, so pages are rendered there.
+ // Only the public landing page is rendered on the server, for search engines.
+ routeRules: {
+ '/**': { ssr: false },
+ '/': { ssr: true },
+ '/en': { ssr: true },
+ '/nl': { ssr: true },
+ },
runtimeConfig: { public: { supabaseUrl: '', supabaseKey: '' } }
})
diff --git a/package-lock.json b/package-lock.json
index 1ec03ea..c1fab97 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -7,8 +7,10 @@
"name": "ons-couple-planner",
"dependencies": {
"@nuxtjs/i18n": "10.2.3",
+ "@pinia/nuxt": "^0.11.3",
"@supabase/supabase-js": "^2.100.0",
"nuxt": "^3.21.11",
+ "pinia": "^3.0.4",
"zod": "^4.0.0"
},
"devDependencies": {
@@ -4574,6 +4576,128 @@
"inBundle": true,
"license": "MIT"
},
+ "node_modules/@pinia/nuxt": {
+ "version": "0.11.3",
+ "resolved": "https://registry.npmjs.org/@pinia/nuxt/-/nuxt-0.11.3.tgz",
+ "integrity": "sha512-7WVNHpWx4qAEzOlnyrRC88kYrwnlR/PrThWT0XI1dSNyUAXu/KBv9oR37uCgYkZroqP5jn8DfzbkNF3BtKvE9w==",
+ "license": "MIT",
+ "dependencies": {
+ "@nuxt/kit": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/posva"
+ },
+ "peerDependencies": {
+ "pinia": "^3.0.4"
+ }
+ },
+ "node_modules/@pinia/nuxt/node_modules/@nuxt/kit": {
+ "version": "4.7.0",
+ "resolved": "https://registry.npmjs.org/@nuxt/kit/-/kit-4.7.0.tgz",
+ "integrity": "sha512-78NsjcazI8PQPE0H8+mx+0c4Wm1GlvM5Oxj60sCHil0TUjTMjqRVMoORgJLPyPulMhD2Ih1rEZh5TEvXkytdLA==",
+ "license": "MIT",
+ "dependencies": {
+ "consola": "^3.4.2",
+ "defu": "^6.1.7",
+ "destr": "^2.0.5",
+ "errx": "^0.2.2",
+ "exsolve": "^1.2.0",
+ "ignore": "^7.0.16",
+ "klona": "^2.0.6",
+ "microdiff": "^1.6.0",
+ "nostics": "^1.4.0",
+ "package-manager-detector": "^1.9.0",
+ "pathe": "^2.0.3",
+ "rc9": "^3.1.0",
+ "rou3": "^1.0.0",
+ "scule": "^1.3.0",
+ "std-env": "^4.3.0",
+ "tinyexec": "^1.3.1",
+ "tinyglobby": "^0.2.17",
+ "unctx": "^3.0.1",
+ "verkit": "^0.5.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "peerDependencies": {
+ "@nuxt/schema": "^3.0.0 || ^4.0.0 || ^5.0.0-0",
+ "confbox": ">=0.1.0",
+ "dotenv": "*",
+ "giget": ">=3.1.0",
+ "jiti": "^2.0.0",
+ "mlly": "^1.2.0",
+ "oxc-parser": ">=0.56.0",
+ "rolldown": ">=1.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@nuxt/schema": {
+ "optional": true
+ },
+ "confbox": {
+ "optional": true
+ },
+ "dotenv": {
+ "optional": true
+ },
+ "giget": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "mlly": {
+ "optional": true
+ },
+ "oxc-parser": {
+ "optional": true
+ },
+ "rolldown": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@pinia/nuxt/node_modules/errx": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/errx/-/errx-0.2.2.tgz",
+ "integrity": "sha512-HaPN6cxm6iZ9bIbQQ5orChcw7SY5smUzM08ZMc6OtV4UQhrrc3Ms1G8Ww2n/9lXkWqiioNTssF8bCvchrSbFEQ==",
+ "license": "MIT"
+ },
+ "node_modules/@pinia/nuxt/node_modules/rou3": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/rou3/-/rou3-1.0.0.tgz",
+ "integrity": "sha512-ySeaQkSrua+ut9g+65I7FHqOFBaY8tV0FmccXItoq0q21se32Q3u4YiW7/RqXSosWgYJaaKwRHXy3BST9PeCNQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
+ "node_modules/@pinia/nuxt/node_modules/unctx": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/unctx/-/unctx-3.0.1.tgz",
+ "integrity": "sha512-5RAt2etv7g362RXyd33R82gm9u/kbtQlpoaOs9Bgm4E32GRMJ0xjbZyvdxUTmiuHk3V1IQb1aUNrp5IWY+JaWw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "magic-string": ">=0.30.21",
+ "oxc-parser": ">=0.140.0",
+ "rolldown": "^1.1.5",
+ "unplugin": "^3.3.0"
+ },
+ "peerDependenciesMeta": {
+ "magic-string": {
+ "optional": true
+ },
+ "oxc-parser": {
+ "optional": true
+ },
+ "rolldown": {
+ "optional": true
+ },
+ "unplugin": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@polka/url": {
"version": "1.0.0-next.29",
"resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",
@@ -7324,6 +7448,18 @@
"integrity": "sha512-aVf4A4hI2w70LnF7GG+7xDQUkliwiXWXFvTjkip4+b64ygDQ2sJPRSKFDHbxn8o0xu9QzPkMuuiWIXyFSE2slA==",
"license": "MIT"
},
+ "node_modules/copy-anything": {
+ "version": "4.1.5",
+ "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.1.5.tgz",
+ "integrity": "sha512-vePst2VLTSqPglW7Q98VwFpGiGpOHTyXIo81MO5VyLecA5zMbZw/P/V1vmwD1jksa2iJpn/YkDrJ3XhTfzUyhQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/mesqueeb"
+ }
+ },
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
@@ -9742,6 +9878,12 @@
"node": ">= 18"
}
},
+ "node_modules/mitt": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
+ "license": "MIT"
+ },
"node_modules/mlly": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz",
@@ -10581,6 +10723,75 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/pinia": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/pinia/-/pinia-3.0.4.tgz",
+ "integrity": "sha512-l7pqLUFTI/+ESXn6k3nu30ZIzW5E2WZF/LaHJEpoq6ElcLD+wduZoB2kBN19du6K/4FDpPMazY2wJr+IndBtQw==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/devtools-api": "^7.7.7"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/posva"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.5.0",
+ "vue": "^3.5.11"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/pinia/node_modules/@vue/devtools-api": {
+ "version": "7.7.10",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.10.tgz",
+ "integrity": "sha512-KxtEpUOOpFz/qOGRrAwA36QF7DqIA+FXgCYit9mk9wjbaZt0sXOFz81ElOZtKA4HbWHUdwNjZHBFsFFyp5BZiA==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/devtools-kit": "^7.7.10"
+ }
+ },
+ "node_modules/pinia/node_modules/@vue/devtools-kit": {
+ "version": "7.7.10",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.10.tgz",
+ "integrity": "sha512-3WNi2Kq4tbpVbmhml7RiphmAt0279oh3fKNeWMQIrltfX8Q91b4i5PL8DtyNKdwmcsGrV4fg+erwWOmD05CLIw==",
+ "license": "MIT",
+ "dependencies": {
+ "@vue/devtools-shared": "^7.7.10",
+ "birpc": "^2.3.0",
+ "hookable": "^5.5.3",
+ "mitt": "^3.0.1",
+ "perfect-debounce": "^1.0.0",
+ "speakingurl": "^14.0.1",
+ "superjson": "^2.2.2"
+ }
+ },
+ "node_modules/pinia/node_modules/@vue/devtools-shared": {
+ "version": "7.7.10",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.10.tgz",
+ "integrity": "sha512-wOPslzB8vTvpxwdaOcR2qAbwmuSP0L+rhpoC6Cf56V3Jip+HWb7PQQXOUPgBNQARpXsbQX/+mvi8kKucmBGRwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "rfdc": "^1.4.1"
+ }
+ },
+ "node_modules/pinia/node_modules/birpc": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.9.0.tgz",
+ "integrity": "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/pinia/node_modules/perfect-debounce": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz",
+ "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==",
+ "license": "MIT"
+ },
"node_modules/pkg-types": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.4.0.tgz",
@@ -11302,6 +11513,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/rfdc": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
+ "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
+ "license": "MIT"
+ },
"node_modules/rolldown": {
"version": "1.2.19",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz",
@@ -11719,6 +11936,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/speakingurl": {
+ "version": "14.0.1",
+ "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz",
+ "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/srvx": {
"version": "0.11.22",
"resolved": "https://registry.npmjs.org/srvx/-/srvx-0.11.22.tgz",
@@ -11856,6 +12082,18 @@
"postcss": "^8.5.13"
}
},
+ "node_modules/superjson": {
+ "version": "2.2.7",
+ "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.7.tgz",
+ "integrity": "sha512-QK/H+tosbovdRvIuGqcWn8g3IxPZY7B8ZPowCAmWsV8bPvCk+bGMlZt90C4AxZjnzMO2WBRDacr1+0i1AOy/5g==",
+ "license": "MIT",
+ "dependencies": {
+ "copy-anything": "^4"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
"node_modules/supports-color": {
"version": "10.2.2",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",
diff --git a/package.json b/package.json
index 246d998..4efe2e7 100644
--- a/package.json
+++ b/package.json
@@ -13,8 +13,10 @@
},
"dependencies": {
"@nuxtjs/i18n": "10.2.3",
+ "@pinia/nuxt": "^0.11.3",
"@supabase/supabase-js": "^2.100.0",
"nuxt": "^3.21.11",
+ "pinia": "^3.0.4",
"zod": "^4.0.0"
},
"devDependencies": {
diff --git a/pages/__tests__/callback.nuxt.spec.ts b/pages/__tests__/callback.nuxt.spec.ts
new file mode 100644
index 0000000..2e64ca0
--- /dev/null
+++ b/pages/__tests__/callback.nuxt.spec.ts
@@ -0,0 +1,77 @@
+import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
+import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+import { createFakeAuth } from '../../composables/__tests__/fake-auth'
+import { resetSession } from '../../composables/__tests__/reset-session'
+import CallbackPage from '../auth/callback.vue'
+
+const supabase = vi.hoisted(() => ({ auth: undefined as unknown }))
+mockNuxtImport('useSupabaseAuth', () => () => supabase.auth)
+
+enableAutoUnmount(afterEach)
+
+function signInAs(email: string | undefined) {
+ supabase.auth = createFakeAuth({ signedInAs: email }).auth
+ resetSession()
+}
+
+beforeEach(async () => {
+ signInAs(undefined)
+ await useNuxtApp().$i18n.setLocale('de')
+ await useRouter().push('/')
+})
+
+// The page Google and confirmation emails come back to.
+async function comeBack(address = '/auth/callback?code=abc') {
+ const wrapper = await mountSuspended(CallbackPage, { route: address })
+ await flushPromises()
+ return wrapper
+}
+
+const currentPath = () => useRouter().currentRoute.value.path
+
+describe('auth callback page', () => {
+ test('has one address for all languages', () => {
+ const paths = useRouter().getRoutes().map(route => route.path).filter(path => path.endsWith('/auth/callback'))
+ expect(paths).toEqual(['/auth/callback'])
+ })
+
+ test('opens the dashboard once Supabase has a session', async () => {
+ signInAs('ann@example.org')
+ await comeBack()
+ await vi.waitFor(() => expect(currentPath()).toBe('/dashboard'))
+ })
+
+ test('opens the dashboard in the active language', async () => {
+ signInAs('ann@example.org')
+ await useNuxtApp().$i18n.setLocale('en')
+ await comeBack()
+ await vi.waitFor(() => expect(currentPath()).toBe('/en/dashboard'))
+ })
+
+ test('asks to sign in when there is no session, for example on another device', async () => {
+ const wrapper = await comeBack()
+ expect(wrapper.get('[role="alert"]').text()).toContain('nicht automatisch anmelden')
+ expect(wrapper.get('a[href="/login"]').text()).toBe('Zur Anmeldung')
+ })
+
+ test.each([
+ '/auth/callback?error=access_denied&error_description=Secret+details',
+ '/auth/callback#error=access_denied&error_description=Secret+details',
+ ])('explains a rejected sign-in without showing server text: %s', async (address) => {
+ const wrapper = await comeBack(address)
+ expect(wrapper.get('[role="alert"]').text()).toContain('abgebrochen oder abgelehnt')
+ expect(wrapper.text()).not.toContain('Secret')
+ })
+
+ test('says that it is working while Supabase has not answered', async () => {
+ const fake = createFakeAuth()
+ fake.auth.getSession.mockReturnValue(new Promise(() => {}))
+ supabase.auth = fake.auth
+ resetSession()
+
+ const wrapper = await comeBack()
+
+ expect(wrapper.get('[role="status"]').text()).toContain('Anmeldung wird abgeschlossen')
+ })
+})
diff --git a/pages/__tests__/login.nuxt.spec.ts b/pages/__tests__/login.nuxt.spec.ts
new file mode 100644
index 0000000..db1bae6
--- /dev/null
+++ b/pages/__tests__/login.nuxt.spec.ts
@@ -0,0 +1,203 @@
+import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
+import { AuthApiError, AuthRetryableFetchError } from '@supabase/supabase-js'
+import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+import { createFakeAuth, stubProviderSettings } from '../../composables/__tests__/fake-auth'
+import { resetSession } from '../../composables/__tests__/reset-session'
+import LoginPage from '../login.vue'
+import { button, description, field } from '../../composables/__tests__/form-helpers'
+
+const supabase = vi.hoisted(() => ({ auth: undefined as unknown }))
+mockNuxtImport('useSupabaseAuth', () => () => supabase.auth)
+
+// The pages are attached to the document so that focus works.
+enableAutoUnmount(afterEach)
+
+let fake: ReturnType
+
+beforeEach(async () => {
+ fake = createFakeAuth()
+ supabase.auth = fake.auth
+ resetSession()
+ await useNuxtApp().$i18n.setLocale('de')
+ await useRouter().push('/')
+})
+
+const open = (route = '/login') => mountSuspended(LoginPage, { route, attachTo: document.body })
+const currentPath = () => useRouter().currentRoute.value.path
+const alertText = (wrapper: Awaited>) => wrapper.find('[role="alert"]').text()
+
+async function signIn(wrapper: Awaited>, email = 'ann@example.org', password = 'secret-1') {
+ await field(wrapper, 'E-Mail-Adresse').setValue(email)
+ await field(wrapper, 'Passwort').setValue(password)
+ await wrapper.get('form').trigger('submit')
+}
+
+describe('login form', () => {
+ test('has labelled fields that password managers understand', async () => {
+ const wrapper = await open()
+ expect(field(wrapper, 'E-Mail-Adresse').attributes()).toMatchObject({ type: 'email', autocomplete: 'email' })
+ expect(field(wrapper, 'Passwort').attributes()).toMatchObject({ type: 'password', autocomplete: 'current-password' })
+ expect(button(wrapper, 'Anmelden').attributes('type')).toBe('submit')
+ })
+
+ test('shows errors at the empty fields and focuses the first one', async () => {
+ const wrapper = await open()
+
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+
+ expect(description(wrapper, 'E-Mail-Adresse')).toBe('Bitte gib deine E-Mail-Adresse ein.')
+ expect(description(wrapper, 'Passwort')).toBe('Bitte gib dein Passwort ein.')
+ expect(field(wrapper, 'E-Mail-Adresse').attributes('aria-invalid')).toBe('true')
+ expect(document.activeElement).toBe(field(wrapper, 'E-Mail-Adresse').element)
+ expect(fake.auth.signInWithPassword).not.toHaveBeenCalled()
+ })
+
+ test('focuses the password when only that is missing', async () => {
+ const wrapper = await open()
+ await signIn(wrapper, 'ann@example.org', '')
+ await flushPromises()
+ expect(document.activeElement).toBe(field(wrapper, 'Passwort').element)
+ expect(field(wrapper, 'E-Mail-Adresse').attributes('aria-invalid')).toBeUndefined()
+ })
+
+ test('rejects something that is not an email address', async () => {
+ const wrapper = await open()
+ await signIn(wrapper, 'ann')
+ await flushPromises()
+ expect(description(wrapper, 'E-Mail-Adresse')).toBe('Das ist keine gültige E-Mail-Adresse.')
+ expect(fake.auth.signInWithPassword).not.toHaveBeenCalled()
+ })
+
+ test('signs in and opens the dashboard', async () => {
+ const wrapper = await open()
+
+ await signIn(wrapper, ' ann@example.org ')
+
+ await vi.waitFor(() => expect(currentPath()).toBe('/dashboard'))
+ expect(fake.auth.signInWithPassword).toHaveBeenCalledWith({ email: 'ann@example.org', password: 'secret-1' })
+ })
+
+ test('returns to the page that asked for the sign-in', async () => {
+ const wrapper = await open('/login?redirect=/map')
+ await signIn(wrapper)
+ await vi.waitFor(() => expect(currentPath()).toBe('/map'))
+ })
+
+ // Somebody follows a German link, switches to English on the login page and signs in.
+ test('continues in the language of the login page', async () => {
+ const wrapper = await open('/en/login?redirect=/map')
+
+ await field(wrapper, 'Email address').setValue('ann@example.org')
+ await field(wrapper, 'Password').setValue('secret-1')
+ await wrapper.get('form').trigger('submit')
+
+ await vi.waitFor(() => expect(currentPath()).toBe('/en/map'))
+ })
+
+ test('translates the return address back to German and keeps its query', async () => {
+ const wrapper = await open('/login?redirect=%2Fen%2Fdates%3Fstatus%3Ddone')
+ await signIn(wrapper)
+ await vi.waitFor(() => expect(useRouter().currentRoute.value.fullPath).toBe('/dates?status=done'))
+ })
+
+ test('does not follow a return address outside the app', async () => {
+ const wrapper = await open('/login?redirect=//evil.example')
+ await signIn(wrapper)
+ await vi.waitFor(() => expect(currentPath()).toBe('/dashboard'))
+ })
+
+ test('explains wrong credentials without showing server text', async () => {
+ fake.auth.signInWithPassword.mockResolvedValueOnce({
+ data: { session: null, user: null } as never,
+ error: new AuthApiError('Invalid login credentials', 400, 'invalid_credentials'),
+ })
+ const wrapper = await open()
+
+ await signIn(wrapper)
+
+ await vi.waitFor(() => expect(alertText(wrapper)).toBe('E-Mail-Adresse oder Passwort ist falsch.'))
+ expect(wrapper.text()).not.toContain('Invalid login credentials')
+ expect(currentPath()).toBe('/login')
+ expect(button(wrapper, 'Anmelden').attributes('disabled')).toBeUndefined()
+ })
+
+ test('explains that the server cannot be reached', async () => {
+ fake.auth.signInWithPassword.mockResolvedValueOnce({
+ data: { session: null, user: null } as never,
+ error: new AuthRetryableFetchError('offline', 0),
+ })
+ const wrapper = await open()
+ await signIn(wrapper)
+ await vi.waitFor(() => expect(alertText(wrapper)).toContain('Keine Verbindung zum Server.'))
+ })
+
+ test('sends only one request while waiting', async () => {
+ let answer: (value: never) => void = () => {}
+ fake.auth.signInWithPassword.mockReturnValueOnce(new Promise((resolve) => {
+ answer = resolve
+ }))
+ const wrapper = await open()
+
+ await signIn(wrapper)
+ await wrapper.get('form').trigger('submit')
+
+ expect(fake.auth.signInWithPassword).toHaveBeenCalledTimes(1)
+ expect(button(wrapper, 'Anmelden').attributes('disabled')).toBeDefined()
+ answer({ data: { session: null, user: null }, error: new AuthApiError('no', 400, 'invalid_credentials') } as never)
+ await vi.waitFor(() => expect(button(wrapper, 'Anmelden').attributes('disabled')).toBeUndefined())
+ })
+
+ test('says so when sign-in is not configured', async () => {
+ supabase.auth = undefined
+ resetSession()
+ const wrapper = await open()
+ await signIn(wrapper)
+ await vi.waitFor(() => expect(alertText(wrapper)).toBe('Die Anmeldung ist derzeit nicht verfügbar.'))
+ })
+
+ test('shows messages in the active language', async () => {
+ const wrapper = await open('/en/login')
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+ expect(description(wrapper, 'Email address')).toBe('Please enter your email address.')
+ })
+
+ test('links to registration and keeps the return address', async () => {
+ const wrapper = await open('/login?redirect=/map')
+ expect(wrapper.get('a[href^="/register"]').attributes('href')).toBe('/register?redirect=/map')
+ })
+})
+
+describe('Google button', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ test('starts the Google sign-in', async () => {
+ const wrapper = await open()
+ stubProviderSettings({ google: true })
+
+ await button(wrapper, 'Mit Google fortfahren').trigger('click')
+ await flushPromises()
+
+ expect(fake.auth.signInWithOAuth).toHaveBeenCalledWith({
+ provider: 'google',
+ options: { redirectTo: `${window.location.origin}/auth/callback` },
+ })
+ // It is not the submit button, so the empty form stays quiet.
+ expect(wrapper.find('[aria-invalid]').exists()).toBe(false)
+ })
+
+ test('stays in the app and explains it when Google is switched off', async () => {
+ const wrapper = await open()
+ stubProviderSettings({ google: false })
+
+ await button(wrapper, 'Mit Google fortfahren').trigger('click')
+
+ await vi.waitFor(() => expect(alertText(wrapper)).toBe('Diese Anmeldeart ist derzeit nicht verfügbar.'))
+ expect(fake.auth.signInWithOAuth).not.toHaveBeenCalled()
+ expect(button(wrapper, 'Mit Google fortfahren').attributes('disabled')).toBeUndefined()
+ })
+})
diff --git a/pages/__tests__/register.nuxt.spec.ts b/pages/__tests__/register.nuxt.spec.ts
new file mode 100644
index 0000000..db16614
--- /dev/null
+++ b/pages/__tests__/register.nuxt.spec.ts
@@ -0,0 +1,102 @@
+import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
+import { AuthApiError } from '@supabase/supabase-js'
+import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
+import { createFakeAuth, stubProviderSettings } from '../../composables/__tests__/fake-auth'
+import { resetSession } from '../../composables/__tests__/reset-session'
+import RegisterPage from '../register.vue'
+import { button, description, field } from '../../composables/__tests__/form-helpers'
+
+const supabase = vi.hoisted(() => ({ auth: undefined as unknown }))
+mockNuxtImport('useSupabaseAuth', () => () => supabase.auth)
+
+enableAutoUnmount(afterEach)
+
+let fake: ReturnType
+
+beforeEach(async () => {
+ fake = createFakeAuth()
+ supabase.auth = fake.auth
+ resetSession()
+ await useNuxtApp().$i18n.setLocale('de')
+ await useRouter().push('/')
+})
+
+const open = (route = '/register') => mountSuspended(RegisterPage, { route, attachTo: document.body })
+const currentPath = () => useRouter().currentRoute.value.path
+
+async function register(wrapper: Awaited>, password = 'secret-1') {
+ await field(wrapper, 'E-Mail-Adresse').setValue('ann@example.org')
+ await field(wrapper, 'Passwort').setValue(password)
+ await wrapper.get('form').trigger('submit')
+}
+
+describe('registration form', () => {
+ test('asks for a new password and states the minimum length beforehand', async () => {
+ const wrapper = await open()
+ expect(field(wrapper, 'Passwort').attributes('autocomplete')).toBe('new-password')
+ expect(description(wrapper, 'Passwort')).toBe('Mindestens 8 Zeichen.')
+ })
+
+ test('rejects a password that is too short', async () => {
+ const wrapper = await open()
+
+ await register(wrapper, '1234567')
+ await flushPromises()
+
+ expect(description(wrapper, 'Passwort')).toContain('Das Passwort braucht mindestens 8 Zeichen.')
+ expect(field(wrapper, 'Passwort').attributes('aria-invalid')).toBe('true')
+ expect(document.activeElement).toBe(field(wrapper, 'Passwort').element)
+ expect(fake.auth.signUp).not.toHaveBeenCalled()
+ })
+
+ test('creates the account and opens the dashboard', async () => {
+ const wrapper = await open()
+ await register(wrapper)
+ await vi.waitFor(() => expect(currentPath()).toBe('/dashboard'))
+ expect(fake.auth.signUp).toHaveBeenCalledWith(expect.objectContaining({
+ email: 'ann@example.org',
+ password: 'secret-1',
+ }))
+ })
+
+ test('returns to the page that asked for the sign-in', async () => {
+ const wrapper = await open('/register?redirect=/photos')
+ await register(wrapper)
+ await vi.waitFor(() => expect(currentPath()).toBe('/photos'))
+ })
+
+ test('asks to confirm the email address when Supabase requires it', async () => {
+ fake.auth.signUp.mockResolvedValueOnce({ data: { session: null, user: { id: '1' } } as never, error: null })
+ const wrapper = await open()
+
+ await register(wrapper)
+
+ await vi.waitFor(() => expect(wrapper.get('[role="status"]').text()).toContain('ann@example.org'))
+ expect(wrapper.get('[role="status"]').text()).toContain('Bestätigungslink')
+ expect(wrapper.find('form').exists()).toBe(false)
+ expect(currentPath()).toBe('/register')
+ })
+
+ test('explains that the account already exists', async () => {
+ fake.auth.signUp.mockResolvedValueOnce({
+ data: { session: null, user: null } as never,
+ error: new AuthApiError('User already registered', 422, 'user_already_exists'),
+ })
+ const wrapper = await open()
+
+ await register(wrapper)
+
+ await vi.waitFor(() => expect(wrapper.get('[role="alert"]').text()).toContain('schon ein Konto'))
+ })
+
+ test('offers Google and a link back to the login page', async () => {
+ const wrapper = await open()
+ stubProviderSettings({ google: true })
+ await button(wrapper, 'Mit Google fortfahren').trigger('click')
+ await flushPromises()
+ expect(fake.auth.signInWithOAuth).toHaveBeenCalled()
+ expect(wrapper.get('a[href="/login"]').text()).toContain('Anmelden')
+ vi.unstubAllGlobals()
+ })
+})
diff --git a/pages/auth/callback.vue b/pages/auth/callback.vue
new file mode 100644
index 0000000..349c584
--- /dev/null
+++ b/pages/auth/callback.vue
@@ -0,0 +1,64 @@
+
+
+
+
+