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,58 @@
|
||||
/**
|
||||
* Auth.js (v5) configuration: the magic-link credentials provider plus a JWT
|
||||
* session that carries `systemRole` so `requirePermission()` can read it from
|
||||
* `session.user` without another DB hit.
|
||||
*
|
||||
* No database adapter is needed — JWT sessions are self-contained. The
|
||||
* credentials provider's `authorize` verifies the one-time magic-link token and
|
||||
* returns the active user.
|
||||
*/
|
||||
|
||||
import NextAuth from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import { getUser, verifyMagicToken } from "./magic-link";
|
||||
import type { SystemRole } from "./roles";
|
||||
|
||||
export const authConfig = {
|
||||
providers: [
|
||||
Credentials({
|
||||
id: "magic-link",
|
||||
name: "Magic Link",
|
||||
credentials: {
|
||||
token: { label: "Token", type: "text" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const token = credentials?.token as string | undefined;
|
||||
const payload = await verifyMagicToken(token);
|
||||
if (!payload) return null;
|
||||
const user = await getUser(payload.email);
|
||||
if (!user || user.status !== "active" || user.deactivatedAt) return null;
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.displayName ?? user.email,
|
||||
systemRole: user.systemRole,
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
session: { strategy: "jwt" },
|
||||
secret: process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET,
|
||||
pages: { signIn: "/login" },
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
(token as { systemRole?: SystemRole }).systemRole =
|
||||
(user as { systemRole?: SystemRole }).systemRole ?? "volunteer";
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
(session.user as { systemRole?: SystemRole }).systemRole =
|
||||
(token as { systemRole?: SystemRole }).systemRole ?? "volunteer";
|
||||
return session;
|
||||
},
|
||||
},
|
||||
} satisfies Parameters<typeof NextAuth>[0];
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth(authConfig);
|
||||
Reference in New Issue
Block a user