- {review.author} ·{' '}
+ {formatAuthor(review.author)} ·{' '}
diff --git a/frontend/src/hooks/useUserId.test.ts b/frontend/src/hooks/useUserId.test.ts
deleted file mode 100644
index 2f5c2a0..0000000
--- a/frontend/src/hooks/useUserId.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { createId, getUserId, USER_ID_KEY } from './useUserId';
-
-// A version 4 UUID: the third group starts with 4, the fourth with 8, 9, a or b.
-const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
-
-afterEach(() => {
- window.localStorage.clear();
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
-});
-
-describe('createId', () => {
- it('creates a version 4 UUID', () => {
- expect(createId()).toMatch(UUID_V4);
- });
-
- it('works without crypto.randomUUID, as on the VM over plain HTTP', () => {
- const realCrypto = globalThis.crypto;
- vi.stubGlobal('crypto', { getRandomValues: realCrypto.getRandomValues.bind(realCrypto) });
-
- expect(createId()).toMatch(UUID_V4);
- expect(createId()).not.toBe(createId());
- });
-});
-
-describe('getUserId', () => {
- it('creates an ID the first time and keeps it', () => {
- const id = getUserId();
- expect(id).toMatch(UUID_V4);
- expect(getUserId()).toBe(id);
- expect(window.localStorage.getItem(USER_ID_KEY)).toBe(id);
- });
-
- it('replaces a saved value that is not a UUID', () => {
- window.localStorage.setItem(USER_ID_KEY, 'not-an-id');
- expect(getUserId()).toMatch(UUID_V4);
- });
-
- it('keeps the same ID for the visit when localStorage is unavailable', () => {
- vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
- throw new Error('Private mode');
- });
-
- const id = getUserId();
- expect(id).toMatch(UUID_V4);
- expect(getUserId()).toBe(id);
- });
-});
diff --git a/frontend/src/hooks/useUserId.ts b/frontend/src/hooks/useUserId.ts
deleted file mode 100644
index 8d259b9..0000000
--- a/frontend/src/hooks/useUserId.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useState } from 'react';
-
-/*
- * Anonymous ID for student reviews, kept in the browser until we have login (#29).
- * It works like a password: whoever knows it can change the user's reviews.
- * The API never sends it back, and the interface never shows it.
- */
-export const USER_ID_KEY = 'kk:user-id';
-
-const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-
-/** A random version 4 UUID. */
-export function createId(): string {
- if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();
-
- // randomUUID only exists on HTTPS and localhost. The VM uses plain HTTP,
- // so there we build the UUID from random bytes ourselves.
- const bytes = crypto.getRandomValues(new Uint8Array(16));
- bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
- bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant
- const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
-}
-
-// Used when localStorage is unavailable, so the ID at least lasts for this visit.
-let sessionId: string | undefined;
-
-/** Reads the saved ID, or creates and saves a new one. */
-export function getUserId(): string {
- try {
- const saved = window.localStorage.getItem(USER_ID_KEY);
- if (saved && UUID.test(saved)) return saved;
-
- const id = createId();
- window.localStorage.setItem(USER_ID_KEY, id);
- return id;
- } catch {
- // Private mode or full storage.
- sessionId ??= createId();
- return sessionId;
- }
-}
-
-/** The same ID for the whole visit, read once when the component mounts. */
-export function useUserId(): string {
- const [id] = useState(getUserId);
- return id;
-}
diff --git a/frontend/src/lib/format.test.ts b/frontend/src/lib/format.test.ts
index d23f3eb..b04e7ac 100644
--- a/frontend/src/lib/format.test.ts
+++ b/frontend/src/lib/format.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
+ formatAuthor,
formatAbv,
formatCount,
formatCountry,
@@ -81,3 +82,10 @@ describe('formatCountry', () => {
expect(formatCountry('!!', 'Atlantis')).toBe('Atlantis');
});
});
+
+describe('formatAuthor', () => {
+ it('shows the username, and «Anonym student» for old reviews without one', () => {
+ expect(formatAuthor('kari')).toBe('kari');
+ expect(formatAuthor(null)).toBe('Anonym student');
+ });
+});
diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts
index 7b81aac..2f5820d 100644
--- a/frontend/src/lib/format.ts
+++ b/frontend/src/lib/format.ts
@@ -84,3 +84,11 @@ export function formatRelativeTime(iso: string, now: Date = new Date()): string
}
return 'akkurat nå';
}
+
+/** Shown for reviews written before login, which have no username. */
+export const ANONYMOUS_AUTHOR = 'Anonym student';
+
+/** The username of the author, or «Anonym student» for old reviews without one. */
+export function formatAuthor(author: string | null): string {
+ return author ?? ANONYMOUS_AUTHOR;
+}
diff --git a/frontend/src/lib/types.ts b/frontend/src/lib/types.ts
index 57c94a0..26fcd82 100644
--- a/frontend/src/lib/types.ts
+++ b/frontend/src/lib/types.ts
@@ -45,8 +45,8 @@ export interface ReviewPreview {
/** Stjerner 1–5 (samme skala som X-Wines, så snittene kan sammenlignes). */
rating: number;
comment: string | null;
- /** Visningsnavn, f.eks. «Student #4821». Ingen personopplysninger. */
- author: string;
+ /** The author's username, or null for anonymous reviews written before login. */
+ author: string | null;
/** ISO 8601-tidspunkt. */
createdAt: string;
wine: Pick;
From be16d9e636129ac9da0e5efb91aba99d038e8eb3 Mon Sep 17 00:00:00 2001
From: Magnus Andreas Igesund Nerland
Date: Mon, 16 Nov 2026 22:48:20 +0100
Subject: [PATCH 4/7] feat(api): add the user's reviews to User (#65)
---
backend/src/resolvers.ts | 63 ++++++++++++++++++++++++-------
backend/src/review-api.db.test.ts | 56 +++++++++++++++++++++++++--
backend/src/schema.ts | 18 +++++++++
3 files changed, 120 insertions(+), 17 deletions(-)
diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts
index 2df743a..34f7775 100644
--- a/backend/src/resolvers.ts
+++ b/backend/src/resolvers.ts
@@ -7,6 +7,7 @@ import { validateReviewInput, validateWineId, type ReviewInput } from './review-
import {
buildFilterOptionsQueries,
buildWinesQuery,
+ decodeCursor,
encodeCursor,
type FilterArgs,
type WinesArgs,
@@ -52,6 +53,26 @@ function toReview(row: ReviewRow) {
};
}
+/**
+ * A page in the GraphQL connection format. `rows` holds one row more than `first`
+ * when there is a next page; that row is only used to set hasNextPage.
+ */
+function toConnection(
+ rows: Row[],
+ { first, offset, totalCount }: { first: number; offset: number; totalCount: number },
+ toNode: (row: Row) => Node,
+) {
+ const edges = rows.slice(0, first).map((row, i) => ({
+ cursor: encodeCursor(offset + i + 1),
+ node: toNode(row),
+ }));
+ return {
+ totalCount,
+ edges,
+ pageInfo: { hasNextPage: rows.length > first, endCursor: edges.at(-1)?.cursor ?? null },
+ };
+}
+
/** Keeps "first" between 1 and MAX_REVIEWS, whatever the frontend sends. */
function limitReviews(first: number | null | undefined, fallback: number): number {
return Math.min(Math.max(first ?? fallback, 1), MAX_REVIEWS);
@@ -74,20 +95,11 @@ export const resolvers = {
pool.query<{ total: number }>(query.countSql, query.countParams),
]);
- const rows = list.rows.slice(0, query.first);
- const edges = rows.map((row, i) => ({
- cursor: encodeCursor(query.offset + i + 1),
- node: toWine(row),
- }));
-
- return {
- totalCount: count.rows[0].total,
- edges,
- pageInfo: {
- hasNextPage: list.rows.length > query.first,
- endCursor: edges.at(-1)?.cursor ?? null,
- },
- };
+ return toConnection(
+ list.rows,
+ { first: query.first, offset: query.offset, totalCount: count.rows[0].total },
+ toWine,
+ );
},
async wine(_parent: unknown, args: { id: string }) {
@@ -188,6 +200,29 @@ export const resolvers = {
},
},
+ // User comes from auth/resolvers.ts. Fields that belong to other features are added here.
+ User: {
+ async reviews(user: { id: string }, args: { first?: number | null; after?: string | null }) {
+ const userId = Number(user.id);
+ const first = limitReviews(args.first, 10);
+ const offset = decodeCursor(args.after);
+ // The index review_user_updated covers both queries.
+ const [list, count] = await Promise.all([
+ pool.query(
+ `SELECT * FROM review
+ WHERE user_id = $1
+ ORDER BY updated_at DESC, id DESC
+ LIMIT $2 OFFSET $3`,
+ [userId, first + 1, offset],
+ ),
+ pool.query<{ total: number }>('SELECT count(*)::int AS total FROM review WHERE user_id = $1', [
+ userId,
+ ]),
+ ]);
+ return toConnection(list.rows, { first, offset, totalCount: count.rows[0].total }, toReview);
+ },
+ },
+
Review: {
// Null for old anonymous reviews. The frontend chooses the text to show for them.
author(review: { userId: number | null }, _args: unknown, { loaders }: Context) {
diff --git a/backend/src/review-api.db.test.ts b/backend/src/review-api.db.test.ts
index 4139e58..c5e3b8e 100644
--- a/backend/src/review-api.db.test.ts
+++ b/backend/src/review-api.db.test.ts
@@ -21,6 +21,13 @@ const url = process.env.TEST_DATABASE_URL;
const SAVE = `mutation Save($input: ReviewInput!) { saveReview(input: $input) { id rating comment author } }`;
const DELETE = `mutation Delete($wineId: ID!) { deleteReview(wineId: $wineId) }`;
const MINE = `query Mine($wineId: ID!) { myReview(wineId: $wineId) { id rating comment author } }`;
+const MY_REVIEWS = `query MyReviews($first: Int, $after: String) {
+ me { reviews(first: $first, after: $after) {
+ totalCount
+ edges { node { rating wine { id } } }
+ pageInfo { hasNextPage endCursor }
+ } }
+}`;
const WINE = `query Wine($id: ID!) {
wine(id: $id) { studentRating { average count } reviews(first: 10) { rating author } }
}`;
@@ -36,19 +43,21 @@ describe.skipIf(!url)('reviews API (PostgreSQL)', () => {
// A wine of our own with an id far above the X-Wines ids, so the tests never touch real data.
const wineId = String(900_000_000 + Math.floor(Math.random() * 1_000_000));
+ const otherWineId = String(Number(wineId) + 1);
const userIds: number[] = [];
const studentIds: number[] = [];
beforeAll(async () => {
await pool.query(
- `INSERT INTO wine (id, name, type, search_text) VALUES ($1, 'Testvin', 'Red', 'testvin')`,
- [wineId],
+ `INSERT INTO wine (id, name, type, search_text)
+ VALUES ($1, 'Testvin', 'Red', 'testvin'), ($2, 'Testvin 2', 'White', 'testvin 2')`,
+ [wineId, otherWineId],
);
});
// Reviews go with the wine and the users (ON DELETE CASCADE).
afterAll(async () => {
- await pool.query('DELETE FROM wine WHERE id = $1', [wineId]);
+ await pool.query('DELETE FROM wine WHERE id = ANY($1)', [[wineId, otherWineId]]);
await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [userIds]);
await pool.query('DELETE FROM student WHERE id = ANY($1)', [studentIds]);
await pool.end();
@@ -154,4 +163,45 @@ describe.skipIf(!url)('reviews API (PostgreSQL)', () => {
);
expect(codeOf(await kim.request(SAVE, save(4.25)))).toBe('BAD_USER_INPUT');
});
+
+ describe('User.reviews', () => {
+ type Page = {
+ totalCount: number;
+ edges: { node: { rating: number; wine: { id: string } } }[];
+ pageInfo: { hasNextPage: boolean; endCursor: string | null };
+ };
+ const pageOf = (result: { data?: Record | null }) =>
+ (result.data?.me as { reviews: Page }).reviews;
+
+ it('is empty for a user without reviews', async () => {
+ const lise = await createBrowser('lise');
+ expect(pageOf(await lise.request(MY_REVIEWS))).toEqual({
+ totalCount: 0,
+ edges: [],
+ pageInfo: { hasNextPage: false, endCursor: null },
+ });
+ });
+
+ it('lists only the reviews of this user, newest first, one page at a time', async () => {
+ const tor = await createBrowser('tor');
+ const other = await createBrowser('other');
+ await tor.request(SAVE, save(4));
+ await tor.request(SAVE, { input: { wineId: otherWineId, rating: 2 } });
+ await other.request(SAVE, save(1));
+
+ const first = pageOf(await tor.request(MY_REVIEWS, { first: 1 }));
+ expect(first.totalCount).toBe(2);
+ expect(first.edges.map((edge) => edge.node)).toEqual([{ rating: 2, wine: { id: otherWineId } }]);
+ expect(first.pageInfo.hasNextPage).toBe(true);
+
+ const second = pageOf(await tor.request(MY_REVIEWS, { first: 1, after: first.pageInfo.endCursor }));
+ expect(second.edges.map((edge) => edge.node)).toEqual([{ rating: 4, wine: { id: wineId } }]);
+ expect(second.pageInfo.hasNextPage).toBe(false);
+ });
+
+ it('rejects a cursor that was not made by the API', async () => {
+ const ina = await createBrowser('ina');
+ expect(codeOf(await ina.request(MY_REVIEWS, { after: 'not-a-cursor' }))).toBe('BAD_USER_INPUT');
+ });
+ });
});
diff --git a/backend/src/schema.ts b/backend/src/schema.ts
index 6797c92..7d12127 100644
--- a/backend/src/schema.ts
+++ b/backend/src/schema.ts
@@ -104,6 +104,24 @@ export const typeDefs = `#graphql
wine: Wine!
}
+ type ReviewEdge {
+ cursor: String!
+ node: Review!
+ }
+
+ type ReviewConnection {
+ "Number of reviews across all pages."
+ totalCount: Int!
+ edges: [ReviewEdge!]!
+ pageInfo: PageInfo!
+ }
+
+ # User is defined in auth/schema.ts. Reviews are public, so this works for any user.
+ extend type User {
+ "The user's reviews, newest first. Use pageInfo.endCursor as 'after' to load more."
+ reviews(first: Int = 10, after: String): ReviewConnection!
+ }
+
"The author is always the logged-in user, so it is not part of the input."
input ReviewInput {
wineId: ID!
From c24cb1f1bfd7642a9cb9cd30ba9e89943152b5ca Mon Sep 17 00:00:00 2001
From: Magnus Andreas Igesund Nerland
Date: Mon, 16 Nov 2026 23:26:09 +0100
Subject: [PATCH 5/7] fix(auth): field errors, focus and capital letters in the
auth form (#65)
---
.../src/features/auth/AccountPage.test.tsx | 5 +-
frontend/src/features/auth/AccountPage.tsx | 9 +-
frontend/src/features/auth/AuthContext.ts | 6 +-
frontend/src/features/auth/AuthProvider.tsx | 6 +-
.../src/features/auth/api/authMessages.ts | 65 +++++---
.../auth/components/AuthForm.module.css | 17 +-
.../auth/components/AuthForm.test.tsx | 121 ++++++++++++++
.../src/features/auth/components/AuthForm.tsx | 147 +++++++++++++-----
.../src/features/auth/credentials.test.ts | 55 +++++++
frontend/src/features/auth/credentials.ts | 56 +++++++
10 files changed, 422 insertions(+), 65 deletions(-)
create mode 100644 frontend/src/features/auth/components/AuthForm.test.tsx
create mode 100644 frontend/src/features/auth/credentials.test.ts
create mode 100644 frontend/src/features/auth/credentials.ts
diff --git a/frontend/src/features/auth/AccountPage.test.tsx b/frontend/src/features/auth/AccountPage.test.tsx
index a5e6ef1..3540ef0 100644
--- a/frontend/src/features/auth/AccountPage.test.tsx
+++ b/frontend/src/features/auth/AccountPage.test.tsx
@@ -104,8 +104,11 @@ describe('AccountPage', () => {
await user.click(await screen.findByRole('button', { name: 'Lag bruker' }));
await signIn(user, 'Lag bruker');
+ // A broken rule is shown next to the field it is about, not as a general error.
await waitFor(() =>
- expect(screen.getByRole('alert')).toHaveTextContent('små bokstaver, tall og understrek'),
+ expect(screen.getByLabelText('Brukernavn')).toHaveAccessibleDescription(
+ /bokstavene a–z, tall og understrek\.$/,
+ ),
);
});
diff --git a/frontend/src/features/auth/AccountPage.tsx b/frontend/src/features/auth/AccountPage.tsx
index 6cb7dbe..97a3b2f 100644
--- a/frontend/src/features/auth/AccountPage.tsx
+++ b/frontend/src/features/auth/AccountPage.tsx
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { useNavigate, useLocation, Link } from 'react-router';
import { useDocumentTitle } from '../../hooks/useDocumentTitle';
+import type { AuthFailure } from './api/authMessages';
import { AuthForm } from './components/AuthForm';
import type { Credentials } from './AuthContext';
import { useAuth } from './useAuth';
@@ -22,10 +23,10 @@ export default function AccountPage() {
const location = useLocation();
useDocumentTitle(user ? 'Min konto' : 'Logg inn');
- async function handleSubmit(credentials: Credentials): Promise {
- const message = await (mode === 'login' ? login : register)(credentials);
- if (!message) await navigate(nextPage(location.state), { replace: true });
- return message;
+ async function handleSubmit(credentials: Credentials): Promise {
+ const failure = await (mode === 'login' ? login : register)(credentials);
+ if (!failure) await navigate(nextPage(location.state), { replace: true });
+ return failure;
}
if (loading) {
diff --git a/frontend/src/features/auth/AuthContext.ts b/frontend/src/features/auth/AuthContext.ts
index 7bde2fb..413a71b 100644
--- a/frontend/src/features/auth/AuthContext.ts
+++ b/frontend/src/features/auth/AuthContext.ts
@@ -1,4 +1,5 @@
import { createContext } from 'react';
+import type { AuthFailure } from './api/authMessages';
import type { User } from './api/authQueries';
export interface Credentials {
@@ -11,9 +12,10 @@ export interface AuthContextValue {
user: User | null;
/** True until we know whether anyone is logged in. */
loading: boolean;
+ /** Returns a Norwegian message (and the field it is about) when it fails, and null when it worked. */
+ register: (credentials: Credentials) => Promise;
+ login: (credentials: Credentials) => Promise;
/** Returns a Norwegian message when it fails, and null when it worked. */
- register: (credentials: Credentials) => Promise;
- login: (credentials: Credentials) => Promise;
logout: () => Promise;
}
diff --git a/frontend/src/features/auth/AuthProvider.tsx b/frontend/src/features/auth/AuthProvider.tsx
index 26d45a0..db2adf7 100644
--- a/frontend/src/features/auth/AuthProvider.tsx
+++ b/frontend/src/features/auth/AuthProvider.tsx
@@ -8,7 +8,7 @@ import {
type MeData,
type User,
} from './api/authQueries';
-import { authErrorMessage } from './api/authMessages';
+import { authErrorMessage, describeAuthError, type AuthFailure } from './api/authMessages';
import { AuthContext, type AuthContextValue, type Credentials } from './AuthContext';
/**
@@ -28,7 +28,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
mutate: typeof loginMutation,
credentials: Credentials,
field: 'login' | 'register',
- ): Promise => {
+ ): Promise => {
try {
const result = await mutate({ variables: { input: credentials } });
const user = (result.data as Record | null)?.[field] ?? null;
@@ -38,7 +38,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
await client.resetStore().catch(() => undefined);
return null;
} catch (error) {
- return authErrorMessage(error);
+ return describeAuthError(error);
}
},
[client],
diff --git a/frontend/src/features/auth/api/authMessages.ts b/frontend/src/features/auth/api/authMessages.ts
index 86f1174..acdd345 100644
--- a/frontend/src/features/auth/api/authMessages.ts
+++ b/frontend/src/features/auth/api/authMessages.ts
@@ -1,43 +1,70 @@
import { CombinedGraphQLErrors } from '@apollo/client/errors';
import { classifyError, ERROR_DETAILS } from '../../../lib/errors';
+import {
+ PASSWORD_MAX_LENGTH,
+ PASSWORD_MIN_LENGTH,
+ USERNAME_MAX_LENGTH,
+ USERNAME_MIN_LENGTH,
+ type CredentialsField,
+ type CredentialsReason,
+} from '../credentials';
-/** The rules the backend checks, so the form can say the same thing before asking. */
-export const USERNAME_PATTERN = '^[a-z0-9_]{3,30}$';
-export const PASSWORD_MIN_LENGTH = 8;
-export const PASSWORD_MAX_LENGTH = 128;
+/** A Norwegian message for the user, and the field it belongs to when there is one. */
+export interface AuthFailure {
+ message: string;
+ field?: CredentialsField;
+}
-const REASONS: Record = {
- USERNAME_TOO_SHORT: 'Brukernavnet må ha minst 3 tegn.',
- USERNAME_TOO_LONG: 'Brukernavnet kan ha maks 30 tegn.',
- USERNAME_INVALID_CHARACTERS: 'Brukernavnet kan bare ha små bokstaver, tall og understrek.',
+export const REASON_MESSAGES: Record = {
+ USERNAME_REQUIRED: 'Skriv inn brukernavn.',
+ PASSWORD_REQUIRED: 'Skriv inn passord.',
+ USERNAME_TOO_SHORT: `Brukernavnet må ha minst ${USERNAME_MIN_LENGTH} tegn.`,
+ USERNAME_TOO_LONG: `Brukernavnet kan ha maks ${USERNAME_MAX_LENGTH} tegn.`,
+ USERNAME_INVALID_CHARACTERS: 'Brukernavnet kan bare ha bokstavene a–z, tall og understrek.',
PASSWORD_TOO_SHORT: `Passordet må ha minst ${PASSWORD_MIN_LENGTH} tegn.`,
PASSWORD_TOO_LONG: `Passordet kan ha maks ${PASSWORD_MAX_LENGTH} tegn.`,
};
-const CODES: Record = {
- USERNAME_TAKEN: 'Brukernavnet er opptatt. Prøv et annet.',
- INVALID_CREDENTIALS: 'Feil brukernavn eller passord.',
- TOO_MANY_ATTEMPTS: 'For mange forsøk. Vent litt og prøv igjen.',
- UNAUTHENTICATED: 'Du må være logget inn for å gjøre dette.',
+/** The message for a rule that was broken, next to the field it is about. */
+export function reasonFailure(reason: CredentialsReason): AuthFailure {
+ return {
+ field: reason.startsWith('USERNAME_') ? 'username' : 'password',
+ message: REASON_MESSAGES[reason],
+ };
+}
+
+const CODES: Record = {
+ USERNAME_TAKEN: { field: 'username', message: 'Brukernavnet er opptatt. Prøv et annet.' },
+ INVALID_CREDENTIALS: { message: 'Feil brukernavn eller passord.' },
+ TOO_MANY_ATTEMPTS: { message: 'For mange forsøk. Vent litt og prøv igjen.' },
+ UNAUTHENTICATED: { message: 'Du må være logget inn for å gjøre dette.' },
};
+const isReason = (value: unknown): value is CredentialsReason =>
+ typeof value === 'string' && Object.hasOwn(REASON_MESSAGES, value);
+
/**
* Turns an error from the API into Norwegian text for the user.
* The backend only sends codes, so nothing it writes is shown as it is.
*/
-export function authErrorMessage(error: unknown): string {
+export function describeAuthError(error: unknown): AuthFailure {
if (CombinedGraphQLErrors.is(error)) {
for (const graphQLError of error.errors) {
const { code, reason } = (graphQLError.extensions ?? {}) as {
- code?: string;
- reason?: string;
+ code?: unknown;
+ reason?: unknown;
};
- if (reason && REASONS[reason]) return REASONS[reason];
- if (code && CODES[code]) return CODES[code];
+ if (isReason(reason)) return reasonFailure(reason);
+ if (typeof code === 'string' && Object.hasOwn(CODES, code)) return CODES[code];
}
}
// Offline, server down, and the like: the same text as everywhere else in the app.
- return ERROR_DETAILS[classifyError(error)];
+ return { message: ERROR_DETAILS[classifyError(error)] };
+}
+
+/** Only the text, for errors that belong to no field (such as a failed logout). */
+export function authErrorMessage(error: unknown): string {
+ return describeAuthError(error).message;
}
diff --git a/frontend/src/features/auth/components/AuthForm.module.css b/frontend/src/features/auth/components/AuthForm.module.css
index fa7daac..186450c 100644
--- a/frontend/src/features/auth/components/AuthForm.module.css
+++ b/frontend/src/features/auth/components/AuthForm.module.css
@@ -24,6 +24,10 @@
outline-offset: 2px;
}
+.input[aria-invalid='true'] {
+ border: 2px solid var(--color-danger, #b3261e);
+}
+
.help {
font-size: var(--text-sm);
color: var(--color-text-muted);
@@ -34,6 +38,17 @@
font-weight: 600;
}
+/* The message under a field. The sign means the error is not shown by colour alone (WCAG 1.4.1). */
+.fieldError {
+ color: var(--color-danger, #b3261e);
+ font-size: var(--text-sm);
+ font-weight: 600;
+}
+
+.fieldError::before {
+ content: '⚠ ';
+}
+
/* Empty: out of the grid so it adds no gap, but still in the accessibility tree. */
.error:empty {
position: absolute;
@@ -54,7 +69,7 @@
cursor: pointer;
}
-.submit:disabled {
+.submit[aria-disabled='true'] {
opacity: 0.6;
cursor: progress;
}
diff --git a/frontend/src/features/auth/components/AuthForm.test.tsx b/frontend/src/features/auth/components/AuthForm.test.tsx
new file mode 100644
index 0000000..b779409
--- /dev/null
+++ b/frontend/src/features/auth/components/AuthForm.test.tsx
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { axe } from 'vitest-axe';
+import type { AuthFailure } from '../api/authMessages';
+import { AuthForm } from './AuthForm';
+
+const PASSWORD = 'langt-nok-passord';
+
+/** `result` is what onSubmit resolves with: null when the API said yes. */
+function renderForm(mode: 'login' | 'register', result: AuthFailure | null = null) {
+ const onSubmit = vi.fn<
+ (credentials: { username: string; password: string }) => Promise
+ >(() => Promise.resolve(result));
+ const user = userEvent.setup();
+ const view = render();
+ return { user, onSubmit, ...view };
+}
+
+const usernameField = () => screen.getByLabelText('Brukernavn');
+const passwordField = () => screen.getByLabelText('Passord');
+
+async function fillIn(
+ user: ReturnType,
+ username: string,
+ password: string,
+) {
+ if (username) await user.type(usernameField(), username);
+ if (password) await user.type(passwordField(), password);
+}
+
+describe('AuthForm', () => {
+ it('shows Norwegian messages under the fields, and moves focus to the first one', async () => {
+ const { user, onSubmit } = renderForm('register');
+ await user.click(screen.getByRole('button', { name: 'Lag bruker' }));
+
+ expect(usernameField()).toHaveFocus();
+ expect(usernameField()).toHaveAttribute('aria-invalid', 'true');
+ expect(usernameField()).toHaveAccessibleDescription(/Skriv inn brukernavn\.$/);
+ expect(passwordField()).toHaveAccessibleDescription(/Skriv inn passord\.$/);
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it('allows capital letters and sends the username in lowercase', async () => {
+ const { user, onSubmit } = renderForm('register');
+ await fillIn(user, ' Kari_N ', PASSWORD);
+ await user.click(screen.getByRole('button', { name: 'Lag bruker' }));
+
+ expect(onSubmit).toHaveBeenCalledWith({ username: 'kari_n', password: PASSWORD });
+ });
+
+ it('explains a broken rule before anything is sent', async () => {
+ const { user, onSubmit } = renderForm('register');
+ await fillIn(user, 'kari', 'kort');
+ await user.click(screen.getByRole('button', { name: 'Lag bruker' }));
+
+ expect(passwordField()).toHaveFocus();
+ expect(passwordField()).toHaveAccessibleDescription(/Passordet må ha minst 8 tegn\.$/);
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it('removes the message when the user starts typing in the field', async () => {
+ const { user } = renderForm('register');
+ await user.click(screen.getByRole('button', { name: 'Lag bruker' }));
+ await user.type(usernameField(), 'k');
+
+ expect(usernameField()).not.toHaveAttribute('aria-invalid');
+ expect(screen.queryByText('Skriv inn brukernavn.')).not.toBeInTheDocument();
+ });
+
+ it('puts an API error about a field next to that field', async () => {
+ const { user } = renderForm('register', {
+ field: 'username',
+ message: 'Brukernavnet er opptatt. Prøv et annet.',
+ });
+ await fillIn(user, 'kari', PASSWORD);
+ await user.click(screen.getByRole('button', { name: 'Lag bruker' }));
+
+ await waitFor(() => expect(usernameField()).toHaveFocus());
+ expect(usernameField()).toHaveAccessibleDescription(/Brukernavnet er opptatt/);
+ expect(screen.getByRole('alert')).toBeEmptyDOMElement();
+ });
+
+ it('announces other API errors with role="alert"', async () => {
+ const { user } = renderForm('login', { message: 'Feil brukernavn eller passord.' });
+ await fillIn(user, 'kari', 'feil-passord');
+ await user.click(screen.getByRole('button', { name: 'Logg inn' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('Feil brukernavn eller passord.');
+ });
+
+ it('keeps the button focusable while the request runs, and ignores a second click', async () => {
+ let finish: (result: AuthFailure | null) => void = () => {};
+ const onSubmit = vi.fn(() => new Promise((resolve) => (finish = resolve)));
+ const user = userEvent.setup();
+ render();
+ await fillIn(user, 'kari', PASSWORD);
+
+ await user.click(screen.getByRole('button', { name: 'Logg inn' }));
+ const button = screen.getByRole('button', { name: 'Logger inn …' });
+ expect(button).toHaveAttribute('aria-disabled', 'true');
+ expect(button).toHaveFocus();
+
+ await user.click(button);
+ expect(onSubmit).toHaveBeenCalledOnce();
+ finish(null);
+ await screen.findByRole('button', { name: 'Logg inn' });
+ });
+
+ it('only shows the rules when creating a user', () => {
+ renderForm('login');
+ expect(usernameField()).not.toHaveAccessibleDescription();
+ expect(passwordField()).toHaveAttribute('autocomplete', 'current-password');
+ });
+
+ it('has no axe violations, also with messages shown', async () => {
+ const { user, container } = renderForm('register');
+ await user.click(screen.getByRole('button', { name: 'Lag bruker' }));
+ expect(await axe(container)).toHaveNoViolations();
+ });
+});
diff --git a/frontend/src/features/auth/components/AuthForm.tsx b/frontend/src/features/auth/components/AuthForm.tsx
index dd75fb8..0958fc3 100644
--- a/frontend/src/features/auth/components/AuthForm.tsx
+++ b/frontend/src/features/auth/components/AuthForm.tsx
@@ -1,84 +1,161 @@
-import { useId, useState, type FormEvent } from 'react';
-import { PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH, USERNAME_PATTERN } from '../api/authMessages';
+import { useId, useRef, useState, type FormEvent } from 'react';
+import { reasonFailure, type AuthFailure } from '../api/authMessages';
import type { Credentials } from '../AuthContext';
+import {
+ normalizeUsername,
+ PASSWORD_MIN_LENGTH,
+ validateCredentials,
+ type CredentialsField,
+} from '../credentials';
import styles from './AuthForm.module.css';
interface AuthFormProps {
mode: 'login' | 'register';
- /** Returns a Norwegian message when it fails, and null when it worked. */
- onSubmit: (credentials: Credentials) => Promise;
+ /** Resolves with a Norwegian message (and its field) when it fails, and null when it worked. */
+ onSubmit: (credentials: Credentials) => Promise;
}
+type FieldErrors = Partial>;
+
+const FIELDS: CredentialsField[] = ['username', 'password'];
+
const TEXTS = {
login: { submit: 'Logg inn', working: 'Logger inn …' },
register: { submit: 'Lag bruker', working: 'Lager bruker …' },
};
-/** Username and password. The same form for logging in and creating a user. */
+/**
+ * Username and password. The same form for logging in and creating a user.
+ *
+ * The form checks the rules itself (noValidate), so every message is in Norwegian. A message
+ * about one field is shown under it and linked with aria-describedby, and focus moves to the
+ * first field with an error. Messages that belong to no field are announced with role="alert".
+ */
export function AuthForm({ mode, onSubmit }: AuthFormProps) {
- const [username, setUsername] = useState('');
- const [password, setPassword] = useState('');
- const [error, setError] = useState('');
+ const [values, setValues] = useState({ username: '', password: '' });
+ const [fieldErrors, setFieldErrors] = useState({});
+ const [formError, setFormError] = useState('');
const [working, setWorking] = useState(false);
- const usernameId = useId();
- const passwordId = useId();
- const helpId = useId();
+ const id = useId();
+ const inputs = {
+ username: useRef(null),
+ password: useRef(null),
+ };
+ const isRegister = mode === 'register';
+
+ /** Shows the messages and moves focus to the first field that has one. */
+ function showFieldErrors(errors: FieldErrors) {
+ setFieldErrors(errors);
+ const first = FIELDS.find((field) => errors[field]);
+ if (first) inputs[first].current?.focus();
+ }
async function handleSubmit(event: FormEvent) {
event.preventDefault();
- setError('');
+ if (working) return;
+ setFormError('');
+
+ const reasons = validateCredentials(mode, values);
+ const errors: FieldErrors = {};
+ for (const field of FIELDS) {
+ const reason = reasons[field];
+ if (reason) errors[field] = reasonFailure(reason).message;
+ }
+ showFieldErrors(errors);
+ if (Object.keys(errors).length > 0) return;
+
setWorking(true);
- const message = await onSubmit({ username: username.trim().toLowerCase(), password });
+ const failure = await onSubmit({
+ username: normalizeUsername(values.username),
+ password: values.password,
+ });
setWorking(false);
- if (message) setError(message);
+
+ if (failure?.field) {
+ const errors: FieldErrors = {};
+ errors[failure.field] = failure.message;
+ showFieldErrors(errors);
+ } else if (failure) {
+ setFormError(failure.message);
+ }
+ }
+
+ function update(field: CredentialsField, value: string) {
+ setValues((current) => ({ ...current, [field]: value }));
+ // The old message no longer fits what the user is typing.
+ if (fieldErrors[field]) setFieldErrors((current) => ({ ...current, [field]: undefined }));
+ }
+
+ /** The id of the help text (registration only) and of the error, when they are shown. */
+ function describedBy(field: CredentialsField) {
+ const ids = [isRegister && `${id}-${field}-help`, fieldErrors[field] && `${id}-${field}-error`];
+ return ids.filter(Boolean).join(' ') || undefined;
}
return (
-
diff --git a/frontend/src/features/auth/credentials.test.ts b/frontend/src/features/auth/credentials.test.ts
new file mode 100644
index 0000000..49b1787
--- /dev/null
+++ b/frontend/src/features/auth/credentials.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest';
+import {
+ normalizeUsername,
+ PASSWORD_MAX_LENGTH,
+ USERNAME_MAX_LENGTH,
+ validateCredentials,
+} from './credentials';
+
+const PASSWORD = 'langt-nok-passord';
+
+describe('normalizeUsername', () => {
+ it('trims and lowercases, like the API', () => {
+ expect(normalizeUsername(' Kari_N ')).toBe('kari_n');
+ });
+});
+
+describe('validateCredentials', () => {
+ it('accepts valid input, also with capital letters in the username', () => {
+ expect(validateCredentials('register', { username: 'Kari_99', password: PASSWORD })).toEqual(
+ {},
+ );
+ });
+
+ it('only checks that both fields are filled in when logging in', () => {
+ expect(validateCredentials('login', { username: 'x', password: 'y' })).toEqual({});
+ expect(validateCredentials('login', { username: ' ', password: '' })).toEqual({
+ username: 'USERNAME_REQUIRED',
+ password: 'PASSWORD_REQUIRED',
+ });
+ });
+
+ it.each([
+ ['', 'USERNAME_REQUIRED'],
+ ['ab', 'USERNAME_TOO_SHORT'],
+ ['a'.repeat(USERNAME_MAX_LENGTH + 1), 'USERNAME_TOO_LONG'],
+ ['kari nordmann', 'USERNAME_INVALID_CHARACTERS'],
+ ['blåbær', 'USERNAME_INVALID_CHARACTERS'],
+ ])('rejects the username %j with %s', (username, reason) => {
+ expect(validateCredentials('register', { username, password: PASSWORD }).username).toBe(reason);
+ });
+
+ it.each([
+ ['', 'PASSWORD_REQUIRED'],
+ ['kort', 'PASSWORD_TOO_SHORT'],
+ ['a'.repeat(PASSWORD_MAX_LENGTH + 1), 'PASSWORD_TOO_LONG'],
+ ])('rejects the password %j with %s', (password, reason) => {
+ expect(validateCredentials('register', { username: 'kari', password }).password).toBe(reason);
+ });
+
+ it('never trims the password', () => {
+ expect(validateCredentials('register', { username: 'kari', password: ' 8 tegn ' })).toEqual(
+ {},
+ );
+ });
+});
diff --git a/frontend/src/features/auth/credentials.ts b/frontend/src/features/auth/credentials.ts
new file mode 100644
index 0000000..37456de
--- /dev/null
+++ b/frontend/src/features/auth/credentials.ts
@@ -0,0 +1,56 @@
+// The rules for usernames and passwords, checked in the browser before anything is sent.
+// The backend has the same rules in backend/src/auth/credentials.ts and checks them again,
+// so change both together.
+import type { Credentials } from './AuthContext';
+
+export const USERNAME_MIN_LENGTH = 3;
+export const USERNAME_MAX_LENGTH = 30;
+const USERNAME_CHARACTERS = /^[a-z0-9_]+$/;
+export const PASSWORD_MIN_LENGTH = 8;
+export const PASSWORD_MAX_LENGTH = 128;
+
+export type CredentialsField = 'username' | 'password';
+
+/** The same names as `extensions.reason` from the API, plus the two "required" checks. */
+export type CredentialsReason =
+ | 'USERNAME_REQUIRED'
+ | 'PASSWORD_REQUIRED'
+ | 'USERNAME_TOO_SHORT'
+ | 'USERNAME_TOO_LONG'
+ | 'USERNAME_INVALID_CHARACTERS'
+ | 'PASSWORD_TOO_SHORT'
+ | 'PASSWORD_TOO_LONG';
+
+export type FieldReasons = Partial>;
+
+/** " Kari " → "kari". The API stores usernames like this, so capital letters are allowed. */
+export function normalizeUsername(username: string): string {
+ return username.trim().toLowerCase();
+}
+
+/**
+ * Login only checks that both fields are filled in: a wrong username or password is for the
+ * API to reject. Registration checks every rule. The password is never trimmed.
+ */
+export function validateCredentials(
+ mode: 'login' | 'register',
+ { username, password }: Credentials,
+): FieldReasons {
+ const reasons: FieldReasons = {};
+ const name = normalizeUsername(username);
+
+ if (!name) reasons.username = 'USERNAME_REQUIRED';
+ else if (mode === 'register') {
+ if (name.length < USERNAME_MIN_LENGTH) reasons.username = 'USERNAME_TOO_SHORT';
+ else if (name.length > USERNAME_MAX_LENGTH) reasons.username = 'USERNAME_TOO_LONG';
+ else if (!USERNAME_CHARACTERS.test(name)) reasons.username = 'USERNAME_INVALID_CHARACTERS';
+ }
+
+ if (!password) reasons.password = 'PASSWORD_REQUIRED';
+ else if (mode === 'register') {
+ if (password.length < PASSWORD_MIN_LENGTH) reasons.password = 'PASSWORD_TOO_SHORT';
+ else if (password.length > PASSWORD_MAX_LENGTH) reasons.password = 'PASSWORD_TOO_LONG';
+ }
+
+ return reasons;
+}
From d0c761dc53d22fde65fa7de599ea5cea62018df1 Mon Sep 17 00:00:00 2001
From: Magnus Andreas Igesund Nerland
Date: Mon, 16 Nov 2026 23:38:08 +0100
Subject: [PATCH 6/7] test(e2e): stub Me in all specs and count the landing
request (#65)
---
frontend/e2e/filters.spec.ts | 12 +++------
frontend/e2e/landing.spec.ts | 45 +++++++++++++++++++++++++++------
frontend/e2e/search.spec.ts | 15 +++++------
frontend/e2e/support/graphql.ts | 37 +++++++++++++++++++++++++++
frontend/e2e/wine.spec.ts | 44 +++++++++++++-------------------
5 files changed, 103 insertions(+), 50 deletions(-)
create mode 100644 frontend/e2e/support/graphql.ts
diff --git a/frontend/e2e/filters.spec.ts b/frontend/e2e/filters.spec.ts
index 72ff66c..9b6d06f 100644
--- a/frontend/e2e/filters.spec.ts
+++ b/frontend/e2e/filters.spec.ts
@@ -1,5 +1,6 @@
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
+import { stubGraphQL } from './support/graphql';
/*
* E2E for filters and sorting. Runs against `vite preview` with a stubbed GraphQL API.
@@ -59,14 +60,9 @@ const filterResponse = {
};
async function stubApi(page: Page) {
- await page.route('**/project2/graphql', (route) => {
- const { operationName, variables } = route.request().postDataJSON() as {
- operationName: string;
- variables: Variables;
- };
- return route.fulfill({
- json: operationName === 'FilterOptions' ? filterResponse : winesResponse(variables),
- });
+ await stubGraphQL(page, {
+ FilterOptions: () => filterResponse,
+ SearchWines: (variables: Variables) => winesResponse(variables),
});
}
diff --git a/frontend/e2e/landing.spec.ts b/frontend/e2e/landing.spec.ts
index ceee7fe..9a1dbab 100644
--- a/frontend/e2e/landing.spec.ts
+++ b/frontend/e2e/landing.spec.ts
@@ -1,5 +1,6 @@
import AxeBuilder from '@axe-core/playwright';
import { expect, test } from '@playwright/test';
+import { stubGraphQL } from './support/graphql';
/*
* E2E for forsiden. Kjøres mot `vite preview` (se playwright.config.ts).
@@ -35,22 +36,27 @@ const landingResponse = {
};
test.describe('Forsiden', () => {
- let graphqlRequests = 0;
+ let operations: string[] = [];
test.beforeEach(async ({ page }) => {
- graphqlRequests = 0;
- await page.route('**/project2/graphql', (route) => {
- graphqlRequests += 1;
- return route.fulfill({ json: landingResponse });
- });
+ operations = await stubGraphQL(page, { Landing: () => landingResponse });
await page.goto('./');
});
- test('henter hele forsiden i én GraphQL-forespørsel', async ({ page }) => {
+ test('henter alt innholdet på forsiden i én GraphQL-forespørsel', async ({ page }) => {
await expect(
page.getByRole('region', { name: 'Best vurdert' }).getByRole('article'),
).toHaveCount(6);
- expect(graphqlRequests).toBe(1);
+ // `Me` (who is logged in) is shared by every page and cached, so it is not counted as
+ // part of the landing page. Everything the page shows comes from one `Landing` query.
+ expect(operations.filter((name) => name !== 'Me')).toEqual(['Landing']);
+ expect(operations.filter((name) => name === 'Me')).toHaveLength(1);
+ });
+
+ test('viser «Logg inn» i menyen når ingen er logget inn', async ({ page }) => {
+ await expect(
+ page.getByRole('navigation', { name: 'Hovedmeny' }).getByRole('link', { name: 'Logg inn' }),
+ ).toBeVisible();
});
test('forklarer hva siden er og har riktig tittel', async ({ page }) => {
@@ -101,3 +107,26 @@ test.describe('Forsiden', () => {
expect(clipped).toEqual([]);
});
});
+
+test.describe('Forsiden som innlogget', () => {
+ test('viser brukernavnet i menyen', async ({ page }) => {
+ await stubGraphQL(page, {
+ Landing: () => landingResponse,
+ Me: () => ({
+ data: {
+ me: {
+ __typename: 'User',
+ id: '1',
+ username: 'kari',
+ createdAt: '2026-11-16T12:00:00.000Z',
+ },
+ },
+ }),
+ });
+ await page.goto('./');
+
+ await expect(
+ page.getByRole('navigation', { name: 'Hovedmeny' }).getByRole('link', { name: 'kari' }),
+ ).toHaveAttribute('href', /\/konto$/);
+ });
+});
diff --git a/frontend/e2e/search.spec.ts b/frontend/e2e/search.spec.ts
index 89f4170..f586fd2 100644
--- a/frontend/e2e/search.spec.ts
+++ b/frontend/e2e/search.spec.ts
@@ -1,5 +1,6 @@
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
+import { stubGraphQL } from './support/graphql';
/*
* E2E for the search page. Runs against `vite preview` with a stubbed GraphQL API that
@@ -51,14 +52,12 @@ function winesResponse({ search, after, first = 24 }: Variables) {
async function stubApi(page: Page) {
const searches: Variables[] = [];
- await page.route('**/project2/graphql', (route) => {
- const { operationName, variables } = route.request().postDataJSON() as {
- operationName: string;
- variables: Variables;
- };
- if (operationName !== 'SearchWines') return route.abort();
- searches.push(variables);
- return route.fulfill({ json: winesResponse(variables) });
+ // FilterOptions has no stub, so the filter panel shows its error. These tests are about the results.
+ await stubGraphQL(page, {
+ SearchWines: (variables: Variables) => {
+ searches.push(variables);
+ return winesResponse(variables);
+ },
});
return searches;
}
diff --git a/frontend/e2e/support/graphql.ts b/frontend/e2e/support/graphql.ts
new file mode 100644
index 0000000..dc3f0c1
--- /dev/null
+++ b/frontend/e2e/support/graphql.ts
@@ -0,0 +1,37 @@
+import type { Page } from '@playwright/test';
+
+/** What a stub gets: the variables the page sent with the operation. */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any -- each spec types its own variables.
+export type Handler = (variables: any) => unknown;
+
+/** The answer to `Me` when nobody is logged in. AuthProvider asks for it on every page. */
+export const LOGGED_OUT = { data: { me: null } };
+
+/**
+ * Stubs the GraphQL API, so the tests need no backend. Each operation is answered by the
+ * handler with the same name as the operation (`query Landing` → `Landing`).
+ *
+ * `Me` answers «nobody is logged in» unless the spec gives its own handler. An operation
+ * without a handler fails like a lost connection (route.abort), so a page never gets an
+ * answer meant for another operation.
+ *
+ * Returns the operation names in the order the page sent them, for tests that count requests.
+ */
+export async function stubGraphQL(page: Page, handlers: Record) {
+ const operations: string[] = [];
+ const all: Record = { Me: () => LOGGED_OUT, ...handlers };
+
+ await page.route('**/project2/graphql', (route) => {
+ const { operationName, variables } = route.request().postDataJSON() as {
+ operationName: string;
+ variables?: Record;
+ };
+ operations.push(operationName);
+
+ const handler = all[operationName];
+ if (!handler) return route.abort();
+ return route.fulfill({ json: handler(variables ?? {}) });
+ });
+
+ return operations;
+}
diff --git a/frontend/e2e/wine.spec.ts b/frontend/e2e/wine.spec.ts
index 98b7dfc..f487d00 100644
--- a/frontend/e2e/wine.spec.ts
+++ b/frontend/e2e/wine.spec.ts
@@ -1,5 +1,6 @@
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
+import { stubGraphQL } from './support/graphql';
/* E2E for the detail page. Runs against `vite preview` with a stubbed GraphQL API. */
const wine = {
@@ -35,33 +36,24 @@ const searchResult = {
};
async function stubApi(page: Page) {
- await page.route('**/project2/graphql', (route) => {
- const { operationName, variables } = route.request().postDataJSON() as {
- operationName: string;
- variables: { id?: string };
- };
- if (operationName === 'Wine') {
- return route.fulfill({
- json: { data: { wine: variables.id === wine.id ? wine : null } },
- });
- }
- if (operationName === 'WineReviews') {
- return route.fulfill({
- json: {
- data: {
- wine: {
- __typename: 'Wine',
- id: wine.id,
- studentRating: { __typename: 'StudentRating', average: null, count: 0 },
- ratingDistribution: [],
- reviews: [],
- },
- myReview: null,
- },
+ await stubGraphQL(page, {
+ Wine: (variables: { id?: string }) => ({
+ data: { wine: variables.id === wine.id ? wine : null },
+ }),
+ WineReviews: () => ({
+ data: {
+ wine: {
+ __typename: 'Wine',
+ id: wine.id,
+ studentRating: { __typename: 'StudentRating', average: null, count: 0 },
+ ratingDistribution: [],
+ reviews: [],
},
- });
- }
- return route.fulfill({ json: searchResult });
+ myReview: null,
+ },
+ }),
+ // Both the search page and «Lignende viner» on the wine page use SearchWines.
+ SearchWines: () => searchResult,
});
}
From 68b8e60b3f7eb94e16282e4136fda3149809c012 Mon Sep 17 00:00:00 2001
From: Magnus Andreas Igesund Nerland
Date: Mon, 16 Nov 2026 23:45:12 +0100
Subject: [PATCH 7/7] docs: reviews with login, manual testing guide (#65)
---
README.md | 21 ++++---
docs/api.md | 60 ++++++++++++++------
docs/manual-testing.md | 122 +++++++++++++++++++++++++++++++++++++++++
3 files changed, 177 insertions(+), 26 deletions(-)
create mode 100644 docs/manual-testing.md
diff --git a/README.md b/README.md
index ff425db..69cb764 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,8 @@ yet, depending on when the review is made.
| Wine detail page | Done | Facts, food pairing, the shared average, the rating distribution and student reviews at `/vin/:id` |
| Student reviews (stored in the database) | Done | 0.5–5 stars and an optional comment, saved and shown at once on the wine page. They count in the shared average |
| «Mine anmeldelser» page | Done | Shows the «Vil prøve» list. Own reviews come with login in the interface |
-| User accounts in the backend | Done | Register, login, logout and «who am I», with sessions in PostgreSQL. Not in the interface yet |
+| User accounts | Done | Register, log in and log out at `/konto`, with sessions in PostgreSQL and an `httpOnly` cookie |
+| Reviews tied to accounts | Done | Writing a review requires login, and the username is shown as the author. Older anonymous reviews are kept as «Anonym student» |
| Larger dataset on the VM | Done | Slim version: 1 007 wines and 150 000 ratings |
| Continuous integration (CI) | Not yet started | Needs a self-hosted runner |
@@ -110,8 +111,8 @@ This section describes what users can do. "Backend" means the API supports the f
| Student reviews | Done | Done | 0.5–5 stars in half stars and an optional comment, stored in PostgreSQL. Hover the left half of a star for half a star, or use the arrow keys. The page updates at once without a reload. One review per student per wine |
| Shared average and distribution | Done | Done | Student reviews count in the average together with X-Wines, also when sorting and filtering. The wine page shows how many gave each score |
| Wishlist ("Vil prøve") | Planned | Done | Saved in the browser and shown on «Mine anmeldelser». Moves to the backend when login is in the interface |
-| User accounts | Done | Planned | Register, login, logout and `me` in the API. Sessions in PostgreSQL with an `httpOnly` cookie. The interface comes next |
-| Anonymous ID | Done | Done | Reviews use a random ID stored in the browser until login is in the interface |
+| User accounts | Done | Done | Register, log in and log out at `/konto`. Errors are shown next to the field they are about, in Norwegian. Sessions in PostgreSQL with an `httpOnly` cookie |
+| Reviews with login | Done | Done | Only logged-in users can write, change or delete a review, and only their own. Visitors see the reviews and a link to log in, which brings them back to the wine. `User.reviews` lists a user's reviews for the profile page |
## Architecture and technology choices
@@ -246,7 +247,7 @@ We follow the principle from the course: measure, set a budget and show the numb
### Technical choices
- Code splitting per page with `React.lazy`. The landing page does not load the code for search and the detail page.
-- The landing page loads all its data in one GraphQL query, with only the fields it shows. An end-to-end test checks that only one request is sent.
+- The landing page loads all its content in one GraphQL query, with only the fields it shows. The only other request is `Me` (who is logged in), which every page shares and Apollo caches. An end-to-end test checks both.
- Search, filtering, sorting and pagination run in the database. A page returns at most 50 wines.
- The rating average is stored on the wine, so no query counts millions of rows.
- DataLoader batches the lookups a page needs, so a page of wines runs one query per field instead of one per wine.
@@ -278,7 +279,7 @@ and because the test was run over VPN. These are the "before" numbers. Compressi
| Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, mapping of API data, data hooks, components, the landing page, the wine page with reviews, the wishlist page, loading, empty and error states, and axe on each component | 269 in 28 files |
| Unit (backend) | Vitest | Parsing of X-Wines CSV files, building SQL for search, filtering and sorting, review validation, and passwords, sessions and rate limiting | 92 in 11 files (6 skipped: they need a test database) |
| End-to-end | Playwright with axe-core, desktop and mobile | Landing, search and detail pages with a stubbed API: one request per page load, debounce, search, filters, sorting, load more, reload, back button, from search to wine and back, the filter dialog on mobile, no hits, wine not found, API errors, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 50 (24 tests in 2 browser projects, and 2 for mobile only) |
-| API | Not set up yet | Resolvers against a test database: search, filtering, sorting and pagination | Planned |
+| API | Vitest with Apollo Server (`executeOperation`) | Login and reviews through real GraphQL requests, with a fake browser per user that keeps the cookie. The review tests run against a separate test database (`TEST_DATABASE_URL`), see [API](docs/api.md#database-tests) | Count again |
Counted on 16 November 2026. The skipped backend tests run the user store against a real database, and need `TEST_DATABASE_URL`.
@@ -367,7 +368,9 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a
### Next: towards the final submission
-- [ ] Login in the interface: forms for register and login, and reviews tied to the account instead of the anonymous ID.
+- [x] Login in the interface: forms for register and login, and reviews tied to the account instead of the anonymous ID.
+- [ ] Favourites with a top 4, «Vil prøve» and «Har prøvd» stored per user.
+- [ ] Profile page with the top 4, the lists and the user's reviews.
- [ ] Wishlist stored in the backend, so it follows the user between devices.
- [ ] Calmer landing page: less text, a separate «Om» page, and a burger menu on mobile.
- [ ] CI, an enforced coverage threshold, and eslint-plugin-jsx-a11y.
@@ -391,7 +394,8 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a
- Search matches the text as one phrase, so "noir pinot" finds nothing. Country is not part of the search text, because the country filter covers it.
- The cursors in the API hold an offset, which is slower deep into large results. To be solved together with the larger dataset.
- The database and its user are still called `vinmonopolet` and `vinmonopolet_app`, from before we switched dataset. Renaming would mean everyone rebuilding their database, so we kept the names.
-- Anyone can create any number of anonymous IDs, so there is nothing stopping someone from leaving many reviews. Login will fix that.
+- Reviews from before login have no account and are shown as «Anonym student». The old `student` table they belong to will be removed later.
+- One e2e test, checking «Rødvin» in the filter dialog on mobile, fails since the error handling changes. Tracked in its own issue.