feat: ST-401-ST-410 M4 REST API, tokenbeleer en activiteitenlog

- api-auth.ts was al aanwezig; demo-check toegevoegd per endpoint (ST-401)
- Token aanmaken (SHA-256 hash, eenmalig tonen), intrekken, max 10 (ST-402)
- GET /api/products actieve productenlijst (ST-403)
- GET /api/products/:id/next-story hoogst geprioriteerde open story (ST-404)
- GET /api/sprints/:id/tasks met limit parameter (ST-405)
- PATCH /api/stories/:id/tasks/reorder met ID-validatie (ST-406)
- POST /api/stories/:id/log met discriminatedUnion per type (ST-407)
- PATCH /api/tasks/:id status bijwerken met cross-user bescherming (ST-408)
- POST /api/todos via API aanmaken (ST-409)
- StoryLog component met kleurcodering per type in story slide-over (ST-410)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Janpeter Visser 2026-04-24 11:56:29 +02:00
parent d92e548f88
commit b71a1a7328
14 changed files with 713 additions and 1 deletions

60
actions/api-tokens.ts Normal file
View file

@ -0,0 +1,60 @@
'use server'
import { revalidatePath } from 'next/cache'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { createHash, randomBytes } from 'crypto'
import { prisma } from '@/lib/prisma'
import { SessionData, sessionOptions } from '@/lib/session'
async function getSession() {
return getIronSession<SessionData>(await cookies(), sessionOptions)
}
export async function createApiTokenAction(_prevState: unknown, formData: FormData) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const label = (formData.get('label') as string | null)?.trim() || null
// Max 10 active tokens
const activeCount = await prisma.apiToken.count({
where: { user_id: session.userId, revoked_at: null },
})
if (activeCount >= 10) return { error: 'Maximaal 10 actieve tokens toegestaan' }
const rawToken = randomBytes(32).toString('hex')
const tokenHash = createHash('sha256').update(rawToken).digest('hex')
await prisma.apiToken.create({
data: {
user_id: session.userId,
token_hash: tokenHash,
label,
},
})
revalidatePath('/settings/tokens')
// Return the raw token once — it won't be retrievable later
return { success: true, token: rawToken }
}
export async function revokeApiTokenAction(id: string) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const token = await prisma.apiToken.findFirst({
where: { id, user_id: session.userId },
})
if (!token) return { error: 'Token niet gevonden' }
await prisma.apiToken.update({
where: { id },
data: { revoked_at: new Date() },
})
revalidatePath('/settings/tokens')
return { success: true }
}

View file

@ -163,6 +163,36 @@ export async function updatePbiPriorityAction(pbiId: string, priority: number, p
return { success: true }
}
export async function getStoryLogsAction(storyId: string) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
const story = await prisma.story.findFirst({
where: { id: storyId, product: { user_id: session.userId } },
include: { product: { select: { repo_url: true } } },
})
if (!story) return { error: 'Story niet gevonden' }
const logs = await prisma.storyLog.findMany({
where: { story_id: storyId },
orderBy: { created_at: 'asc' },
})
return {
success: true,
logs: logs.map(l => ({
id: l.id,
type: l.type,
content: l.content,
status: l.status,
commit_hash: l.commit_hash,
commit_message: l.commit_message,
created_at: l.created_at.toISOString(),
})),
repoUrl: story.product.repo_url,
}
}
export async function reorderStoriesAction(
pbiId: string,
productId: string,

View file

@ -0,0 +1,34 @@
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { SessionData, sessionOptions } from '@/lib/session'
import Link from 'next/link'
export default async function SettingsPage() {
const session = await getIronSession<SessionData>(await cookies(), sessionOptions)
return (
<div className="p-6 max-w-2xl mx-auto w-full space-y-6">
<h1 className="text-xl font-medium text-foreground">Instellingen</h1>
<div className="bg-surface-container-low border border-border rounded-xl p-5 space-y-3">
<h2 className="text-sm font-medium text-foreground">Account</h2>
<p className="text-sm text-muted-foreground">
Ingelogd als <span className="text-foreground font-medium">{session.userId}</span>
{session.isDemo && <span className="ml-2 text-warning text-xs">(demo)</span>}
</p>
</div>
<div className="bg-surface-container-low border border-border rounded-xl p-5 space-y-3">
<div className="flex items-center justify-between">
<h2 className="text-sm font-medium text-foreground">API Tokens</h2>
<Link href="/settings/tokens" className="text-xs text-primary hover:underline">
Beheren
</Link>
</div>
<p className="text-sm text-muted-foreground">
Gebruik API tokens om Scrum4Me te koppelen aan Claude Code.
</p>
</div>
</div>
)
}

View file

@ -0,0 +1,37 @@
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { SessionData, sessionOptions } from '@/lib/session'
import { prisma } from '@/lib/prisma'
import { TokenManager } from '@/components/settings/token-manager'
import Link from 'next/link'
export default async function TokensPage() {
const session = await getIronSession<SessionData>(await cookies(), sessionOptions)
const tokens = await prisma.apiToken.findMany({
where: { user_id: session.userId },
orderBy: { created_at: 'desc' },
})
return (
<div className="p-6 max-w-2xl mx-auto w-full">
<div className="flex items-center gap-3 mb-6">
<Link href="/settings" className="text-muted-foreground hover:text-foreground text-sm">
Instellingen
</Link>
<span className="text-muted-foreground">/</span>
<h1 className="text-xl font-medium text-foreground">API Tokens</h1>
</div>
<TokenManager
tokens={tokens.map(t => ({
id: t.id,
label: t.label,
created_at: t.created_at.toISOString(),
revoked_at: t.revoked_at?.toISOString() ?? null,
}))}
isDemo={session.isDemo ?? false}
/>
</div>
)
}

View file

@ -0,0 +1,44 @@
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
const { id } = await params
const sprint = await prisma.sprint.findFirst({
where: { product_id: id, status: 'ACTIVE', product: { user_id: auth.userId } },
})
if (!sprint) {
return Response.json({ error: 'Geen actieve Sprint gevonden' }, { status: 404 })
}
const story = await prisma.story.findFirst({
where: { sprint_id: sprint.id, status: 'IN_SPRINT' },
orderBy: [{ priority: 'asc' }, { sort_order: 'asc' }],
include: {
tasks: {
orderBy: [{ priority: 'asc' }, { sort_order: 'asc' }],
select: { id: true, title: true, description: true, priority: true, sort_order: true, status: true },
},
},
})
if (!story) {
return Response.json({ error: 'Geen open stories in de Sprint' }, { status: 404 })
}
return Response.json({
id: story.id,
title: story.title,
description: story.description,
acceptance_criteria: story.acceptance_criteria,
tasks: story.tasks,
})
}

17
app/api/products/route.ts Normal file
View file

@ -0,0 +1,17 @@
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
export async function GET(request: Request) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
const products = await prisma.product.findMany({
where: { user_id: auth.userId, archived: false },
orderBy: { created_at: 'desc' },
select: { id: true, name: true, repo_url: true },
})
return Response.json(products)
}

View file

@ -0,0 +1,37 @@
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
const { id } = await params
const url = new URL(request.url)
const limitParam = parseInt(url.searchParams.get('limit') ?? '10')
const limit = Math.min(Math.max(1, limitParam), 50)
const sprint = await prisma.sprint.findFirst({
where: { id, product: { user_id: auth.userId } },
})
if (!sprint) {
return Response.json({ error: 'Sprint niet gevonden' }, { status: 404 })
}
const tasks = await prisma.task.findMany({
where: { sprint_id: id },
orderBy: [
{ story: { sort_order: 'asc' } },
{ priority: 'asc' },
{ sort_order: 'asc' },
],
take: limit,
select: { id: true, title: true, story_id: true, priority: true, sort_order: true, status: true },
})
return Response.json(tasks)
}

View file

@ -0,0 +1,59 @@
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { z } from 'zod'
const logSchema = z.discriminatedUnion('type', [
z.object({
type: z.literal('IMPLEMENTATION_PLAN'),
content: z.string().min(1),
}),
z.object({
type: z.literal('TEST_RESULT'),
content: z.string().min(1),
status: z.enum(['PASSED', 'FAILED']),
}),
z.object({
type: z.literal('COMMIT'),
content: z.string().min(1),
commit_hash: z.string().min(1),
commit_message: z.string().min(1),
}),
])
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
const { id: storyId } = await params
const story = await prisma.story.findFirst({
where: { id: storyId, product: { user_id: auth.userId } },
})
if (!story) {
return Response.json({ error: 'Story niet gevonden' }, { status: 404 })
}
const body = await request.json().catch(() => null)
const parsed = logSchema.safeParse(body)
if (!parsed.success) {
return Response.json({ error: parsed.error.flatten() }, { status: 400 })
}
const log = await prisma.storyLog.create({
data: {
story_id: storyId,
type: parsed.data.type,
content: parsed.data.content,
status: 'status' in parsed.data ? parsed.data.status : null,
commit_hash: 'commit_hash' in parsed.data ? parsed.data.commit_hash : null,
commit_message: 'commit_message' in parsed.data ? parsed.data.commit_message : null,
},
})
return Response.json({ id: log.id, created_at: log.created_at }, { status: 201 })
}

View file

@ -0,0 +1,50 @@
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { z } from 'zod'
const bodySchema = z.object({
task_ids: z.array(z.string()).min(1),
})
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
if (auth.isDemo) {
return Response.json({ error: 'Niet beschikbaar in demo-modus' }, { status: 403 })
}
const { id: storyId } = await params
const body = await request.json().catch(() => null)
const parsed = bodySchema.safeParse(body)
if (!parsed.success) {
return Response.json({ error: parsed.error.flatten() }, { status: 400 })
}
const story = await prisma.story.findFirst({
where: { id: storyId, product: { user_id: auth.userId } },
include: { tasks: { select: { id: true } } },
})
if (!story) {
return Response.json({ error: 'Story niet gevonden' }, { status: 404 })
}
const storyTaskIds = new Set(story.tasks.map(t => t.id))
const invalidId = parsed.data.task_ids.find(id => !storyTaskIds.has(id))
if (invalidId) {
return Response.json({ error: `Ongeldig task_id: ${invalidId}` }, { status: 400 })
}
await prisma.$transaction(
parsed.data.task_ids.map((id, i) =>
prisma.task.update({ where: { id }, data: { sort_order: i + 1.0 } })
)
)
return Response.json({ success: true })
}

View file

@ -0,0 +1,46 @@
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { z } from 'zod'
const patchSchema = z.object({
status: z.enum(['TO_DO', 'IN_PROGRESS', 'DONE']),
})
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
if (auth.isDemo) {
return Response.json({ error: 'Niet beschikbaar in demo-modus' }, { status: 403 })
}
const { id } = await params
const task = await prisma.task.findFirst({
where: { id },
include: { story: { include: { product: true } } },
})
if (!task) {
return Response.json({ error: 'Taak niet gevonden' }, { status: 404 })
}
if (task.story.product.user_id !== auth.userId) {
return Response.json({ error: 'Geen toegang' }, { status: 403 })
}
const body = await request.json().catch(() => null)
const parsed = patchSchema.safeParse(body)
if (!parsed.success) {
return Response.json({ error: parsed.error.flatten() }, { status: 400 })
}
const updated = await prisma.task.update({
where: { id },
data: { status: parsed.data.status },
})
return Response.json({ id: updated.id, status: updated.status })
}

29
app/api/todos/route.ts Normal file
View file

@ -0,0 +1,29 @@
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { z } from 'zod'
const bodySchema = z.object({
title: z.string().min(1, 'Titel is verplicht').max(500),
})
export async function POST(request: Request) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
const body = await request.json().catch(() => null)
const parsed = bodySchema.safeParse(body)
if (!parsed.success) {
return Response.json({ error: parsed.error.flatten() }, { status: 400 })
}
const todo = await prisma.todo.create({
data: {
user_id: auth.userId,
title: parsed.data.title,
},
})
return Response.json({ id: todo.id, title: todo.title, created_at: todo.created_at }, { status: 201 })
}

View file

@ -29,7 +29,8 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sh
import { PanelNavBar } from '@/components/shared/panel-nav-bar'
import { useSelectionStore } from '@/stores/selection-store'
import { usePlannerStore } from '@/stores/planner-store'
import { createStoryAction, updateStoryAction, deleteStoryAction, reorderStoriesAction } from '@/actions/stories'
import { createStoryAction, updateStoryAction, deleteStoryAction, reorderStoriesAction, getStoryLogsAction } from '@/actions/stories'
import { StoryLog } from '@/components/shared/story-log'
import { cn } from '@/lib/utils'
const PRIORITY_LABELS: Record<number, string> = { 1: 'Kritiek', 2: 'Hoog', 3: 'Gemiddeld', 4: 'Laag' }
@ -125,6 +126,11 @@ function StoryDetailSheet({
}) {
const [confirmDelete, setConfirmDelete] = useState(false)
const [isDeleting, startDeleteTransition] = useTransition()
const [logs, setLogs] = useState<Awaited<ReturnType<typeof getStoryLogsAction>> | null>(null)
useEffect(() => {
getStoryLogsAction(story.id).then(setLogs)
}, [story.id])
const [state, formAction] = useActionState(
async (_prev: unknown, fd: FormData) => {
@ -212,6 +218,16 @@ function StoryDetailSheet({
)}
</div>
{/* Activity log */}
<div className="px-5 py-4 border-t border-border">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-3">Activiteitenlog</p>
{logs && 'logs' in logs && logs.logs ? (
<StoryLog logs={logs.logs.map(l => ({ ...l, status: l.status ?? null, commit_hash: l.commit_hash ?? null, commit_message: l.commit_message ?? null }))} repoUrl={logs.repoUrl} />
) : (
<p className="text-xs text-muted-foreground">Laden</p>
)}
</div>
{!isDemo && (
<div className="border-t border-border p-4">
{confirmDelete ? (

View file

@ -0,0 +1,150 @@
'use client'
import { useState, useActionState, useTransition } from 'react'
import { useFormStatus } from 'react-dom'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { createApiTokenAction, revokeApiTokenAction } from '@/actions/api-tokens'
interface Token {
id: string
label: string | null
created_at: string
revoked_at: string | null
}
interface TokenManagerProps {
tokens: Token[]
isDemo: boolean
}
function CreateSubmitButton() {
const { pending } = useFormStatus()
return (
<Button type="submit" disabled={pending}>
{pending ? 'Aanmaken…' : 'Token aanmaken'}
</Button>
)
}
export function TokenManager({ tokens, isDemo }: TokenManagerProps) {
const [newToken, setNewToken] = useState<string | null>(null)
const [copied, setCopied] = useState(false)
const [, startRevoke] = useTransition()
const [state, formAction] = useActionState(
async (_prev: unknown, fd: FormData) => {
const result = await createApiTokenAction(_prev, fd)
if (result.success && result.token) {
setNewToken(result.token)
}
return result
},
undefined
)
function handleCopy() {
if (!newToken) return
navigator.clipboard.writeText(newToken)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
function handleRevoke(id: string) {
startRevoke(async () => {
await revokeApiTokenAction(id)
})
}
const activeTokens = tokens.filter(t => !t.revoked_at)
const revokedTokens = tokens.filter(t => t.revoked_at)
return (
<div className="space-y-6">
{/* New token revealed */}
{newToken && (
<div className="bg-success-container border border-success/30 rounded-xl p-4 space-y-3">
<p className="text-sm font-medium text-success-container-foreground">
Token aangemaakt kopieer het nu. Je ziet het daarna niet meer.
</p>
<div className="flex gap-2">
<code className="flex-1 bg-surface-container px-3 py-2 rounded-lg text-xs font-mono break-all">
{newToken}
</code>
<Button size="sm" variant="outline" onClick={handleCopy}>
{copied ? 'Gekopieerd!' : 'Kopieer'}
</Button>
</div>
<Button size="sm" variant="ghost" onClick={() => setNewToken(null)}>Sluiten</Button>
</div>
)}
{/* Create form */}
{!isDemo && (
<div className="bg-surface-container-low border border-border rounded-xl p-5 space-y-4">
<h2 className="text-sm font-medium text-foreground">Nieuw token aanmaken</h2>
<form action={formAction} className="flex gap-2">
<Input name="label" placeholder="Label (optioneel)" className="flex-1" />
<CreateSubmitButton />
</form>
{typeof state?.error === 'string' && (
<p className="text-xs text-error">{state.error}</p>
)}
<p className="text-xs text-muted-foreground">
Maximaal 10 actieve tokens. Je hebt er nu {activeTokens.length}.
</p>
</div>
)}
{/* Active tokens */}
<div className="space-y-2">
<h2 className="text-sm font-medium text-foreground">Actieve tokens ({activeTokens.length})</h2>
{activeTokens.length === 0 ? (
<p className="text-sm text-muted-foreground">Geen actieve tokens.</p>
) : (
<div className="bg-surface-container-low border border-border rounded-xl divide-y divide-border">
{activeTokens.map(token => (
<div key={token.id} className="flex items-center justify-between px-4 py-3 gap-3">
<div>
<p className="text-sm font-medium">{token.label ?? <span className="text-muted-foreground italic">Geen label</span>}</p>
<p className="text-xs text-muted-foreground">
Aangemaakt {new Date(token.created_at).toLocaleDateString('nl-NL')}
</p>
</div>
{!isDemo && (
<Button
size="sm"
variant="ghost"
className="text-error hover:bg-error/10 shrink-0"
onClick={() => handleRevoke(token.id)}
>
Intrekken
</Button>
)}
</div>
))}
</div>
)}
</div>
{/* Revoked tokens */}
{revokedTokens.length > 0 && (
<div className="space-y-2">
<h2 className="text-sm font-medium text-muted-foreground">Ingetrokken tokens</h2>
<div className="bg-surface-container-low border border-border rounded-xl divide-y divide-border opacity-60">
{revokedTokens.map(token => (
<div key={token.id} className="flex items-center justify-between px-4 py-3 gap-3">
<div>
<p className="text-sm line-through">{token.label ?? 'Geen label'}</p>
<p className="text-xs text-muted-foreground">
Ingetrokken {new Date(token.revoked_at!).toLocaleDateString('nl-NL')}
</p>
</div>
</div>
))}
</div>
</div>
)}
</div>
)
}

View file

@ -0,0 +1,103 @@
interface StoryLogEntry {
id: string
type: string
content: string
status: string | null
commit_hash: string | null
commit_message: string | null
created_at: string
}
interface StoryLogProps {
logs: StoryLogEntry[]
repoUrl?: string | null
}
const TYPE_STYLES: Record<string, { bg: string; label: string; labelColor: string }> = {
IMPLEMENTATION_PLAN: {
bg: 'bg-info-container/50 border-info/20',
label: 'Implementatieplan',
labelColor: 'text-info',
},
TEST_RESULT: {
bg: 'bg-surface-container border-border',
label: 'Testresultaat',
labelColor: 'text-foreground',
},
COMMIT: {
bg: 'bg-secondary-container/30 border-secondary/20',
label: 'Commit',
labelColor: 'text-secondary',
},
}
export function StoryLog({ logs, repoUrl }: StoryLogProps) {
if (logs.length === 0) {
return (
<p className="text-sm text-muted-foreground text-center py-4">
Nog geen activiteit. Gebruik de REST API om logs toe te voegen.
</p>
)
}
return (
<div className="space-y-3">
{logs.map(log => {
const style = TYPE_STYLES[log.type] ?? TYPE_STYLES.IMPLEMENTATION_PLAN
const isTestResult = log.type === 'TEST_RESULT'
const testPassed = log.status === 'PASSED'
return (
<div
key={log.id}
className={`rounded-lg border p-3 space-y-1.5 ${
isTestResult
? testPassed
? 'bg-success-container/40 border-success/20'
: 'bg-error-container/40 border-error/20'
: style.bg
}`}
>
<div className="flex items-center justify-between">
<span className={`text-xs font-semibold ${
isTestResult ? (testPassed ? 'text-success' : 'text-error') : style.labelColor
}`}>
{style.label}
{isTestResult && `${testPassed ? 'Geslaagd' : 'Mislukt'}`}
</span>
<span className="text-xs text-muted-foreground">
{new Date(log.created_at).toLocaleDateString('nl-NL', {
day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit',
})}
</span>
</div>
<p className="text-sm text-foreground whitespace-pre-line">{log.content}</p>
{log.commit_hash && (
<div className="flex items-center gap-2 mt-1">
{repoUrl ? (
<a
href={`${repoUrl}/commit/${log.commit_hash}`}
target="_blank"
rel="noopener noreferrer"
className="text-xs font-mono text-secondary hover:underline"
>
{log.commit_hash.slice(0, 7)}
</a>
) : (
<code className="text-xs font-mono text-secondary">
{log.commit_hash.slice(0, 7)}
</code>
)}
{log.commit_message && (
<span className="text-xs text-muted-foreground truncate">{log.commit_message}</span>
)}
</div>
)}
</div>
)
})}
</div>
)
}