From 9fb5b2d806445d9581994f7b2e9e74d10a7dcf2b Mon Sep 17 00:00:00 2001
From: SivertEikrem
Date: Mon, 16 Nov 2026 15:25:37 +0100
Subject: [PATCH 1/4] feat(auth): add login state for the frontend (#29)
---
frontend/src/features/auth/AuthProvider.tsx | 93 +++++++++++++++++++
.../src/features/auth/api/authMessages.ts | 42 +++++++++
frontend/src/features/auth/api/authQueries.ts | 49 ++++++++++
frontend/src/main.tsx | 7 +-
4 files changed, 189 insertions(+), 2 deletions(-)
create mode 100644 frontend/src/features/auth/AuthProvider.tsx
create mode 100644 frontend/src/features/auth/api/authMessages.ts
create mode 100644 frontend/src/features/auth/api/authQueries.ts
diff --git a/frontend/src/features/auth/AuthProvider.tsx b/frontend/src/features/auth/AuthProvider.tsx
new file mode 100644
index 0000000..4be87e9
--- /dev/null
+++ b/frontend/src/features/auth/AuthProvider.tsx
@@ -0,0 +1,93 @@
+import { createContext, use, useCallback, type ReactNode } from 'react';
+import { useApolloClient, useMutation, useQuery } from '@apollo/client/react';
+import {
+ LOGIN_MUTATION,
+ LOGOUT_MUTATION,
+ ME_QUERY,
+ REGISTER_MUTATION,
+ type MeData,
+ type User,
+} from './api/authQueries';
+import { authErrorMessage } from './api/authMessages';
+
+export interface Credentials {
+ username: string;
+ password: string;
+}
+
+export interface AuthContextValue {
+ /** null when nobody is logged in. */
+ user: User | null;
+ /** True until we know whether anyone is logged in. */
+ loading: boolean;
+ /** Returns a Norwegian message when it fails, and null when it worked. */
+ register: (credentials: Credentials) => Promise;
+ login: (credentials: Credentials) => Promise;
+ logout: () => Promise;
+}
+
+const AuthContext = createContext(null);
+
+/**
+ * Keeps the logged-in user for the whole app. The session itself lives in an httpOnly
+ * cookie that JavaScript cannot read, so `me` is what tells us who is logged in.
+ */
+export function AuthProvider({ children }: { children: ReactNode }) {
+ const client = useApolloClient();
+ const { data, loading } = useQuery(ME_QUERY);
+ const [registerMutation] = useMutation(REGISTER_MUTATION);
+ const [loginMutation] = useMutation(LOGIN_MUTATION);
+ const [logoutMutation] = useMutation(LOGOUT_MUTATION);
+
+ /** Runs a mutation and writes the new user into the cache, so the whole app sees it. */
+ const run = useCallback(
+ async (
+ mutate: typeof loginMutation,
+ credentials: Credentials,
+ field: 'login' | 'register',
+ ): Promise => {
+ try {
+ const result = await mutate({ variables: { input: credentials } });
+ const user = (result.data as Record | null)?.[field] ?? null;
+ client.writeQuery({ query: ME_QUERY, data: { me: user } });
+ return null;
+ } catch (error) {
+ return authErrorMessage(error);
+ }
+ },
+ [client],
+ );
+
+ const value: AuthContextValue = {
+ user: data?.me ?? null,
+ loading,
+ register: (credentials) => run(registerMutation, credentials, 'register'),
+ login: (credentials) => run(loginMutation, credentials, 'login'),
+ logout: async () => {
+ try {
+ await logoutMutation();
+ } finally {
+ // Whatever the server said, this browser is logged out. Everything cached
+ // was fetched as the old user, so the store starts over.
+ client.writeQuery({ query: ME_QUERY, data: { me: null } });
+ await client.resetStore();
+ }
+ },
+ };
+
+ return {children};
+}
+
+/** The logged-in user, or null. */
+export function useAuth(): AuthContextValue {
+ const value = use(AuthContext);
+ if (!value) throw new Error('useAuth must be used inside AuthProvider');
+ return value;
+}
+
+/** For pages behind RequireAuth, where there is always a user. */
+export function useAuthenticatedUser(): User {
+ const { user } = useAuth();
+ if (!user) throw new Error('useAuthenticatedUser must be used inside RequireAuth');
+ return user;
+}
\ No newline at end of file
diff --git a/frontend/src/features/auth/api/authMessages.ts b/frontend/src/features/auth/api/authMessages.ts
new file mode 100644
index 0000000..d6f753d
--- /dev/null
+++ b/frontend/src/features/auth/api/authMessages.ts
@@ -0,0 +1,42 @@
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+
+/** 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;
+
+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.',
+ 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.',
+};
+
+/**
+ * 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 {
+ if (CombinedGraphQLErrors.is(error)) {
+ for (const graphQLError of error.errors) {
+ const { code, reason } = (graphQLError.extensions ?? {}) as {
+ code?: string;
+ reason?: string;
+ };
+
+ if (reason && REASONS[reason]) return REASONS[reason];
+ if (code && CODES[code]) return CODES[code];
+ }
+ return 'Noe gikk galt. Prøv igjen.';
+ }
+
+ return 'Vi fikk ikke kontakt med serveren. Sjekk nettet og prøv igjen.';
+}
\ No newline at end of file
diff --git a/frontend/src/features/auth/api/authQueries.ts b/frontend/src/features/auth/api/authQueries.ts
new file mode 100644
index 0000000..ea7d1dc
--- /dev/null
+++ b/frontend/src/features/auth/api/authQueries.ts
@@ -0,0 +1,49 @@
+import { gql } from '@apollo/client';
+
+export interface User {
+ id: string;
+ username: string;
+ createdAt: string;
+}
+
+export interface MeData {
+ /** null when nobody is logged in. */
+ me: User | null;
+}
+
+/** Who is logged in. The browser sends the session cookie with every request. */
+export const ME_QUERY = gql`
+ query Me {
+ me {
+ id
+ username
+ createdAt
+ }
+ }
+`;
+
+export const REGISTER_MUTATION = gql`
+ mutation Register($input: CredentialsInput!) {
+ register(input: $input) {
+ id
+ username
+ createdAt
+ }
+ }
+`;
+
+export const LOGIN_MUTATION = gql`
+ mutation Login($input: CredentialsInput!) {
+ login(input: $input) {
+ id
+ username
+ createdAt
+ }
+ }
+`;
+
+export const LOGOUT_MUTATION = gql`
+ mutation Logout {
+ logout
+ }
+`;
\ No newline at end of file
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 0c9d8f3..edc6c8f 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -2,13 +2,16 @@ import { ApolloProvider } from '@apollo/client/react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './app/App';
+import { AuthProvider } from './features/auth/AuthProvider';
import { apolloClient } from './lib/apollo';
import './styles/global.css';
createRoot(document.getElementById('root')!).render(
-
+
+
+ ,
-);
+);
\ No newline at end of file
From 075447f0337f187d58ce94060ddc6b8ce9c64436 Mon Sep 17 00:00:00 2001
From: SivertEikrem
Date: Mon, 16 Nov 2026 15:38:41 +0100
Subject: [PATCH 2/4] feat(auth): add the account page and login in the menu
(#29)
---
frontend/src/app/App.tsx | 2 +
frontend/src/components/layout/Header.tsx | 13 ++-
.../src/features/auth/AccountPage.module.css | 36 ++++++++
frontend/src/features/auth/AccountPage.tsx | 77 ++++++++++++++++
frontend/src/features/auth/RequireAuth.tsx | 27 ++++++
.../auth/components/AuthForm.module.css | 60 +++++++++++++
.../src/features/auth/components/AuthForm.tsx | 88 +++++++++++++++++++
7 files changed, 302 insertions(+), 1 deletion(-)
create mode 100644 frontend/src/features/auth/AccountPage.module.css
create mode 100644 frontend/src/features/auth/AccountPage.tsx
create mode 100644 frontend/src/features/auth/RequireAuth.tsx
create mode 100644 frontend/src/features/auth/components/AuthForm.module.css
create mode 100644 frontend/src/features/auth/components/AuthForm.tsx
diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx
index a293b43..367712f 100644
--- a/frontend/src/app/App.tsx
+++ b/frontend/src/app/App.tsx
@@ -8,6 +8,7 @@ const LandingPage = lazy(() => import('../features/landing/LandingPage'));
const SearchPage = lazy(() => import('../features/search/SearchPage'));
const WinePage = lazy(() => import('../features/wine/WinePage'));
const MyPage = lazy(() => import('../features/my/MyPage'));
+const AccountPage = lazy(() => import('../features/auth/AccountPage'));
/** BASE_URL kommer fra `base` i vite.config.ts (f.eks. «/project2/»). */
const basename = import.meta.env.BASE_URL.replace(/\/$/, '') || '/';
@@ -20,6 +21,7 @@ export function AppRoutes() {
} />
} />
} />
+ } />
@@ -35,9 +38,17 @@ export function Header({ showSearch = true }: HeaderProps) {
Mine anmeldelser
+ {/* Nothing until we know who is logged in, so the menu does not flicker. */}
+ {!loading && (
+
+
+ {user ? user.username : 'Logg inn'}
+
+
+ )}
);
-}
+}
\ No newline at end of file
diff --git a/frontend/src/features/auth/AccountPage.module.css b/frontend/src/features/auth/AccountPage.module.css
new file mode 100644
index 0000000..dfbb9c9
--- /dev/null
+++ b/frontend/src/features/auth/AccountPage.module.css
@@ -0,0 +1,36 @@
+.page {
+ display: grid;
+ gap: var(--space-4);
+ max-width: 28rem;
+ padding-block: var(--space-7);
+}
+
+.intro {
+ color: var(--color-text-muted);
+}
+
+.switch {
+ color: var(--color-text-muted);
+}
+
+.link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--color-link);
+ font: inherit;
+ text-decoration: underline;
+ cursor: pointer;
+}
+
+.logout {
+ justify-self: start;
+ min-height: var(--tap-target);
+ padding: 0 var(--space-5);
+ border: 2px solid var(--color-link);
+ border-radius: var(--radius-pill);
+ font-weight: 700;
+ background: transparent;
+ color: var(--color-text);
+ cursor: pointer;
+}
\ No newline at end of file
diff --git a/frontend/src/features/auth/AccountPage.tsx b/frontend/src/features/auth/AccountPage.tsx
new file mode 100644
index 0000000..20b6474
--- /dev/null
+++ b/frontend/src/features/auth/AccountPage.tsx
@@ -0,0 +1,77 @@
+import { useState } from 'react';
+import { useNavigate, useLocation, Link } from 'react-router';
+import { useDocumentTitle } from '../../hooks/useDocumentTitle';
+import { AuthForm } from './components/AuthForm';
+import { useAuth, type Credentials } from './AuthProvider';
+import styles from './AccountPage.module.css';
+
+/** Where to go after logging in: back where the user came from, or to «Mine anmeldelser». */
+function nextPage(state: unknown): string {
+ const from = (state as { from?: unknown } | null)?.from;
+ return typeof from === 'string' && from.startsWith('/') && !from.startsWith('//') ? from : '/mine';
+}
+
+export default function AccountPage() {
+ const [mode, setMode] = useState<'login' | 'register'>('login');
+ const { user, loading, login, register, logout } = useAuth();
+ const navigate = useNavigate();
+ 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;
+ }
+
+ if (loading) {
+ return (
+
+
Konto
+
Laster …
+
+ );
+ }
+
+ if (user) {
+ return (
+
+
Min konto
+
+ Du er logget inn som {user.username}.
+
+
+ Gå til Mine anmeldelser
+
+
+
+ );
+ }
+
+ return (
+
+
{mode === 'login' ? 'Logg inn' : 'Lag bruker'}
+
+ {mode === 'login'
+ ? 'Logg inn for å ta vare på dommene og listene dine.'
+ : 'Du trenger bare et brukernavn og et passord. Vi lagrer ingen e-postadresse.'}
+
+
+ {/* A new key clears the fields when switching, so a password is never left behind. */}
+
+
+
+ {mode === 'login' ? 'Har du ikke bruker? ' : 'Har du bruker fra før? '}
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/frontend/src/features/auth/RequireAuth.tsx b/frontend/src/features/auth/RequireAuth.tsx
new file mode 100644
index 0000000..15296b4
--- /dev/null
+++ b/frontend/src/features/auth/RequireAuth.tsx
@@ -0,0 +1,27 @@
+import { Navigate, useLocation } from 'react-router';
+import type { ReactNode } from 'react';
+import { useAuth } from './AuthProvider';
+
+/**
+ * Pages that need a logged-in user. Sends the user to /konto with the page they
+ * wanted, so they come back here after logging in.
+ */
+export function RequireAuth({ children }: { children: ReactNode }) {
+ const { user, loading } = useAuth();
+ const location = useLocation();
+
+ // Until we know who is logged in, showing the login page would be wrong.
+ if (loading) {
+ return (
+
+
Laster …
+
+ );
+ }
+
+ if (!user) {
+ return ;
+ }
+
+ return children;
+}
\ No newline at end of file
diff --git a/frontend/src/features/auth/components/AuthForm.module.css b/frontend/src/features/auth/components/AuthForm.module.css
new file mode 100644
index 0000000..117c560
--- /dev/null
+++ b/frontend/src/features/auth/components/AuthForm.module.css
@@ -0,0 +1,60 @@
+.form {
+ display: grid;
+ gap: var(--space-4);
+}
+
+.field {
+ display: grid;
+ gap: var(--space-1);
+}
+
+.input {
+ width: 100%;
+ min-height: var(--tap-target);
+ padding: 0 var(--space-3);
+ border: 1px solid var(--color-border);
+ border-radius: var(--radius-lg);
+ font: inherit;
+ color: inherit;
+ background: transparent;
+}
+
+.input:focus-visible {
+ outline: 3px solid var(--color-focus);
+ outline-offset: 2px;
+}
+
+.help {
+ font-size: var(--text-sm);
+ color: var(--color-text-muted);
+}
+
+.error {
+ color: var(--color-danger, #b3261e);
+ font-weight: 600;
+}
+
+/* Empty: out of the grid so it adds no gap, but still in the accessibility tree. */
+.error:empty {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+}
+
+.submit {
+ min-height: var(--tap-target);
+ padding: 0 var(--space-5);
+ border: 2px solid var(--color-link);
+ border-radius: var(--radius-pill);
+ font-weight: 700;
+ background: var(--color-link);
+ color: var(--color-surface, #fff);
+ cursor: pointer;
+}
+
+.submit:disabled {
+ opacity: 0.6;
+ cursor: progress;
+}
\ No newline at end of file
diff --git a/frontend/src/features/auth/components/AuthForm.tsx b/frontend/src/features/auth/components/AuthForm.tsx
new file mode 100644
index 0000000..47d1290
--- /dev/null
+++ b/frontend/src/features/auth/components/AuthForm.tsx
@@ -0,0 +1,88 @@
+import { useId, useState, type FormEvent } from 'react';
+import { PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH, USERNAME_PATTERN } from '../api/authMessages';
+import type { Credentials } from '../AuthProvider';
+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;
+}
+
+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. */
+export function AuthForm({ mode, onSubmit }: AuthFormProps) {
+ const [username, setUsername] = useState('');
+ const [password, setPassword] = useState('');
+ const [error, setError] = useState('');
+ const [working, setWorking] = useState(false);
+ const usernameId = useId();
+ const passwordId = useId();
+ const helpId = useId();
+
+ async function handleSubmit(event: FormEvent) {
+ event.preventDefault();
+ setError('');
+ setWorking(true);
+ const message = await onSubmit({ username: username.trim().toLowerCase(), password });
+ setWorking(false);
+ if (message) setError(message);
+ }
+
+ return (
+
+ );
+}
\ No newline at end of file
From f61b2ed7f3b50045b6a1b7b4df426fbcdbbe3569 Mon Sep 17 00:00:00 2001
From: SivertEikrem
Date: Mon, 16 Nov 2026 16:01:21 +0100
Subject: [PATCH 3/4] feat(auth): log in, register and log out in the frontend
(#29)
---
frontend/src/app/App.test.tsx | 15 +-
.../src/components/layout/AppLayout.test.tsx | 28 ++--
frontend/src/components/layout/Header.tsx | 4 +-
.../src/features/auth/AccountPage.module.css | 2 +-
.../src/features/auth/AccountPage.test.tsx | 143 ++++++++++++++++++
frontend/src/features/auth/AccountPage.tsx | 9 +-
frontend/src/features/auth/AuthContext.ts | 20 +++
frontend/src/features/auth/AuthProvider.tsx | 38 +----
frontend/src/features/auth/RequireAuth.tsx | 5 +-
.../src/features/auth/api/authMessages.ts | 2 +-
frontend/src/features/auth/api/authQueries.ts | 2 +-
.../auth/components/AuthForm.module.css | 2 +-
.../src/features/auth/components/AuthForm.tsx | 8 +-
frontend/src/features/auth/useAuth.ts | 17 +++
.../wine/components/SimilarWines.test.tsx | 10 +-
frontend/src/main.tsx | 2 +-
16 files changed, 237 insertions(+), 70 deletions(-)
create mode 100644 frontend/src/features/auth/AccountPage.test.tsx
create mode 100644 frontend/src/features/auth/AuthContext.ts
create mode 100644 frontend/src/features/auth/useAuth.ts
diff --git a/frontend/src/app/App.test.tsx b/frontend/src/app/App.test.tsx
index 19da5e0..91b9ec1 100644
--- a/frontend/src/app/App.test.tsx
+++ b/frontend/src/app/App.test.tsx
@@ -6,14 +6,21 @@ import { MemoryRouter } from 'react-router';
import { createApolloCache } from '../lib/apollo';
import { searchMock } from '../test/searchMocks';
import { AppRoutes } from './App';
+import { AuthProvider } from '../features/auth/AuthProvider';
+import { ME_QUERY } from '../features/auth/api/authQueries';
+
+/** The header shows who is logged in, so the routes need AuthProvider. */
+const notLoggedIn = { request: { query: ME_QUERY }, result: { data: { me: null } } };
function renderRoute(route: string) {
render(
- 1).mock]} cache={createApolloCache()}>
+ 1).mock, notLoggedIn]} cache={createApolloCache()}>
-
-
-
+
+
+
+
+ ,
);
diff --git a/frontend/src/components/layout/AppLayout.test.tsx b/frontend/src/components/layout/AppLayout.test.tsx
index 42e01d4..5da2720 100644
--- a/frontend/src/components/layout/AppLayout.test.tsx
+++ b/frontend/src/components/layout/AppLayout.test.tsx
@@ -4,18 +4,28 @@ import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router';
import { focusHeadingWhenReady } from '../../lib/focus';
import { AppLayout } from './AppLayout';
+import { MockedProvider } from '@apollo/client/testing/react';
+import { AuthProvider } from '../../features/auth/AuthProvider';
+import { ME_QUERY } from '../../features/auth/api/authQueries';
+
+/** The header shows who is logged in, so the layout needs Apollo and AuthProvider. */
+const notLoggedIn = { request: { query: ME_QUERY }, result: { data: { me: null } } };
function renderApp(route = '/') {
return render(
-
-
- }>
- Forside} />
- Søk} />
- Mine} />
-
-
- ,
+
+
+
+
+ }>
+ Forside} />
+ Søk} />
+ Mine} />
+
+
+
+
+ ,
);
}
diff --git a/frontend/src/components/layout/Header.tsx b/frontend/src/components/layout/Header.tsx
index e24a0db..b721b04 100644
--- a/frontend/src/components/layout/Header.tsx
+++ b/frontend/src/components/layout/Header.tsx
@@ -1,5 +1,5 @@
import { Link, NavLink } from 'react-router';
-import { useAuth } from '../../features/auth/AuthProvider';
+import { useAuth } from '../../features/auth/useAuth';
import { SearchForm } from '../ui/SearchForm';
import { LogoMark } from './Logo';
import styles from './Header.module.css';
@@ -51,4 +51,4 @@ export function Header({ showSearch = true }: HeaderProps) {
);
-}
\ No newline at end of file
+}
diff --git a/frontend/src/features/auth/AccountPage.module.css b/frontend/src/features/auth/AccountPage.module.css
index dfbb9c9..b9d31e2 100644
--- a/frontend/src/features/auth/AccountPage.module.css
+++ b/frontend/src/features/auth/AccountPage.module.css
@@ -33,4 +33,4 @@
background: transparent;
color: var(--color-text);
cursor: pointer;
-}
\ No newline at end of file
+}
diff --git a/frontend/src/features/auth/AccountPage.test.tsx b/frontend/src/features/auth/AccountPage.test.tsx
new file mode 100644
index 0000000..ae413aa
--- /dev/null
+++ b/frontend/src/features/auth/AccountPage.test.tsx
@@ -0,0 +1,143 @@
+import { describe, expect, it } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { MockLink } from '@apollo/client/testing';
+import { MockedProvider } from '@apollo/client/testing/react';
+import { MemoryRouter, Route, Routes } from 'react-router';
+import { axe } from 'vitest-axe';
+import { createApolloCache } from '../../lib/apollo';
+import { LocationProbe } from '../../test/LocationProbe';
+import AccountPage from './AccountPage';
+import { AuthProvider } from './AuthProvider';
+import { LOGIN_MUTATION, LOGOUT_MUTATION, ME_QUERY, REGISTER_MUTATION } from './api/authQueries';
+
+const USER = {
+ __typename: 'User',
+ id: '1',
+ username: 'student',
+ createdAt: '2026-11-16T12:00:00.000Z',
+};
+
+const CREDENTIALS = { username: 'student', password: 'hemmelig123' };
+
+/** Who is logged in when the page opens. */
+function me(user: typeof USER | null): MockLink.MockedResponse {
+ return { request: { query: ME_QUERY }, result: { data: { me: user } } };
+}
+
+function login(result: MockLink.MockedResponse['result'] | Error): MockLink.MockedResponse {
+ const request = { query: LOGIN_MUTATION, variables: { input: CREDENTIALS } };
+ return result instanceof Error ? { request, error: result } : { request, result };
+}
+
+function renderPage(mocks: MockLink.MockedResponse[]) {
+ const user = userEvent.setup();
+ const result = render(
+
+
+
+
+ } />
+ Mine anmeldelser} />
+
+
+
+
+ ,
+ );
+ return { user, ...result };
+}
+
+/** Fills in the form and submits it. */
+async function signIn(user: ReturnType, button: string) {
+ await user.type(await screen.findByLabelText('Brukernavn'), CREDENTIALS.username);
+ await user.type(screen.getByLabelText('Passord'), CREDENTIALS.password);
+ await user.click(screen.getByRole('button', { name: button }));
+}
+
+describe('AccountPage', () => {
+ it('logs in and goes to «Mine anmeldelser»', async () => {
+ const { user } = renderPage([me(null), login({ data: { login: USER } })]);
+
+ await signIn(user, 'Logg inn');
+
+ expect(
+ await screen.findByRole('heading', { level: 1, name: 'Mine anmeldelser' }),
+ ).toBeInTheDocument();
+ });
+
+ it('shows a Norwegian message when the password is wrong', async () => {
+ const { user } = renderPage([
+ me(null),
+ {
+ request: { query: LOGIN_MUTATION, variables: { input: CREDENTIALS } },
+ result: {
+ errors: [{ message: 'Invalid credentials', extensions: { code: 'INVALID_CREDENTIALS' } }],
+ },
+ },
+ ]);
+
+ await signIn(user, 'Logg inn');
+
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent('Feil brukernavn eller passord.'),
+ );
+ });
+
+ it('explains which rule the username broke', async () => {
+ const { user } = renderPage([
+ me(null),
+ {
+ request: { query: REGISTER_MUTATION, variables: { input: CREDENTIALS } },
+ result: {
+ errors: [
+ {
+ message: 'Invalid username',
+ extensions: { code: 'BAD_USER_INPUT', reason: 'USERNAME_INVALID_CHARACTERS' },
+ },
+ ],
+ },
+ },
+ ]);
+
+ await user.click(await screen.findByRole('button', { name: 'Lag bruker' }));
+ await signIn(user, 'Lag bruker');
+
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent('små bokstaver, tall og understrek'),
+ );
+ });
+
+ it('says who is logged in, and can log out', async () => {
+ const { user } = renderPage([
+ me(USER),
+ { request: { query: LOGOUT_MUTATION }, result: { data: { logout: true } } },
+ me(null),
+ ]);
+
+ expect(await screen.findByText('student')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Logg ut' }));
+
+ // The page re-renders while `me` is fetched again, so look the button up each time.
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Logg inn' })).toBeInTheDocument(),
+ );
+ expect(screen.queryByText('student')).not.toBeInTheDocument();
+ });
+
+ it('tells the user when the server cannot be reached', async () => {
+ const { user } = renderPage([me(null), login(new Error('Nede'))]);
+
+ await signIn(user, 'Logg inn');
+
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent('Vi fikk ikke kontakt med serveren'),
+ );
+ });
+
+ it('has no axe violations', async () => {
+ const { container } = renderPage([me(null)]);
+ await screen.findByLabelText('Brukernavn');
+ expect(await axe(container)).toHaveNoViolations();
+ });
+});
diff --git a/frontend/src/features/auth/AccountPage.tsx b/frontend/src/features/auth/AccountPage.tsx
index 20b6474..99f916a 100644
--- a/frontend/src/features/auth/AccountPage.tsx
+++ b/frontend/src/features/auth/AccountPage.tsx
@@ -2,13 +2,16 @@ import { useState } from 'react';
import { useNavigate, useLocation, Link } from 'react-router';
import { useDocumentTitle } from '../../hooks/useDocumentTitle';
import { AuthForm } from './components/AuthForm';
-import { useAuth, type Credentials } from './AuthProvider';
+import type { Credentials } from './AuthContext';
+import { useAuth } from './useAuth';
import styles from './AccountPage.module.css';
/** Where to go after logging in: back where the user came from, or to «Mine anmeldelser». */
function nextPage(state: unknown): string {
const from = (state as { from?: unknown } | null)?.from;
- return typeof from === 'string' && from.startsWith('/') && !from.startsWith('//') ? from : '/mine';
+ return typeof from === 'string' && from.startsWith('/') && !from.startsWith('//')
+ ? from
+ : '/mine';
}
export default function AccountPage() {
@@ -74,4 +77,4 @@ export default function AccountPage() {
);
-}
\ No newline at end of file
+}
diff --git a/frontend/src/features/auth/AuthContext.ts b/frontend/src/features/auth/AuthContext.ts
new file mode 100644
index 0000000..c31a646
--- /dev/null
+++ b/frontend/src/features/auth/AuthContext.ts
@@ -0,0 +1,20 @@
+import { createContext } from 'react';
+import type { User } from './api/authQueries';
+
+export interface Credentials {
+ username: string;
+ password: string;
+}
+
+export interface AuthContextValue {
+ /** null when nobody is logged in. */
+ user: User | null;
+ /** True until we know whether anyone is logged in. */
+ loading: boolean;
+ /** Returns a Norwegian message when it fails, and null when it worked. */
+ register: (credentials: Credentials) => Promise;
+ login: (credentials: Credentials) => Promise;
+ logout: () => Promise;
+}
+
+export const AuthContext = createContext(null);
diff --git a/frontend/src/features/auth/AuthProvider.tsx b/frontend/src/features/auth/AuthProvider.tsx
index 4be87e9..b57376d 100644
--- a/frontend/src/features/auth/AuthProvider.tsx
+++ b/frontend/src/features/auth/AuthProvider.tsx
@@ -1,4 +1,4 @@
-import { createContext, use, useCallback, type ReactNode } from 'react';
+import { useCallback, type ReactNode } from 'react';
import { useApolloClient, useMutation, useQuery } from '@apollo/client/react';
import {
LOGIN_MUTATION,
@@ -9,24 +9,7 @@ import {
type User,
} from './api/authQueries';
import { authErrorMessage } from './api/authMessages';
-
-export interface Credentials {
- username: string;
- password: string;
-}
-
-export interface AuthContextValue {
- /** null when nobody is logged in. */
- user: User | null;
- /** True until we know whether anyone is logged in. */
- loading: boolean;
- /** Returns a Norwegian message when it fails, and null when it worked. */
- register: (credentials: Credentials) => Promise;
- login: (credentials: Credentials) => Promise;
- logout: () => Promise;
-}
-
-const AuthContext = createContext(null);
+import { AuthContext, type AuthContextValue, type Credentials } from './AuthContext';
/**
* Keeps the logged-in user for the whole app. The session itself lives in an httpOnly
@@ -70,24 +53,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// Whatever the server said, this browser is logged out. Everything cached
// was fetched as the old user, so the store starts over.
client.writeQuery({ query: ME_QUERY, data: { me: null } });
- await client.resetStore();
+ // resetStore rejects if a query fails to refetch. The user is logged out either way.
+ await client.resetStore().catch(() => undefined);
}
},
};
return {children};
}
-
-/** The logged-in user, or null. */
-export function useAuth(): AuthContextValue {
- const value = use(AuthContext);
- if (!value) throw new Error('useAuth must be used inside AuthProvider');
- return value;
-}
-
-/** For pages behind RequireAuth, where there is always a user. */
-export function useAuthenticatedUser(): User {
- const { user } = useAuth();
- if (!user) throw new Error('useAuthenticatedUser must be used inside RequireAuth');
- return user;
-}
\ No newline at end of file
diff --git a/frontend/src/features/auth/RequireAuth.tsx b/frontend/src/features/auth/RequireAuth.tsx
index 15296b4..2ca6013 100644
--- a/frontend/src/features/auth/RequireAuth.tsx
+++ b/frontend/src/features/auth/RequireAuth.tsx
@@ -1,7 +1,6 @@
import { Navigate, useLocation } from 'react-router';
import type { ReactNode } from 'react';
-import { useAuth } from './AuthProvider';
-
+import { useAuth } from './useAuth';
/**
* Pages that need a logged-in user. Sends the user to /konto with the page they
* wanted, so they come back here after logging in.
@@ -24,4 +23,4 @@ export function RequireAuth({ children }: { children: ReactNode }) {
}
return children;
-}
\ No newline at end of file
+}
diff --git a/frontend/src/features/auth/api/authMessages.ts b/frontend/src/features/auth/api/authMessages.ts
index d6f753d..8d0e24d 100644
--- a/frontend/src/features/auth/api/authMessages.ts
+++ b/frontend/src/features/auth/api/authMessages.ts
@@ -39,4 +39,4 @@ export function authErrorMessage(error: unknown): string {
}
return 'Vi fikk ikke kontakt med serveren. Sjekk nettet og prøv igjen.';
-}
\ No newline at end of file
+}
diff --git a/frontend/src/features/auth/api/authQueries.ts b/frontend/src/features/auth/api/authQueries.ts
index ea7d1dc..30ec282 100644
--- a/frontend/src/features/auth/api/authQueries.ts
+++ b/frontend/src/features/auth/api/authQueries.ts
@@ -46,4 +46,4 @@ export const LOGOUT_MUTATION = gql`
mutation Logout {
logout
}
-`;
\ No newline at end of file
+`;
diff --git a/frontend/src/features/auth/components/AuthForm.module.css b/frontend/src/features/auth/components/AuthForm.module.css
index 117c560..fa7daac 100644
--- a/frontend/src/features/auth/components/AuthForm.module.css
+++ b/frontend/src/features/auth/components/AuthForm.module.css
@@ -57,4 +57,4 @@
.submit:disabled {
opacity: 0.6;
cursor: progress;
-}
\ No newline at end of file
+}
diff --git a/frontend/src/features/auth/components/AuthForm.tsx b/frontend/src/features/auth/components/AuthForm.tsx
index 47d1290..dd75fb8 100644
--- a/frontend/src/features/auth/components/AuthForm.tsx
+++ b/frontend/src/features/auth/components/AuthForm.tsx
@@ -1,6 +1,6 @@
import { useId, useState, type FormEvent } from 'react';
import { PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH, USERNAME_PATTERN } from '../api/authMessages';
-import type { Credentials } from '../AuthProvider';
+import type { Credentials } from '../AuthContext';
import styles from './AuthForm.module.css';
interface AuthFormProps {
@@ -70,9 +70,7 @@ export function AuthForm({ mode, onSubmit }: AuthFormProps) {
maxLength={PASSWORD_MAX_LENGTH}
required
/>
- {mode === 'register' && (
-
Minst {PASSWORD_MIN_LENGTH} tegn.
- )}
+ {mode === 'register' &&
Minst {PASSWORD_MIN_LENGTH} tegn.
}
{/* Always in the DOM, so screen readers announce the message when it appears. */}
@@ -85,4 +83,4 @@ export function AuthForm({ mode, onSubmit }: AuthFormProps) {
);
-}
\ No newline at end of file
+}
diff --git a/frontend/src/features/auth/useAuth.ts b/frontend/src/features/auth/useAuth.ts
new file mode 100644
index 0000000..60f1597
--- /dev/null
+++ b/frontend/src/features/auth/useAuth.ts
@@ -0,0 +1,17 @@
+import { use } from 'react';
+import { AuthContext, type AuthContextValue } from './AuthContext';
+import type { User } from './api/authQueries';
+
+/** The logged-in user, or null. */
+export function useAuth(): AuthContextValue {
+ const value = use(AuthContext);
+ if (!value) throw new Error('useAuth must be used inside AuthProvider');
+ return value;
+}
+
+/** For pages behind RequireAuth, where there is always a user. */
+export function useAuthenticatedUser(): User {
+ const { user } = useAuth();
+ if (!user) throw new Error('useAuthenticatedUser must be used inside RequireAuth');
+ return user;
+}
diff --git a/frontend/src/features/wine/components/SimilarWines.test.tsx b/frontend/src/features/wine/components/SimilarWines.test.tsx
index 41532c6..7424523 100644
--- a/frontend/src/features/wine/components/SimilarWines.test.tsx
+++ b/frontend/src/features/wine/components/SimilarWines.test.tsx
@@ -54,11 +54,11 @@ function similar(wines: { id: string; name: string }[]): MockLink.MockedResponse
__typename: 'WineConnection',
totalCount: wines.length,
edges: wines.map(({ id, name }) => ({
- __typename: 'WineEdge',
- cursor: id,
- node: apiWine(id, name),
- })),
- pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null },
+ __typename: 'WineEdge',
+ cursor: id,
+ node: apiWine(id, name),
+ })),
+ pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null },
},
},
},
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index edc6c8f..b8da1b6 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -14,4 +14,4 @@ createRoot(document.getElementById('root')!).render(
,
-);
\ No newline at end of file
+);
From 773d37bab4e6a36965bc56858c5664b43f8347fe Mon Sep 17 00:00:00 2001
From: SivertEikrem
Date: Mon, 16 Nov 2026 20:33:44 +0100
Subject: [PATCH 4/4] fix(auth): keep the user logged in when logout fails
(#29)
---
.../src/features/auth/AccountPage.module.css | 13 +++++++++++++
.../src/features/auth/AccountPage.test.tsx | 17 +++++++++++++++++
frontend/src/features/auth/AccountPage.tsx | 10 +++++++++-
frontend/src/features/auth/AuthContext.ts | 2 +-
frontend/src/features/auth/AuthProvider.tsx | 18 +++++++++++-------
5 files changed, 51 insertions(+), 9 deletions(-)
diff --git a/frontend/src/features/auth/AccountPage.module.css b/frontend/src/features/auth/AccountPage.module.css
index b9d31e2..41ad3c2 100644
--- a/frontend/src/features/auth/AccountPage.module.css
+++ b/frontend/src/features/auth/AccountPage.module.css
@@ -34,3 +34,16 @@
color: var(--color-text);
cursor: pointer;
}
+
+.error {
+ color: var(--color-danger, #b3261e);
+ font-weight: 600;
+}
+
+.error:empty {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+}
diff --git a/frontend/src/features/auth/AccountPage.test.tsx b/frontend/src/features/auth/AccountPage.test.tsx
index ae413aa..1c9d22f 100644
--- a/frontend/src/features/auth/AccountPage.test.tsx
+++ b/frontend/src/features/auth/AccountPage.test.tsx
@@ -125,6 +125,23 @@ describe('AccountPage', () => {
expect(screen.queryByText('student')).not.toBeInTheDocument();
});
+ it('stays logged in and says so when logging out fails', async () => {
+ const { user } = renderPage([
+ me(USER),
+ { request: { query: LOGOUT_MUTATION }, error: new Error('Nede') },
+ ]);
+
+ expect(await screen.findByText('student')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Logg ut' }));
+
+ // Only the server can clear the session cookie, so a failed logout must not look like it worked.
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent('Vi fikk ikke kontakt med serveren'),
+ );
+ expect(screen.getByText('student')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Logg ut' })).toBeInTheDocument();
+ });
+
it('tells the user when the server cannot be reached', async () => {
const { user } = renderPage([me(null), login(new Error('Nede'))]);
diff --git a/frontend/src/features/auth/AccountPage.tsx b/frontend/src/features/auth/AccountPage.tsx
index 99f916a..6cb7dbe 100644
--- a/frontend/src/features/auth/AccountPage.tsx
+++ b/frontend/src/features/auth/AccountPage.tsx
@@ -15,6 +15,7 @@ function nextPage(state: unknown): string {
}
export default function AccountPage() {
+ const [logoutError, setLogoutError] = useState('');
const [mode, setMode] = useState<'login' | 'register'>('login');
const { user, loading, login, register, logout } = useAuth();
const navigate = useNavigate();
@@ -46,7 +47,14 @@ export default function AccountPage() {