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:
Tiel Coder
2026-11-17 19:34:06 +00:00
parent a68e1c6277
commit 3cd932e1a1
16 changed files with 779 additions and 1 deletions
+28
View File
@@ -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,
});
};
+43
View File
@@ -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 },
);
}
};