forked from fahrPool/fahrPool
1547 lines
46 KiB
Markdown
1547 lines
46 KiB
Markdown
# Fundament (Auth & Rollen) Implementation Plan
|
||
|
||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||
|
||
**Goal:** Ein lauffähiges Fundament für "Aushilfsfahrer": self-hosted Supabase (Docker Compose), eine Next.js-App mit E-Mail/Passwort-Login, und ein Vier-Rollen-Modell (admin, disponent, fahrer, readonly) mit Row-Level-Security, auf dem alle künftigen Teilprojekte aufbauen.
|
||
|
||
**Architecture:** Next.js (App Router, TypeScript) spricht über `@supabase/ssr` mit einem self-hosted Supabase-Stack (Postgres, GoTrue, PostgREST, Storage, Kong, Studio, Postgres-Meta), der per Docker Compose auf demselben Server läuft. Die Rolle jedes Nutzers steckt in einer `profiles`-Tabelle und wird über Row-Level-Security-Policies durchgesetzt, nicht nur im Frontend.
|
||
|
||
**Tech Stack:** Next.js (App Router) + TypeScript, `@supabase/supabase-js` + `@supabase/ssr`, Vitest, Supabase CLI (`npx supabase`) für Migrationen & pgTAP-Tests, Docker Compose für den self-hosted Supabase-Stack (Postgres, GoTrue, PostgREST, Storage, Kong, Studio, Postgres-Meta).
|
||
|
||
## Global Constraints
|
||
|
||
- Vier Rollen exakt: `admin`, `disponent`, `fahrer`, `readonly` (Postgres-Enum-Werte, lowercase, wie in der Spec)
|
||
- Kein Self-Signup: `DISABLE_SIGNUP=true` in GoTrue, Accounts werden ausschließlich vom Admin angelegt
|
||
- Row Level Security ist Pflicht auf jeder fachlichen Tabelle (hier: `profiles`); künftige Teilprojekte übernehmen dasselbe Muster (`public.user_role()`-Helper-Funktion — nicht im `auth`-Schema, siehe Task 3)
|
||
- Package Manager: npm (konsistent mit dem Schwesterprojekt Rasenfriseur2)
|
||
- Testing: Vitest für Unit-Tests, pgTAP (`npx supabase test db`) für RLS-Tests. Kein E2E/Playwright in diesem Teilprojekt
|
||
- Out of Scope (siehe Spec): volle Nutzerverwaltungs-UI, Passwort-Reset-Flow, TLS/Reverse-Proxy-Konfiguration, Aufträge/Kanban/Routen/Zeiterfassung
|
||
- Out of Scope (Storage-Bilder-Transformation): `ENABLE_IMAGE_TRANSFORMATION=false`, kein `imgproxy`-Service — Bilder-Upload selbst ist ein späteres Teilprojekt, hier steht nur der `storage`-Service bereit
|
||
|
||
---
|
||
|
||
### Task 1: Next.js-Scaffold + Vitest-Setup
|
||
|
||
**Files:**
|
||
- Create: `web/` (per `create-next-app`)
|
||
- Modify: `web/next.config.ts` (Standalone-Output für Docker)
|
||
- Create: `web/vitest.config.ts`
|
||
- Modify: `web/package.json` (Test-Skripte)
|
||
|
||
**Interfaces:**
|
||
- Produces: lauffähiges Next.js-App-Router-Projekt in `web/` mit `npm run build`, `npm run dev`, `npm test`
|
||
|
||
- [ ] **Step 1: Next.js-Projekt scaffolden**
|
||
|
||
Run (im Repo-Root `C:\Users\Jonny\Projekte\Claude\Aushilfsfahrer`):
|
||
|
||
```bash
|
||
npx create-next-app@latest web --typescript --eslint --no-tailwind --no-react-compiler --app --no-src-dir --import-alias "@/*" --use-npm --disable-git --no-agents-md
|
||
```
|
||
|
||
Expected: Neuer Ordner `web/` mit `package.json`, `app/`, `tsconfig.json` etc. Kein verschachteltes `.git` (wegen `--disable-git` — das Repo-Root-Git verwaltet `web/` mit).
|
||
|
||
- [ ] **Step 2: Standalone-Output aktivieren (für Docker später)**
|
||
|
||
`web/next.config.ts` — ersetze den Inhalt durch:
|
||
|
||
```typescript
|
||
import type { NextConfig } from "next";
|
||
|
||
const nextConfig: NextConfig = {
|
||
output: "standalone",
|
||
};
|
||
|
||
export default nextConfig;
|
||
```
|
||
|
||
- [ ] **Step 3: Vitest installieren**
|
||
|
||
Run (im Ordner `web/`):
|
||
|
||
```bash
|
||
npm install --save-dev vitest
|
||
```
|
||
|
||
- [ ] **Step 4: Vitest konfigurieren**
|
||
|
||
Create `web/vitest.config.ts`:
|
||
|
||
```typescript
|
||
import { defineConfig } from "vitest/config";
|
||
|
||
export default defineConfig({
|
||
test: {
|
||
environment: "node",
|
||
env: {
|
||
NEXT_PUBLIC_SUPABASE_URL: "http://localhost:8000",
|
||
NEXT_PUBLIC_SUPABASE_ANON_KEY: "test-anon-key",
|
||
},
|
||
},
|
||
});
|
||
```
|
||
|
||
- [ ] **Step 5: Test-Skript ergänzen**
|
||
|
||
In `web/package.json`, im `"scripts"`-Block, ergänze:
|
||
|
||
```json
|
||
"test": "vitest run"
|
||
```
|
||
|
||
- [ ] **Step 6: Verifizieren**
|
||
|
||
Run (im Ordner `web/`):
|
||
|
||
```bash
|
||
npm run build
|
||
```
|
||
Expected: Build erfolgreich (Exit-Code 0), Next.js zeigt die Standard-Routen-Übersicht.
|
||
|
||
```bash
|
||
npm test
|
||
```
|
||
Expected: Vitest startet, meldet `No test files found` (es gibt noch keine Tests — das bestätigt, dass der Runner korrekt verdrahtet ist).
|
||
|
||
- [ ] **Step 7: Commit**
|
||
|
||
```bash
|
||
git add web/
|
||
git commit -m "chore: scaffold Next.js app with Vitest"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 2: Supabase-Lokalprojekt + `profiles`-Schema
|
||
|
||
**Files:**
|
||
- Create: `supabase/config.toml` (per `supabase init`)
|
||
- Create: `supabase/migrations/<timestamp>_profiles.sql`
|
||
|
||
**Interfaces:**
|
||
- Produces: `public.app_role` (Enum: `admin`, `disponent`, `fahrer`, `readonly`), Tabelle `public.profiles` (`id uuid` PK, `name text`, `role public.app_role`, `created_at timestamptz`), Funktion `public.handle_new_user()`, Trigger `on_auth_user_created` auf `auth.users`
|
||
|
||
**Voraussetzung:** Docker Desktop muss laufen (die Supabase-CLI startet für die Lokalentwicklung ihren eigenen, isolierten Container-Stack auf den Ports 54321–54324 — unabhängig vom Produktions-Docker-Compose aus Task 4).
|
||
|
||
- [ ] **Step 1: Supabase-Projekt initialisieren**
|
||
|
||
Run (im Repo-Root):
|
||
|
||
```bash
|
||
npx supabase@latest init
|
||
```
|
||
|
||
Expected: Ordner `supabase/` mit `config.toml` wird angelegt. Bei der Frage nach VS-Code-Settings/Deno kann mit den Standardwerten (Enter) bestätigt werden.
|
||
|
||
- [ ] **Step 2: Lokalen Stack starten**
|
||
|
||
```bash
|
||
npx supabase@latest start
|
||
```
|
||
|
||
Expected: Nach einigem Warten (Images werden gezogen) eine Ausgabe mit `API URL`, `DB URL`, `Studio URL` (u. a. `http://127.0.0.1:54323`), `anon key`, `service_role key`.
|
||
|
||
- [ ] **Step 3: Migration anlegen**
|
||
|
||
```bash
|
||
npx supabase@latest migration new profiles
|
||
```
|
||
|
||
Expected: Neue leere Datei `supabase/migrations/<timestamp>_profiles.sql`.
|
||
|
||
- [ ] **Step 4: Migration befüllen**
|
||
|
||
Ersetze den Inhalt der neu erstellten Datei durch:
|
||
|
||
```sql
|
||
create type public.app_role as enum ('admin', 'disponent', 'fahrer', 'readonly');
|
||
|
||
create table public.profiles (
|
||
id uuid primary key references auth.users (id) on delete cascade,
|
||
name text not null,
|
||
role public.app_role not null default 'readonly',
|
||
created_at timestamptz not null default now()
|
||
);
|
||
|
||
alter table public.profiles enable row level security;
|
||
|
||
create or replace function public.handle_new_user()
|
||
returns trigger
|
||
language plpgsql
|
||
security definer
|
||
set search_path = public
|
||
as $$
|
||
begin
|
||
insert into public.profiles (id, name, role)
|
||
values (
|
||
new.id,
|
||
coalesce(new.raw_user_meta_data ->> 'name', new.email),
|
||
'readonly'
|
||
);
|
||
return new;
|
||
end;
|
||
$$;
|
||
|
||
create trigger on_auth_user_created
|
||
after insert on auth.users
|
||
for each row execute function public.handle_new_user();
|
||
```
|
||
|
||
**Warum `security definer` + `set search_path = public`:** Der Trigger muss in `public.profiles` schreiben können, auch wenn der auslösende Insert (durch GoTrue) das nicht direkt darf; `set search_path` verhindert, dass die Funktion durch eine geänderte Search-Path-Einstellung auf ein falsches Schema zeigt (Standard-Absicherung für `security definer`-Funktionen in Postgres).
|
||
|
||
**Warum die Rolle fest auf `readonly` steht (nicht aus `raw_user_meta_data` gelesen):** `raw_user_meta_data` ist Teil des JWT/Anmeldedaten-Payloads und in bestimmten GoTrue-Flows (z. B. OAuth, Invite-Links) vom Endnutzer beeinflussbar. Würde die Rolle daraus übernommen, könnte sich ein Nutzer über manipulierte Metadaten selbst zum Admin machen — eine klassische Privilege-Escalation-Lücke. Jeder neue Nutzer startet deshalb immer als `readonly`; ein Admin muss die Rolle danach explizit setzen (siehe Task 4, Schritt 8).
|
||
|
||
- [ ] **Step 5: Migration anwenden und verifizieren**
|
||
|
||
```bash
|
||
npx supabase@latest db reset
|
||
```
|
||
|
||
Expected: Ausgabe zeigt, dass alle Migrationen (inkl. `profiles`) angewendet wurden, ohne Fehler.
|
||
|
||
Öffne `http://127.0.0.1:54323` (Studio) → SQL Editor → führe aus:
|
||
|
||
```sql
|
||
insert into auth.users (id, email) values (gen_random_uuid(), 'test@example.com');
|
||
select id, name, role from public.profiles where name = 'test@example.com';
|
||
```
|
||
|
||
Expected: Eine Zeile mit `role = readonly` (Default) — bestätigt, dass der Trigger korrekt greift.
|
||
|
||
- [ ] **Step 6: Commit**
|
||
|
||
```bash
|
||
git add supabase/
|
||
git commit -m "feat: add profiles table, role enum and auto-create trigger"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 3: RLS-Policies + pgTAP-Tests
|
||
|
||
**Files:**
|
||
- Create: `supabase/migrations/<timestamp>_rls_profiles.sql`
|
||
- Create: `supabase/tests/profiles_rls.sql`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `public.profiles`, `public.app_role` (Task 2)
|
||
- Produces: `public.user_role() returns public.app_role` (SQL-Helper, von künftigen Teilprojekten für eigene RLS-Policies wiederverwendbar), RLS-Policies auf `public.profiles`, Basis-Grants für `authenticated` auf `public.profiles`
|
||
|
||
**Hinweis (aus Task-3-Umsetzung übernommen):** Aktuelle self-hosted-Supabase-Instanzen entziehen der Migrations-Rolle `postgres` das `CREATE`-Recht auf dem Schema `auth` (Plattform-Lockdown, seit 2025-04-21). Eigene Funktionen können dort deshalb nicht mehr angelegt werden — der Helper heißt daher `public.user_role()`, nicht `auth.user_role()`. Außerdem hatte Task 2 keine `GRANT`-Statements für `authenticated` auf `public.profiles` gesetzt; RLS-Policies ohne zugrundeliegende Grants greifen nicht (Postgres prüft erst das Grant, dann die Policy) — diese Migration holt das nach.
|
||
|
||
- [ ] **Step 1: Migration anlegen**
|
||
|
||
```bash
|
||
npx supabase@latest migration new rls_profiles
|
||
```
|
||
|
||
- [ ] **Step 2: Grants + RLS-Policies + Helper-Funktion schreiben**
|
||
|
||
Ersetze den Inhalt der neuen Datei durch:
|
||
|
||
```sql
|
||
grant select, update on public.profiles to authenticated;
|
||
|
||
create or replace function public.user_role()
|
||
returns public.app_role
|
||
language sql
|
||
stable
|
||
security definer
|
||
set search_path = public
|
||
as $$
|
||
select role from public.profiles where id = auth.uid();
|
||
$$;
|
||
|
||
create policy "Nutzer sehen ihr eigenes Profil"
|
||
on public.profiles for select
|
||
using (auth.uid() = id);
|
||
|
||
create policy "Admins sehen alle Profile"
|
||
on public.profiles for select
|
||
using (public.user_role() = 'admin');
|
||
|
||
create policy "Admins aktualisieren alle Profile"
|
||
on public.profiles for update
|
||
using (public.user_role() = 'admin');
|
||
```
|
||
|
||
**Warum `public.user_role()` als `security definer`:** Ohne `security definer` würde die Funktion beim Lesen von `public.profiles` selbst wieder RLS auslösen (die Policies, die diese Funktion erst ermöglichen soll) — das würde in eine Endlosschleife/Zugriffsverweigerung laufen. `security definer` lässt die Funktion mit den Rechten des Funktions-Erstellers laufen und umgeht damit gezielt die RLS nur für diese eine, kontrollierte Abfrage.
|
||
|
||
- [ ] **Step 3: pgTAP-Test scaffolden**
|
||
|
||
```bash
|
||
npx supabase@latest test new profiles_rls
|
||
```
|
||
|
||
Expected: Neue Datei `supabase/tests/profiles_rls.sql` mit einem pgTAP-Grundgerüst.
|
||
|
||
- [ ] **Step 4: Test schreiben (vor der Migration ausführen, um sicherzugehen, dass er ohne Policies fehlschlägt)**
|
||
|
||
Ersetze den Inhalt von `supabase/tests/profiles_rls.sql` durch:
|
||
|
||
```sql
|
||
begin;
|
||
select plan(3);
|
||
|
||
insert into auth.users (id, email) values
|
||
('11111111-1111-1111-1111-111111111111', 'admin@test.local'),
|
||
('22222222-2222-2222-2222-222222222222', 'fahrer@test.local');
|
||
|
||
update public.profiles set role = 'admin' where id = '11111111-1111-1111-1111-111111111111';
|
||
update public.profiles set role = 'fahrer' where id = '22222222-2222-2222-2222-222222222222';
|
||
|
||
set local role authenticated;
|
||
set local request.jwt.claims to '{"sub": "22222222-2222-2222-2222-222222222222", "role": "authenticated"}';
|
||
|
||
select results_eq(
|
||
$$ select id from public.profiles order by id $$,
|
||
$$ values ('22222222-2222-2222-2222-222222222222'::uuid) $$,
|
||
'Fahrer sieht nur das eigene Profil'
|
||
);
|
||
|
||
reset role;
|
||
set local role authenticated;
|
||
set local request.jwt.claims to '{"sub": "11111111-1111-1111-1111-111111111111", "role": "authenticated"}';
|
||
|
||
select results_eq(
|
||
$$ select count(*)::int from public.profiles $$,
|
||
$$ values (2) $$,
|
||
'Admin sieht alle Profile'
|
||
);
|
||
|
||
select is(public.user_role(), 'admin'::public.app_role, 'public.user_role() liefert die Rolle des eingeloggten Nutzers');
|
||
|
||
select * from finish();
|
||
rollback;
|
||
```
|
||
|
||
- [ ] **Step 5: Reihenfolge sicherstellen — Test läuft gegen die Migration aus Step 2**
|
||
|
||
```bash
|
||
npx supabase@latest db reset
|
||
npx supabase@latest test db
|
||
```
|
||
|
||
Expected: `db reset` wendet beide Migrationen (`profiles`, `rls_profiles`) an. `test db` zeigt `1..3` und drei `ok`-Zeilen (`ok 1 - Fahrer sieht nur das eigene Profil`, `ok 2 - Admin sieht alle Profile`, `ok 3 - public.user_role() liefert die Rolle des eingeloggten Nutzers`).
|
||
|
||
- [ ] **Step 6: Commit**
|
||
|
||
```bash
|
||
git add supabase/
|
||
git commit -m "feat: add RLS policies and pgTAP tests for profiles"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 4: Self-Hosted Produktions-Stack (Docker Compose)
|
||
|
||
**Files:**
|
||
- Create: `docker-compose.yaml`
|
||
- Create: `.env.example`
|
||
- Create: `volumes/api/kong.yml`
|
||
- Create: `scripts/generate-secrets.js`
|
||
|
||
**Interfaces:**
|
||
- Produces: laufender Supabase-Stack unter `http://localhost:8000` (Kong, API), `http://127.0.0.1:8082` (Studio); `.env` mit `POSTGRES_PASSWORD`, `JWT_SECRET`, `ANON_KEY`, `SERVICE_ROLE_KEY`
|
||
|
||
**Hinweis zu Ports:** Der lokale CLI-Stack aus Task 2/3 läuft auf 54321–54324 und kollidiert nicht mit diesem Produktions-Stack (5432, 8000, 8082). Beide können parallel laufen.
|
||
|
||
- [ ] **Step 1: Secret-Generator schreiben**
|
||
|
||
Create `scripts/generate-secrets.js`:
|
||
|
||
```javascript
|
||
#!/usr/bin/env node
|
||
const crypto = require("crypto");
|
||
|
||
function base64url(buffer) {
|
||
return buffer
|
||
.toString("base64")
|
||
.replace(/\+/g, "-")
|
||
.replace(/\//g, "_")
|
||
.replace(/=+$/, "");
|
||
}
|
||
|
||
function signJwt(payload, secret) {
|
||
const header = { alg: "HS256", typ: "JWT" };
|
||
const encodedHeader = base64url(Buffer.from(JSON.stringify(header)));
|
||
const encodedPayload = base64url(Buffer.from(JSON.stringify(payload)));
|
||
const signature = base64url(
|
||
crypto
|
||
.createHmac("sha256", secret)
|
||
.update(`${encodedHeader}.${encodedPayload}`)
|
||
.digest()
|
||
);
|
||
return `${encodedHeader}.${encodedPayload}.${signature}`;
|
||
}
|
||
|
||
const jwtSecret = crypto.randomBytes(32).toString("base64");
|
||
const postgresPassword = crypto.randomBytes(24).toString("base64");
|
||
|
||
const iat = Math.floor(Date.now() / 1000);
|
||
const exp = iat + 10 * 365 * 24 * 60 * 60;
|
||
|
||
const anonKey = signJwt({ role: "anon", iss: "supabase", iat, exp }, jwtSecret);
|
||
const serviceRoleKey = signJwt(
|
||
{ role: "service_role", iss: "supabase", iat, exp },
|
||
jwtSecret
|
||
);
|
||
|
||
console.log(`POSTGRES_PASSWORD=${postgresPassword}`);
|
||
console.log(`JWT_SECRET=${jwtSecret}`);
|
||
console.log(`ANON_KEY=${anonKey}`);
|
||
console.log(`SERVICE_ROLE_KEY=${serviceRoleKey}`);
|
||
```
|
||
|
||
- [ ] **Step 2: Skript verifizieren**
|
||
|
||
```bash
|
||
node scripts/generate-secrets.js
|
||
```
|
||
|
||
Expected: 4 Zeilen `KEY=wert`. Verifiziere, dass `ANON_KEY` gültiges JWT-Format hat (3 durch Punkte getrennte Base64url-Teile) und die Payload stimmt:
|
||
|
||
```bash
|
||
node -e "const k=process.argv[1]; console.log(JSON.parse(Buffer.from(k.split('.')[1],'base64url').toString()))" "$(node scripts/generate-secrets.js | grep ANON_KEY | cut -d= -f2)"
|
||
```
|
||
|
||
Expected: `{ role: 'anon', iss: 'supabase', iat: ..., exp: ... }`
|
||
|
||
- [ ] **Step 3: `.env.example` schreiben**
|
||
|
||
Create `.env.example`:
|
||
|
||
```bash
|
||
# Mit `node scripts/generate-secrets.js` erzeugen und hier einsetzen:
|
||
POSTGRES_PASSWORD=
|
||
JWT_SECRET=
|
||
ANON_KEY=
|
||
SERVICE_ROLE_KEY=
|
||
|
||
POSTGRES_DB=postgres
|
||
POSTGRES_PORT=5432
|
||
JWT_EXPIRY=3600
|
||
|
||
SITE_URL=http://localhost:3000
|
||
ADDITIONAL_REDIRECT_URLS=
|
||
DISABLE_SIGNUP=true
|
||
ENABLE_EMAIL_AUTOCONFIRM=true
|
||
|
||
KONG_HTTP_PORT=8000
|
||
STUDIO_PORT=8082
|
||
|
||
# Muss von aussen erreichbar sein (Browser!), nicht der interne Docker-Hostname:
|
||
NEXT_PUBLIC_SUPABASE_URL=http://localhost:8000
|
||
NEXT_PUBLIC_SUPABASE_ANON_KEY=
|
||
```
|
||
|
||
- [ ] **Step 4: Kong-Konfiguration schreiben**
|
||
|
||
Create `volumes/api/kong.yml`:
|
||
|
||
```yaml
|
||
_format_version: "2.1"
|
||
_transform: true
|
||
|
||
consumers:
|
||
- username: anon
|
||
keyauth_credentials:
|
||
- key: $ANON_KEY
|
||
- username: service_role
|
||
keyauth_credentials:
|
||
- key: $SERVICE_ROLE_KEY
|
||
|
||
acls:
|
||
- consumer: anon
|
||
group: anon
|
||
- consumer: service_role
|
||
group: admin
|
||
|
||
services:
|
||
- name: auth-v1-open
|
||
url: http://auth:9999/verify
|
||
routes:
|
||
- name: auth-v1-open
|
||
strip_path: true
|
||
paths:
|
||
- /auth/v1/verify
|
||
plugins:
|
||
- name: cors
|
||
|
||
- name: auth-v1-open-callback
|
||
url: http://auth:9999/callback
|
||
routes:
|
||
- name: auth-v1-open-callback
|
||
strip_path: true
|
||
paths:
|
||
- /auth/v1/callback
|
||
plugins:
|
||
- name: cors
|
||
|
||
- name: auth-v1
|
||
url: http://auth:9999/
|
||
routes:
|
||
- name: auth-v1-all
|
||
strip_path: true
|
||
paths:
|
||
- /auth/v1/
|
||
plugins:
|
||
- name: cors
|
||
- name: key-auth
|
||
config:
|
||
hide_credentials: true
|
||
- name: acl
|
||
config:
|
||
hide_groups_header: true
|
||
allow:
|
||
- admin
|
||
- anon
|
||
|
||
- name: rest-v1
|
||
url: http://rest:3000/
|
||
routes:
|
||
- name: rest-v1-all
|
||
strip_path: true
|
||
paths:
|
||
- /rest/v1/
|
||
plugins:
|
||
- name: cors
|
||
- name: key-auth
|
||
config:
|
||
hide_credentials: true
|
||
- name: acl
|
||
config:
|
||
hide_groups_header: true
|
||
allow:
|
||
- admin
|
||
- anon
|
||
|
||
- name: storage-v1
|
||
url: http://storage:5000/
|
||
routes:
|
||
- name: storage-v1-all
|
||
strip_path: true
|
||
paths:
|
||
- /storage/v1/
|
||
plugins:
|
||
- name: cors
|
||
- name: key-auth
|
||
config:
|
||
hide_credentials: true
|
||
- name: acl
|
||
config:
|
||
hide_groups_header: true
|
||
allow:
|
||
- admin
|
||
- anon
|
||
```
|
||
|
||
- [ ] **Step 5: Docker Compose schreiben**
|
||
|
||
Create `docker-compose.yaml`:
|
||
|
||
```yaml
|
||
name: aushilfsfahrer
|
||
|
||
services:
|
||
db:
|
||
image: supabase/postgres:17.6.1.136
|
||
restart: unless-stopped
|
||
ports:
|
||
- "127.0.0.1:${POSTGRES_PORT}:5432"
|
||
environment:
|
||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||
POSTGRES_DB: ${POSTGRES_DB}
|
||
JWT_SECRET: ${JWT_SECRET}
|
||
JWT_EXP: ${JWT_EXPIRY}
|
||
volumes:
|
||
- ./volumes/db/data:/var/lib/postgresql/data
|
||
healthcheck:
|
||
test: ["CMD", "pg_isready", "-U", "postgres", "-h", "localhost"]
|
||
interval: 5s
|
||
timeout: 5s
|
||
retries: 10
|
||
|
||
auth:
|
||
image: supabase/gotrue:v2.189.0
|
||
restart: unless-stopped
|
||
depends_on:
|
||
db:
|
||
condition: service_healthy
|
||
environment:
|
||
GOTRUE_API_HOST: 0.0.0.0
|
||
GOTRUE_API_PORT: 9999
|
||
API_EXTERNAL_URL: ${NEXT_PUBLIC_SUPABASE_URL}
|
||
GOTRUE_DB_DRIVER: postgres
|
||
GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
|
||
GOTRUE_SITE_URL: ${SITE_URL}
|
||
GOTRUE_URI_ALLOW_LIST: ${ADDITIONAL_REDIRECT_URLS}
|
||
GOTRUE_DISABLE_SIGNUP: ${DISABLE_SIGNUP}
|
||
GOTRUE_JWT_ADMIN_ROLES: service_role
|
||
GOTRUE_JWT_AUD: authenticated
|
||
GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated
|
||
GOTRUE_JWT_EXP: ${JWT_EXPIRY}
|
||
GOTRUE_JWT_SECRET: ${JWT_SECRET}
|
||
GOTRUE_EXTERNAL_EMAIL_ENABLED: "true"
|
||
GOTRUE_MAILER_AUTOCONFIRM: ${ENABLE_EMAIL_AUTOCONFIRM}
|
||
healthcheck:
|
||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:9999/health"]
|
||
interval: 5s
|
||
timeout: 5s
|
||
retries: 10
|
||
|
||
rest:
|
||
image: postgrest/postgrest:v14.12
|
||
restart: unless-stopped
|
||
depends_on:
|
||
db:
|
||
condition: service_healthy
|
||
environment:
|
||
PGRST_DB_URI: postgres://authenticator:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
|
||
PGRST_DB_SCHEMAS: public
|
||
PGRST_DB_ANON_ROLE: anon
|
||
PGRST_JWT_SECRET: ${JWT_SECRET}
|
||
PGRST_DB_USE_LEGACY_GUCS: "false"
|
||
|
||
storage:
|
||
image: supabase/storage-api:v1.60.4
|
||
restart: unless-stopped
|
||
depends_on:
|
||
db:
|
||
condition: service_healthy
|
||
rest:
|
||
condition: service_started
|
||
environment:
|
||
ANON_KEY: ${ANON_KEY}
|
||
SERVICE_KEY: ${SERVICE_ROLE_KEY}
|
||
POSTGREST_URL: http://rest:3000
|
||
PGRST_JWT_SECRET: ${JWT_SECRET}
|
||
DATABASE_URL: postgres://supabase_storage_admin:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
|
||
FILE_SIZE_LIMIT: "52428800"
|
||
STORAGE_BACKEND: file
|
||
FILE_STORAGE_BACKEND_PATH: /var/lib/storage
|
||
TENANT_ID: stub
|
||
REGION: stub
|
||
GLOBAL_S3_BUCKET: stub
|
||
ENABLE_IMAGE_TRANSFORMATION: "false"
|
||
volumes:
|
||
- ./volumes/storage:/var/lib/storage
|
||
healthcheck:
|
||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:5000/status"]
|
||
interval: 5s
|
||
timeout: 5s
|
||
retries: 10
|
||
|
||
meta:
|
||
image: supabase/postgres-meta:v0.96.6
|
||
restart: unless-stopped
|
||
depends_on:
|
||
db:
|
||
condition: service_healthy
|
||
environment:
|
||
PG_META_PORT: 8080
|
||
PG_META_DB_HOST: db
|
||
PG_META_DB_PORT: 5432
|
||
PG_META_DB_NAME: ${POSTGRES_DB}
|
||
PG_META_DB_USER: supabase_admin
|
||
PG_META_DB_PASSWORD: ${POSTGRES_PASSWORD}
|
||
|
||
studio:
|
||
image: supabase/studio:2026.06.03-sha-0bca601
|
||
restart: unless-stopped
|
||
ports:
|
||
- "127.0.0.1:${STUDIO_PORT}:3000"
|
||
depends_on:
|
||
- meta
|
||
- rest
|
||
environment:
|
||
STUDIO_PG_META_URL: http://meta:8080
|
||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||
SUPABASE_URL: http://kong:8000
|
||
SUPABASE_PUBLIC_URL: ${NEXT_PUBLIC_SUPABASE_URL}
|
||
SUPABASE_ANON_KEY: ${ANON_KEY}
|
||
SUPABASE_SERVICE_KEY: ${SERVICE_ROLE_KEY}
|
||
|
||
kong:
|
||
image: kong/kong:3.9.1
|
||
restart: unless-stopped
|
||
ports:
|
||
- "${KONG_HTTP_PORT}:8000"
|
||
depends_on:
|
||
- auth
|
||
- rest
|
||
- storage
|
||
environment:
|
||
KONG_DATABASE: "off"
|
||
KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml
|
||
KONG_DNS_ORDER: LAST,A,CNAME
|
||
KONG_PLUGINS: request-transformer,cors,key-auth,acl
|
||
ANON_KEY: ${ANON_KEY}
|
||
SERVICE_ROLE_KEY: ${SERVICE_ROLE_KEY}
|
||
volumes:
|
||
- ./volumes/api/kong.yml:/home/kong/kong.yml:ro
|
||
```
|
||
|
||
**Warum Studio nur auf `127.0.0.1` gebunden ist:** Studio hat in diesem Fundament keinen eigenen Login-Schutz vor Kong (das würde Kong-Basic-Auth erfordern, die wir hier bewusst weglassen — YAGNI für ein internes Tool). Der Port ist deshalb nur lokal auf dem Server erreichbar; Fernzugriff läuft über SSH-Port-Forwarding (`ssh -L 8082:127.0.0.1:8082 server`), bis ein Reverse-Proxy mit Auth existiert (explizit Out-of-Scope, siehe Spec).
|
||
|
||
- [ ] **Step 6: `.env` erzeugen und Stack starten**
|
||
|
||
```bash
|
||
node scripts/generate-secrets.js
|
||
```
|
||
|
||
Kopiere die vier Zeilen in eine neue Datei `.env` (Kopie von `.env.example`, mit den generierten Werten für `POSTGRES_PASSWORD`, `JWT_SECRET`, `ANON_KEY`, `SERVICE_ROLE_KEY` — und `ANON_KEY` zusätzlich auch für `NEXT_PUBLIC_SUPABASE_ANON_KEY`).
|
||
|
||
```bash
|
||
docker compose up -d
|
||
docker compose ps
|
||
```
|
||
|
||
Expected: Alle Services `healthy` oder `running` (kong/studio haben keinen Healthcheck definiert, sind aber `running` sobald sie starten).
|
||
|
||
- [ ] **Step 7: Migrationen auf den Produktions-Stack anwenden**
|
||
|
||
```bash
|
||
npx supabase@latest db push --db-url "postgres://postgres:${POSTGRES_PASSWORD}@127.0.0.1:${POSTGRES_PORT}/${POSTGRES_DB}"
|
||
```
|
||
|
||
(Setze `${POSTGRES_PASSWORD}` etc. aus deiner `.env` ein, oder exportiere sie vorher als Shell-Variablen.)
|
||
|
||
Expected: Ausgabe listet beide Migrationen (`profiles`, `rls_profiles`) als angewendet.
|
||
|
||
- [ ] **Step 8: Ersten Admin-Nutzer anlegen**
|
||
|
||
Öffne `http://127.0.0.1:8082` (Studio) → Authentication → Add user → E-Mail/Passwort setzen, unter "User Metadata" (JSON) optional:
|
||
|
||
```json
|
||
{ "name": "Admin" }
|
||
```
|
||
|
||
Der Trigger legt das Profil mit `role = readonly` an (die Rolle wird bewusst nie aus User Metadata übernommen, siehe Task 2 — Privilege-Escalation-Schutz). Setze die Rolle deshalb danach explizit im SQL Editor:
|
||
|
||
```sql
|
||
update public.profiles set role = 'admin' where name = 'Admin';
|
||
select name, role from public.profiles;
|
||
```
|
||
Expected: Zeile zeigt `role = admin`.
|
||
|
||
- [ ] **Step 9: `.gitignore` ergänzen (Datenverzeichnisse nicht versionieren)**
|
||
|
||
Modify `.gitignore` — ergänze:
|
||
|
||
```
|
||
volumes/db/data/
|
||
volumes/storage/
|
||
.env
|
||
```
|
||
|
||
- [ ] **Step 10: Commit**
|
||
|
||
```bash
|
||
git add docker-compose.yaml .env.example volumes/api/kong.yml scripts/generate-secrets.js .gitignore
|
||
git commit -m "feat: add self-hosted Supabase stack via Docker Compose"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 5: Supabase-Client-Helfer (Browser & Server) für Next.js
|
||
|
||
**Files:**
|
||
- Create: `web/lib/supabase/client.ts`
|
||
- Create: `web/lib/supabase/client.test.ts`
|
||
- Create: `web/lib/supabase/server.ts`
|
||
- Create: `web/.env.local.example`
|
||
- Modify: `web/.gitignore` (falls `.env.local` nicht schon ignoriert wird — `create-next-app` ignoriert `.env*.local` standardmäßig, prüfen statt duplizieren)
|
||
|
||
**Interfaces:**
|
||
- Consumes: `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY` (Env-Vars, aus Task 4s `.env`)
|
||
- Produces: `createClient(): SupabaseClient` (Browser, `web/lib/supabase/client.ts`), `createClient(): Promise<SupabaseClient>` (Server, `web/lib/supabase/server.ts`) — von Task 6/7/8 verwendet
|
||
|
||
- [ ] **Step 1: Pakete installieren**
|
||
|
||
Run (in `web/`):
|
||
|
||
```bash
|
||
npm install @supabase/supabase-js @supabase/ssr
|
||
```
|
||
|
||
- [ ] **Step 2: Fehlschlagenden Test für den Browser-Client schreiben**
|
||
|
||
Create `web/lib/supabase/client.test.ts`:
|
||
|
||
```typescript
|
||
import { describe, expect, it } from "vitest";
|
||
import { createClient } from "./client";
|
||
|
||
describe("createClient (Browser)", () => {
|
||
it("erstellt einen Supabase-Client mit auth- und from-Methoden", () => {
|
||
const client = createClient();
|
||
expect(typeof client.auth.getUser).toBe("function");
|
||
expect(typeof client.from).toBe("function");
|
||
});
|
||
});
|
||
```
|
||
|
||
- [ ] **Step 3: Test ausführen, erwartet: FAIL**
|
||
|
||
```bash
|
||
npm test
|
||
```
|
||
Expected: FAIL — `Cannot find module './client'` (Datei existiert noch nicht).
|
||
|
||
- [ ] **Step 4: Browser-Client implementieren**
|
||
|
||
Create `web/lib/supabase/client.ts`:
|
||
|
||
```typescript
|
||
import { createBrowserClient } from "@supabase/ssr";
|
||
|
||
export function createClient() {
|
||
return createBrowserClient(
|
||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
|
||
);
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 5: Test ausführen, erwartet: PASS**
|
||
|
||
```bash
|
||
npm test
|
||
```
|
||
Expected: PASS (1 Test).
|
||
|
||
- [ ] **Step 6: Server-Client implementieren**
|
||
|
||
Create `web/lib/supabase/server.ts`:
|
||
|
||
```typescript
|
||
import { createServerClient } from "@supabase/ssr";
|
||
import { cookies } from "next/headers";
|
||
|
||
export async function createClient() {
|
||
const cookieStore = await cookies();
|
||
|
||
return createServerClient(
|
||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
||
{
|
||
cookies: {
|
||
getAll() {
|
||
return cookieStore.getAll();
|
||
},
|
||
setAll(cookiesToSet) {
|
||
try {
|
||
cookiesToSet.forEach(({ name, value, options }) =>
|
||
cookieStore.set(name, value, options)
|
||
);
|
||
} catch {
|
||
// Cookies können nicht gesetzt werden, wenn dies aus einer
|
||
// Server-Component-Render-Phase heraus aufgerufen wird
|
||
// (nur lesbar) — die Middleware (Task 7) übernimmt in dem Fall
|
||
// das Session-Refresh.
|
||
}
|
||
},
|
||
},
|
||
}
|
||
);
|
||
}
|
||
```
|
||
|
||
**Kein automatisierter Test für `server.ts`:** `next/headers` funktioniert nur innerhalb eines echten Next.js-Request-Kontexts (Server Component / Route Handler), nicht in einem isolierten Vitest-Lauf. Dieser Helfer wird indirekt über die Login-Seite (Task 6) und das Dashboard (Task 8) manuell verifiziert.
|
||
|
||
- [ ] **Step 7: `.env.local.example` anlegen**
|
||
|
||
Create `web/.env.local.example`:
|
||
|
||
```bash
|
||
NEXT_PUBLIC_SUPABASE_URL=http://localhost:8000
|
||
NEXT_PUBLIC_SUPABASE_ANON_KEY=
|
||
```
|
||
|
||
- [ ] **Step 8: Lokale `.env.local` befüllen (nicht committen)**
|
||
|
||
Kopiere `web/.env.local.example` zu `web/.env.local` und trage den `ANON_KEY` aus der Root-`.env` (Task 4) ein. Prüfe, dass `web/.gitignore` bereits `.env*.local` enthält (Standard bei `create-next-app`) — falls nicht, ergänze es.
|
||
|
||
- [ ] **Step 9: Commit**
|
||
|
||
```bash
|
||
git add web/lib/supabase/ web/.env.local.example web/package.json web/package-lock.json web/.gitignore
|
||
git commit -m "feat: add Supabase browser and server client helpers"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 6: Login (Server Action, Validierung, Tests)
|
||
|
||
**Files:**
|
||
- Create: `web/lib/validate-login.ts`
|
||
- Create: `web/lib/validate-login.test.ts`
|
||
- Create: `web/app/login/actions.ts`
|
||
- Create: `web/app/login/page.tsx`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `createClient()` aus `web/lib/supabase/server.ts` (Task 5)
|
||
- Produces: `validateLogin(input: LoginInput): LoginValidationResult`, `LoginInput`, `LoginValidationResult` (Typen); Server Actions `login(formData: FormData): Promise<void>`, `logout(): Promise<void>` (von Task 8s `LogoutButton` verwendet)
|
||
|
||
- [ ] **Step 1: Fehlschlagende Tests für die Validierung schreiben**
|
||
|
||
Create `web/lib/validate-login.test.ts`:
|
||
|
||
```typescript
|
||
import { describe, expect, it } from "vitest";
|
||
import { validateLogin } from "./validate-login";
|
||
|
||
describe("validateLogin", () => {
|
||
it("akzeptiert gültige E-Mail und Passwort", () => {
|
||
const result = validateLogin({ email: "admin@example.com", password: "geheim123" });
|
||
expect(result).toEqual({
|
||
valid: true,
|
||
email: "admin@example.com",
|
||
password: "geheim123",
|
||
});
|
||
});
|
||
|
||
it("lehnt eine fehlende E-Mail ab", () => {
|
||
const result = validateLogin({ email: "", password: "geheim123" });
|
||
expect(result).toEqual({
|
||
valid: false,
|
||
error: "Bitte eine gültige E-Mail-Adresse eingeben.",
|
||
});
|
||
});
|
||
|
||
it("lehnt eine ungültige E-Mail ab", () => {
|
||
const result = validateLogin({ email: "keine-email", password: "geheim123" });
|
||
expect(result.valid).toBe(false);
|
||
});
|
||
|
||
it("lehnt ein fehlendes Passwort ab", () => {
|
||
const result = validateLogin({ email: "admin@example.com", password: "" });
|
||
expect(result).toEqual({
|
||
valid: false,
|
||
error: "Bitte ein Passwort eingeben.",
|
||
});
|
||
});
|
||
|
||
it("trimmt Leerzeichen in der E-Mail", () => {
|
||
const result = validateLogin({ email: " admin@example.com ", password: "geheim123" });
|
||
expect(result).toEqual({
|
||
valid: true,
|
||
email: "admin@example.com",
|
||
password: "geheim123",
|
||
});
|
||
});
|
||
});
|
||
```
|
||
|
||
- [ ] **Step 2: Tests ausführen, erwartet: FAIL**
|
||
|
||
```bash
|
||
npm test
|
||
```
|
||
Expected: FAIL — `Cannot find module './validate-login'`.
|
||
|
||
- [ ] **Step 3: Validierung implementieren**
|
||
|
||
Create `web/lib/validate-login.ts`:
|
||
|
||
```typescript
|
||
export type LoginInput = {
|
||
email: FormDataEntryValue | null;
|
||
password: FormDataEntryValue | null;
|
||
};
|
||
|
||
export type LoginValidationResult =
|
||
| { valid: true; email: string; password: string }
|
||
| { valid: false; error: string };
|
||
|
||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||
|
||
export function validateLogin(input: LoginInput): LoginValidationResult {
|
||
const email = typeof input.email === "string" ? input.email.trim() : "";
|
||
const password = typeof input.password === "string" ? input.password : "";
|
||
|
||
if (!email || !EMAIL_REGEX.test(email)) {
|
||
return { valid: false, error: "Bitte eine gültige E-Mail-Adresse eingeben." };
|
||
}
|
||
if (!password) {
|
||
return { valid: false, error: "Bitte ein Passwort eingeben." };
|
||
}
|
||
return { valid: true, email, password };
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 4: Tests ausführen, erwartet: PASS**
|
||
|
||
```bash
|
||
npm test
|
||
```
|
||
Expected: PASS (5 Tests).
|
||
|
||
- [ ] **Step 5: Server Actions implementieren**
|
||
|
||
Create `web/app/login/actions.ts`:
|
||
|
||
```typescript
|
||
"use server";
|
||
|
||
import { redirect } from "next/navigation";
|
||
import { createClient } from "@/lib/supabase/server";
|
||
import { validateLogin } from "@/lib/validate-login";
|
||
|
||
export async function login(formData: FormData): Promise<void> {
|
||
const validation = validateLogin({
|
||
email: formData.get("email"),
|
||
password: formData.get("password"),
|
||
});
|
||
|
||
if (!validation.valid) {
|
||
redirect(`/login?error=${encodeURIComponent(validation.error)}`);
|
||
}
|
||
|
||
const supabase = await createClient();
|
||
const { error } = await supabase.auth.signInWithPassword({
|
||
email: validation.email,
|
||
password: validation.password,
|
||
});
|
||
|
||
if (error) {
|
||
redirect(`/login?error=${encodeURIComponent("E-Mail oder Passwort ist falsch.")}`);
|
||
}
|
||
|
||
redirect("/dashboard");
|
||
}
|
||
|
||
export async function logout(): Promise<void> {
|
||
const supabase = await createClient();
|
||
await supabase.auth.signOut();
|
||
redirect("/login");
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 6: Login-Seite implementieren**
|
||
|
||
Create `web/app/login/page.tsx`:
|
||
|
||
```tsx
|
||
import { login } from "./actions";
|
||
|
||
export default async function LoginPage({
|
||
searchParams,
|
||
}: {
|
||
searchParams: Promise<{ error?: string }>;
|
||
}) {
|
||
const { error } = await searchParams;
|
||
|
||
return (
|
||
<main>
|
||
<h1>Anmelden</h1>
|
||
{error && <p role="alert">{error}</p>}
|
||
<form action={login}>
|
||
<div>
|
||
<label htmlFor="email">E-Mail</label>
|
||
<input id="email" name="email" type="email" required />
|
||
</div>
|
||
<div>
|
||
<label htmlFor="password">Passwort</label>
|
||
<input id="password" name="password" type="password" required />
|
||
</div>
|
||
<button type="submit">Anmelden</button>
|
||
</form>
|
||
</main>
|
||
);
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 7: Manuell verifizieren**
|
||
|
||
Stelle sicher, dass der Docker-Compose-Stack aus Task 4 läuft und `web/.env.local` gesetzt ist (Task 5, Step 8). Dann:
|
||
|
||
```bash
|
||
npm run dev
|
||
```
|
||
|
||
Öffne `http://localhost:3000/login`:
|
||
- Falsches Passwort eingeben → Meldung "E-Mail oder Passwort ist falsch." erscheint auf der Seite
|
||
- Mit dem in Task 4/Step 8 angelegten Admin-Account einloggen → Redirect nach `/dashboard` (404 ist an dieser Stelle erwartet, die Seite kommt erst in Task 8 — wichtig ist der Redirect selbst)
|
||
|
||
- [ ] **Step 8: Commit**
|
||
|
||
```bash
|
||
git add web/lib/validate-login.ts web/lib/validate-login.test.ts web/app/login/
|
||
git commit -m "feat: add login page with server action and validation"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 7: Middleware (Session-Refresh + Redirect-Guard)
|
||
|
||
**Files:**
|
||
- Create: `web/lib/supabase/middleware.ts`
|
||
- Create: `web/middleware.ts`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`
|
||
- Produces: `updateSession(request: NextRequest): Promise<NextResponse>`; jede Route außer `/login` erfordert ab jetzt eine Session
|
||
|
||
- [ ] **Step 1: Middleware-Helfer implementieren**
|
||
|
||
Create `web/lib/supabase/middleware.ts`:
|
||
|
||
```typescript
|
||
import { createServerClient } from "@supabase/ssr";
|
||
import { NextResponse, type NextRequest } from "next/server";
|
||
|
||
export async function updateSession(request: NextRequest) {
|
||
let supabaseResponse = NextResponse.next({ request });
|
||
|
||
const supabase = createServerClient(
|
||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
||
{
|
||
cookies: {
|
||
getAll() {
|
||
return request.cookies.getAll();
|
||
},
|
||
setAll(cookiesToSet) {
|
||
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value));
|
||
supabaseResponse = NextResponse.next({ request });
|
||
cookiesToSet.forEach(({ name, value, options }) =>
|
||
supabaseResponse.cookies.set(name, value, options)
|
||
);
|
||
},
|
||
},
|
||
}
|
||
);
|
||
|
||
const {
|
||
data: { user },
|
||
} = await supabase.auth.getUser();
|
||
|
||
const isLoginPage = request.nextUrl.pathname.startsWith("/login");
|
||
|
||
if (!user && !isLoginPage) {
|
||
const url = request.nextUrl.clone();
|
||
url.pathname = "/login";
|
||
return NextResponse.redirect(url);
|
||
}
|
||
|
||
if (user && isLoginPage) {
|
||
const url = request.nextUrl.clone();
|
||
url.pathname = "/dashboard";
|
||
return NextResponse.redirect(url);
|
||
}
|
||
|
||
return supabaseResponse;
|
||
}
|
||
```
|
||
|
||
**Warum `supabase.auth.getUser()` statt `getSession()`:** `getSession()` liest die Session nur aus dem Cookie, ohne das JWT beim Auth-Server zu verifizieren — ein manipuliertes Cookie würde unbemerkt durchgehen. `getUser()` verifiziert das Token aktiv gegen GoTrue und ist der von Supabase empfohlene sichere Weg in Middleware/Server-Code.
|
||
|
||
- [ ] **Step 2: Middleware-Einstiegspunkt anlegen**
|
||
|
||
Create `web/middleware.ts`:
|
||
|
||
```typescript
|
||
import { type NextRequest } from "next/server";
|
||
import { updateSession } from "@/lib/supabase/middleware";
|
||
|
||
export async function middleware(request: NextRequest) {
|
||
return await updateSession(request);
|
||
}
|
||
|
||
export const config = {
|
||
matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"],
|
||
};
|
||
```
|
||
|
||
- [ ] **Step 3: Manuell verifizieren**
|
||
|
||
```bash
|
||
npm run dev
|
||
```
|
||
|
||
- Im Browser abgemeldet `http://localhost:3000/dashboard` aufrufen → Redirect zu `/login`
|
||
- Als Admin einloggen (Task 6) → Redirect zu `/dashboard`
|
||
- Eingeloggt `http://localhost:3000/login` aufrufen → Redirect zu `/dashboard` (kein erneutes Login-Formular)
|
||
|
||
- [ ] **Step 4: Commit**
|
||
|
||
```bash
|
||
git add web/middleware.ts web/lib/supabase/middleware.ts
|
||
git commit -m "feat: add auth middleware with session refresh and redirects"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 8: Root-Layout, Navigation, Dashboard
|
||
|
||
**Files:**
|
||
- Create: `web/lib/auth/roles.ts`
|
||
- Create: `web/lib/auth/roles.test.ts`
|
||
- Create: `web/lib/auth/profile.ts`
|
||
- Modify: `web/app/layout.tsx`
|
||
- Create: `web/components/NavLinks.tsx`
|
||
- Create: `web/components/LogoutButton.tsx`
|
||
- Create: `web/app/dashboard/page.tsx`
|
||
- Modify: `web/app/page.tsx`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `createClient()` (`web/lib/supabase/server.ts`, Task 5), `logout()` (`web/app/login/actions.ts`, Task 6)
|
||
- Produces: `type Role`, `canManageUsers(role: Role): boolean`; `type Profile`, `type ProfileResult`, `loadProfile(): Promise<ProfileResult>`
|
||
|
||
- [ ] **Step 1: Fehlschlagenden Test für die Rollen-Logik schreiben**
|
||
|
||
Create `web/lib/auth/roles.test.ts`:
|
||
|
||
```typescript
|
||
import { describe, expect, it } from "vitest";
|
||
import { canManageUsers } from "./roles";
|
||
|
||
describe("canManageUsers", () => {
|
||
it("erlaubt Nutzerverwaltung für admin", () => {
|
||
expect(canManageUsers("admin")).toBe(true);
|
||
});
|
||
|
||
it("verbietet Nutzerverwaltung für disponent", () => {
|
||
expect(canManageUsers("disponent")).toBe(false);
|
||
});
|
||
|
||
it("verbietet Nutzerverwaltung für fahrer", () => {
|
||
expect(canManageUsers("fahrer")).toBe(false);
|
||
});
|
||
|
||
it("verbietet Nutzerverwaltung für readonly", () => {
|
||
expect(canManageUsers("readonly")).toBe(false);
|
||
});
|
||
});
|
||
```
|
||
|
||
- [ ] **Step 2: Test ausführen, erwartet: FAIL**
|
||
|
||
```bash
|
||
npm test
|
||
```
|
||
Expected: FAIL — `Cannot find module './roles'`.
|
||
|
||
- [ ] **Step 3: Rollen-Modul implementieren**
|
||
|
||
Create `web/lib/auth/roles.ts`:
|
||
|
||
```typescript
|
||
export type Role = "admin" | "disponent" | "fahrer" | "readonly";
|
||
|
||
export function canManageUsers(role: Role): boolean {
|
||
return role === "admin";
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 4: Test ausführen, erwartet: PASS**
|
||
|
||
```bash
|
||
npm test
|
||
```
|
||
Expected: PASS (4 Tests).
|
||
|
||
- [ ] **Step 5: Profil-Loader implementieren**
|
||
|
||
Create `web/lib/auth/profile.ts`:
|
||
|
||
```typescript
|
||
import { cache } from "react";
|
||
import { createClient } from "@/lib/supabase/server";
|
||
import type { Role } from "./roles";
|
||
|
||
export type Profile = {
|
||
id: string;
|
||
name: string;
|
||
role: Role;
|
||
};
|
||
|
||
export type ProfileResult =
|
||
| { status: "unauthenticated" }
|
||
| { status: "missing-profile" }
|
||
| { status: "ok"; profile: Profile };
|
||
|
||
export const loadProfile = cache(async (): Promise<ProfileResult> => {
|
||
const supabase = await createClient();
|
||
const {
|
||
data: { user },
|
||
} = await supabase.auth.getUser();
|
||
|
||
if (!user) {
|
||
return { status: "unauthenticated" };
|
||
}
|
||
|
||
const { data, error } = await supabase
|
||
.from("profiles")
|
||
.select("id, name, role")
|
||
.eq("id", user.id)
|
||
.single();
|
||
|
||
if (error || !data) {
|
||
return { status: "missing-profile" };
|
||
}
|
||
|
||
return { status: "ok", profile: data as Profile };
|
||
});
|
||
```
|
||
|
||
**Warum `cache()` aus `react`:** Layout und einzelne Seiten (z. B. das Dashboard) rufen `loadProfile()` unabhängig voneinander auf. `cache()` dedupliziert diese Aufrufe innerhalb derselben Anfrage, sodass trotzdem nur eine Datenbankabfrage passiert — kein expliziter Context-Provider nötig, der Server Components ohnehin nicht erreichen könnte.
|
||
|
||
- [ ] **Step 6: Navigation-Komponente implementieren**
|
||
|
||
Create `web/components/NavLinks.tsx`:
|
||
|
||
```tsx
|
||
import Link from "next/link";
|
||
import { canManageUsers, type Role } from "@/lib/auth/roles";
|
||
|
||
export function NavLinks({ role }: { role: Role }) {
|
||
return (
|
||
<nav>
|
||
<Link href="/dashboard">Dashboard</Link>
|
||
{canManageUsers(role) && <Link href="/nutzerverwaltung">Nutzerverwaltung</Link>}
|
||
</nav>
|
||
);
|
||
}
|
||
```
|
||
|
||
**Hinweis:** `/nutzerverwaltung` existiert als Route noch nicht (eigenes Teilprojekt, siehe Spec "Out of Scope"). Der Link ist bewusst schon verdrahtet; ein Klick als Admin führt aktuell zu einer 404 — das ist für dieses Fundament erwartet.
|
||
|
||
- [ ] **Step 7: Logout-Button implementieren**
|
||
|
||
Create `web/components/LogoutButton.tsx`:
|
||
|
||
```tsx
|
||
import { logout } from "@/app/login/actions";
|
||
|
||
export function LogoutButton() {
|
||
return (
|
||
<form action={logout}>
|
||
<button type="submit">Abmelden</button>
|
||
</form>
|
||
);
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 8: Root-Layout anpassen**
|
||
|
||
Modify `web/app/layout.tsx` — ersetze den gesamten Inhalt durch:
|
||
|
||
```tsx
|
||
import "./globals.css";
|
||
import { loadProfile } from "@/lib/auth/profile";
|
||
import { NavLinks } from "@/components/NavLinks";
|
||
import { LogoutButton } from "@/components/LogoutButton";
|
||
|
||
export const metadata = {
|
||
title: "Aushilfsfahrer",
|
||
};
|
||
|
||
export default async function RootLayout({
|
||
children,
|
||
}: Readonly<{ children: React.ReactNode }>) {
|
||
const result = await loadProfile();
|
||
|
||
if (result.status === "missing-profile") {
|
||
return (
|
||
<html lang="de">
|
||
<body>
|
||
<main>
|
||
<h1>Profil nicht gefunden</h1>
|
||
<p>Für deinen Account existiert kein Profil. Bitte wende dich an einen Admin.</p>
|
||
</main>
|
||
</body>
|
||
</html>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<html lang="de">
|
||
<body>
|
||
{result.status === "ok" && (
|
||
<header>
|
||
<NavLinks role={result.profile.role} />
|
||
<span>
|
||
{result.profile.name} ({result.profile.role})
|
||
</span>
|
||
<LogoutButton />
|
||
</header>
|
||
)}
|
||
<main>{children}</main>
|
||
</body>
|
||
</html>
|
||
);
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 9: Dashboard-Seite implementieren**
|
||
|
||
Create `web/app/dashboard/page.tsx`:
|
||
|
||
```tsx
|
||
import { loadProfile } from "@/lib/auth/profile";
|
||
|
||
export default async function DashboardPage() {
|
||
const result = await loadProfile();
|
||
|
||
if (result.status !== "ok") {
|
||
return null;
|
||
}
|
||
|
||
return (
|
||
<div>
|
||
<h1>Dashboard</h1>
|
||
<p>
|
||
Eingeloggt als {result.profile.name} ({result.profile.role})
|
||
</p>
|
||
</div>
|
||
);
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 10: Root-Seite auf Dashboard umleiten**
|
||
|
||
Modify `web/app/page.tsx` — ersetze den gesamten Inhalt durch:
|
||
|
||
```tsx
|
||
import { redirect } from "next/navigation";
|
||
|
||
export default function Home() {
|
||
redirect("/dashboard");
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 11: Manuell verifizieren**
|
||
|
||
```bash
|
||
npm test
|
||
npm run build
|
||
npm run dev
|
||
```
|
||
|
||
- Als Admin einloggen → Header zeigt Name, Rolle, "Nutzerverwaltung"-Link und Dashboard-Link, Dashboard-Seite zeigt Name+Rolle
|
||
- Als Fahrer/Disponent/ReadOnly einloggen (in Studio testweise anlegen, danach die Rolle wie in Task 4/Schritt 8 im SQL Editor per `update public.profiles set role = '...' where id = '...';` setzen — die Rolle wird nie aus User Metadata übernommen) → kein "Nutzerverwaltung"-Link im Header
|
||
- "Abmelden" klicken → zurück zu `/login`, `/dashboard` danach wieder nicht erreichbar ohne erneuten Login
|
||
|
||
- [ ] **Step 12: Commit**
|
||
|
||
```bash
|
||
git add web/lib/auth/ web/components/ web/app/layout.tsx web/app/dashboard/ web/app/page.tsx
|
||
git commit -m "feat: add root layout, role-based navigation and dashboard"
|
||
```
|
||
|
||
---
|
||
|
||
### Task 9: Web-Dockerfile + Docker-Compose-Integration
|
||
|
||
**Files:**
|
||
- Create: `web/Dockerfile`
|
||
- Create: `web/.dockerignore`
|
||
- Modify: `docker-compose.yaml` (Service `web` ergänzen)
|
||
- Modify: `.env.example` (Web-spezifische Variable ergänzen, falls nötig — bereits vorhanden durch Task 4)
|
||
|
||
**Interfaces:**
|
||
- Consumes: `docker-compose.yaml` aus Task 4, `web/` aus Tasks 1–8
|
||
- Produces: kompletter Stack (Supabase + Next.js) startbar mit einem `docker compose up -d`
|
||
|
||
- [ ] **Step 1: `.dockerignore` anlegen**
|
||
|
||
Create `web/.dockerignore`:
|
||
|
||
```
|
||
node_modules
|
||
.next
|
||
.env.local
|
||
npm-debug.log
|
||
```
|
||
|
||
- [ ] **Step 2: Dockerfile schreiben**
|
||
|
||
Create `web/Dockerfile`:
|
||
|
||
```dockerfile
|
||
FROM node:22-alpine AS deps
|
||
WORKDIR /app
|
||
COPY package.json package-lock.json ./
|
||
RUN npm ci
|
||
|
||
FROM node:22-alpine AS builder
|
||
WORKDIR /app
|
||
COPY --from=deps /app/node_modules ./node_modules
|
||
COPY . .
|
||
ARG NEXT_PUBLIC_SUPABASE_URL
|
||
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||
ENV NEXT_PUBLIC_SUPABASE_URL=${NEXT_PUBLIC_SUPABASE_URL}
|
||
ENV NEXT_PUBLIC_SUPABASE_ANON_KEY=${NEXT_PUBLIC_SUPABASE_ANON_KEY}
|
||
RUN npm run build
|
||
|
||
FROM node:22-alpine AS runner
|
||
WORKDIR /app
|
||
ENV NODE_ENV=production
|
||
COPY --from=builder /app/public ./public
|
||
COPY --from=builder /app/.next/standalone ./
|
||
COPY --from=builder /app/.next/static ./.next/static
|
||
EXPOSE 3000
|
||
CMD ["node", "server.js"]
|
||
```
|
||
|
||
**Warum `NEXT_PUBLIC_*` als Build-Args statt nur Laufzeit-Env:** Next.js bäckt `NEXT_PUBLIC_*`-Variablen zur Build-Zeit in den Browser-Bundle ein. Werden sie erst beim Container-Start gesetzt (wie bei serverseitigen Secrets üblich), landet im Bundle ein leerer Wert. Deshalb müssen sie schon beim `docker build` als Build-Argumente durchgereicht werden.
|
||
|
||
- [ ] **Step 3: Docker Compose um den `web`-Service ergänzen**
|
||
|
||
Modify `docker-compose.yaml` — füge am Ende des `services:`-Blocks hinzu:
|
||
|
||
```yaml
|
||
web:
|
||
build:
|
||
context: ./web
|
||
args:
|
||
NEXT_PUBLIC_SUPABASE_URL: ${NEXT_PUBLIC_SUPABASE_URL}
|
||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${NEXT_PUBLIC_SUPABASE_ANON_KEY}
|
||
restart: unless-stopped
|
||
ports:
|
||
- "3000:3000"
|
||
depends_on:
|
||
- kong
|
||
environment:
|
||
NEXT_PUBLIC_SUPABASE_URL: ${NEXT_PUBLIC_SUPABASE_URL}
|
||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${NEXT_PUBLIC_SUPABASE_ANON_KEY}
|
||
```
|
||
|
||
- [ ] **Step 4: Kompletten Stack bauen und starten**
|
||
|
||
Stelle sicher, dass in `.env` auch `NEXT_PUBLIC_SUPABASE_ANON_KEY` gesetzt ist (Task 4, Step 6 — gleicher Wert wie `ANON_KEY`).
|
||
|
||
```bash
|
||
docker compose build web
|
||
docker compose up -d
|
||
docker compose ps
|
||
```
|
||
|
||
Expected: Alle Services laufen, `web` ebenfalls.
|
||
|
||
- [ ] **Step 5: End-to-End verifizieren**
|
||
|
||
Öffne `http://localhost:3000` im Browser:
|
||
- Redirect zu `/login`
|
||
- Login mit dem Admin-Account (Task 4, Step 8) → Redirect zu `/dashboard`, Header zeigt Name/Rolle/Nutzerverwaltung-Link
|
||
- "Abmelden" → zurück zu `/login`
|
||
|
||
- [ ] **Step 6: Commit**
|
||
|
||
```bash
|
||
git add web/Dockerfile web/.dockerignore docker-compose.yaml
|
||
git commit -m "feat: containerize the Next.js app and wire it into docker-compose"
|
||
```
|
||
|
||
---
|
||
|
||
## Self-Review (durchgeführt)
|
||
|
||
- **Spec-Abdeckung:** Next.js+TypeScript (Task 1), self-hosted Supabase/Docker (Task 4/9), `profiles`+Rollen-Enum+Trigger (Task 2), RLS+`public.user_role()` (Task 3), kein Self-Signup (`DISABLE_SIGNUP=true`, Task 4), Login/Middleware/Redirect (Task 6/7), Profil im Root-Layout + Dashboard (Task 8), rollenbasierte Nutzerverwaltungs-Sichtbarkeit (Task 8), Logout (Task 8), Fehlerseite bei fehlendem Profil (Task 8), Vitest (Tasks 1/5/6/8), pgTAP (Task 3) — alle Spec-Abschnitte sind abgedeckt.
|
||
- **Platzhalter-Scan:** Keine TBD/TODO-Stellen, jeder Code-Block ist vollständig.
|
||
- **Typ-Konsistenz:** `Role` (Task 8) wird identisch in `roles.ts`, `profile.ts`, `NavLinks.tsx` verwendet; `ProfileResult`-Status-Strings (`unauthenticated`/`missing-profile`/`ok`) sind in `profile.ts`, `layout.tsx`, `dashboard/page.tsx` konsistent.
|
||
- **Scope:** Fokussiert auf das Fundament-Teilprojekt; Aufträge/Kanban/Routen/Zeiterfassung bleiben eigene Pläne.
|