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/FormField.vue b/components/FormField.vue new file mode 100644 index 0000000..8440245 --- /dev/null +++ b/components/FormField.vue @@ -0,0 +1,56 @@ + + + diff --git a/components/SessionControls.vue b/components/SessionControls.vue new file mode 100644 index 0000000..d1015d6 --- /dev/null +++ b/components/SessionControls.vue @@ -0,0 +1,26 @@ + + + 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 @@