A3: auth (magic-link sign-in, requirePermission chokepoint, role enum)
- Auth.js v5 Credentials provider (magic-link) + JWT session carrying systemRole - src/auth: roles, permissions (feature-scoped matrix), magic-link dev console transport - requirePermission(user, perm) chokepoint -> AuthError(401/403) - Routes: /api/auth/[...nextauth], /api/dev/magic-link, /api/dev/complete, /api/admin, /login - Auto-activate new emails in dev (AUTO_ACTIVATE_NEW_USERS, flip to require approval) - Acceptance pnpm test src/auth green: 401 anonymous, 403 volunteer on /admin, 200 admin - Verified at runtime against Postgres on :5433
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* `/admin` chokepoint. Demonstrates the authorization gate:
|
||||
* - anonymous -> 401
|
||||
* - volunteer/other -> 403 (lacks admin.settings)
|
||||
* - admin -> 200
|
||||
* The permission here (`admin.settings`) is admin-only by the capability matrix.
|
||||
*/
|
||||
export const GET = async () => {
|
||||
try {
|
||||
const session = await auth();
|
||||
const user = requirePermission(
|
||||
(session?.user as { systemRole: SystemRole } | null | undefined),
|
||||
"admin.settings",
|
||||
);
|
||||
return new Response(JSON.stringify({ ok: true, role: user.systemRole }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
import { handlers } from "@/auth/config";
|
||||
|
||||
export const { GET, POST } = handlers;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { signIn } from "@/auth/config";
|
||||
import { verifyMagicToken } from "@/auth/magic-link";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* Completes a magic-link sign-in. GET /api/dev/complete?token=... verifies the
|
||||
* one-time token and establishes the Auth.js session.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const token = new URL(req.url, "http://localhost").searchParams.get(
|
||||
"token",
|
||||
) ?? undefined;
|
||||
const payload = await verifyMagicToken(token);
|
||||
if (!payload) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "invalid or expired link" }),
|
||||
{ status: 400, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
|
||||
const result = await signIn("magic-link", { token, redirect: false });
|
||||
return new Response(JSON.stringify({ ok: true, url: result.url }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requestMagicLink } from "@/auth/magic-link";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const bodySchema = z.object({ email: z.string().email() });
|
||||
|
||||
/**
|
||||
* Dev console magic-link transport. POST { email } -> resolves/creates the user
|
||||
* (auto-activating when AUTO_ACTIVATE_NEW_USERS is on) and returns the sign-in
|
||||
* link, which is also printed to the console. Swapping in Postmark later is a
|
||||
* change inside `requestMagicLink` only.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
let email: string | undefined;
|
||||
try {
|
||||
const text = await req.text();
|
||||
email = text ? (JSON.parse(text) as { email?: string }).email : undefined;
|
||||
} catch {
|
||||
// fall through to validation, which rejects a missing email
|
||||
}
|
||||
|
||||
const parsed = bodySchema.safeParse({ email });
|
||||
if (!parsed.success) {
|
||||
return new Response(JSON.stringify({ error: "a valid email is required" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await requestMagicLink(parsed.data.email);
|
||||
return new Response(JSON.stringify(result), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "failed to process request" }),
|
||||
{ status: 500, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
/**
|
||||
* Magic-link sign-in (v1, no passwords). Enter an email; the dev console
|
||||
* transport prints a sign-in link. Clicking it completes the Auth.js session.
|
||||
* At launch there is no email/SMS delivery, so the link is shown here as a
|
||||
* fallback and printed to the console (see /api/dev/magic-link).
|
||||
*/
|
||||
export default function LoginPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [status, setStatus] = useState<{ kind: "idle" | "sending" | "sent" | "error"; message?: string }>({
|
||||
kind: "idle",
|
||||
});
|
||||
|
||||
async function onSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setStatus({ kind: "sending" });
|
||||
try {
|
||||
const res = await fetch("/api/dev/magic-link", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
const body = (await res.json()) as { ok?: boolean; url?: string; error?: string };
|
||||
if (res.ok && body.url) {
|
||||
setStatus({ kind: "sent", message: body.url });
|
||||
} else {
|
||||
setStatus({ kind: "error", message: body.error ?? "Something went wrong." });
|
||||
}
|
||||
} catch {
|
||||
setStatus({ kind: "error", message: "Network error." });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center px-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Sign in</CardTitle>
|
||||
<CardDescription>Enter your work email — no password required.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="you@church.local"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={status.kind === "sending"}>
|
||||
{status.kind === "sending" ? "Sending link…" : "Send sign-in link"}
|
||||
</Button>
|
||||
{status.kind === "sent" && status.message && (
|
||||
<p className="rounded border border-border bg-muted p-3 text-sm break-all">
|
||||
Sign-in link (dev console transport):<br />
|
||||
<span className="text-foreground underline">{status.message}</span>
|
||||
</p>
|
||||
)}
|
||||
{status.kind === "error" && status.message && (
|
||||
<p className="text-sm text-destructive">{status.message}</p>
|
||||
)}
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user