--- phase: 01-foundation plan: "02" subsystem: auth tags: [next-auth, jwt, credentials, bcryptjs, middleware, session, seed] requires: - phase: 01-foundation/01-01 provides: "Next.js 15 App Router scaffold, Prisma schema with Tenant and User models, singleton PrismaClient" provides: - "NextAuth.js v4 credentials provider with JWT sessions carrying tenantId and roles" - "Extended NextAuth types (Session, JWT) with tenantId, roles, isSuperAdmin, firstName, lastName" - "Route protection middleware (src/middleware.ts) redirecting unauthenticated users to /login" - "Login page UI at /login with email/password form, error/loading states" - "Logout via Header component Sign out button (signOut with callbackUrl /login)" - "Server-side auth helpers: getServerSession() and getCurrentUser() in src/lib/auth.ts" - "Seed data: Demo ISP tenant + admin@demo.com (ADMIN) + superadmin@netforge.com (super-admin)" - "8 unit tests for authOptions JWT/session callbacks" affects: - "01-03 (tenant provisioning): reads tenantId from JWT token for tenant context" - "All future plans: getCurrentUser() is the primary auth helper for Server Components" - "Phase 2 (billing/RBAC): roles array in JWT enables RBAC checks" - "Phase 3 (collectors): tenantId in JWT scopes all queries to correct tenant" tech-stack: added: [next-auth@4, bcryptjs@3, @types/bcryptjs, @types/jest, tsx] patterns: - "JWT strategy with 24-hour maxAge — no server-side session storage needed" - "tenantId + roles in JWT token for stateless RBAC and multi-tenancy" - "withAuth middleware from next-auth/middleware for route protection" - "SessionProvider at root layout level (src/components/providers.tsx) for useSession access" - "Seed script uses findFirst+create pattern for null tenantId super-admins (PostgreSQL unique constraint behavior with nulls)" key-files: created: - src/types/next-auth.d.ts - src/lib/auth-options.ts - src/lib/auth.ts - src/app/api/auth/[...nextauth]/route.ts - src/middleware.ts - src/app/(auth)/layout.tsx - src/app/(auth)/login/page.tsx - src/app/(dashboard)/layout.tsx - src/app/(dashboard)/dashboard/page.tsx - src/components/layout/header.tsx - src/components/providers.tsx - prisma/seed.ts - src/lib/__tests__/auth.test.ts modified: - package.json - src/app/layout.tsx key-decisions: - "Used NextAuth.js v4 (not v5/Auth.js beta) for credentials provider stability" - "JWT carries tenantId and roles directly — no database lookup on each request" - "Super-admin user has tenantId=null; authorize() checks isSuperAdmin OR active tenant status" - "Seed uses findFirst+create instead of upsert for super-admin: PostgreSQL treats NULL != NULL in unique constraints, so upsert on [email, tenantId] with null tenantId creates duplicates" - "Added @types/jest to fix TypeScript type errors for Vitest globals (describe/it/expect)" patterns-established: - "Auth pattern: getCurrentUser() in Server Components, useSession() in Client Components" - "Protected route pattern: middleware handles redirect to /login; individual pages can also call getCurrentUser() for extra safety" - "Dashboard layout pattern: (dashboard) route group has Header + main layout; (auth) group has centered card layout" duration: 8min completed: 2026-03-04 --- # Phase 1 Plan 02: Authentication Summary **NextAuth.js v4 credentials auth with JWT carrying tenantId+roles, /login page, route protection middleware, and idempotent seed data for demo tenant + admin + super-admin users** ## Performance - **Duration:** 8 min - **Started:** 2026-03-04T10:34:59Z - **Completed:** 2026-03-04T10:42:58Z - **Tasks:** 2 completed - **Files modified:** 15 ## Accomplishments - NextAuth.js v4 configured with CredentialsProvider — email/password auth with bcrypt verification, JWT sessions that embed tenantId and roles for stateless multi-tenancy - Route protection middleware (withAuth) blocks all non-public routes and redirects unauthenticated users to /login; TypeScript types extended for full session typing - Login page UI at /login with form validation, error display, loading state, and post-login redirect to /dashboard; Header component with Sign out button in authenticated layout - Seed script creates Demo ISP tenant + admin@demo.com (ADMIN role) + superadmin@netforge.com (isSuperAdmin, no tenant) using upsert/idempotent pattern - 8 unit tests for authOptions configuration and JWT/session callback behavior — all passing ## Task Commits 1. **Task 1: NextAuth.js configuration with credentials provider and JWT** - `71a9277` (feat) 2. **Task 2: Login page UI, logout flow, seed script, and auth unit tests** - `3c37cb1` (feat) **Plan metadata:** (to be added in final commit) ## Files Created/Modified - `src/types/next-auth.d.ts` - Extended NextAuth Session and JWT types with tenantId, roles, isSuperAdmin, firstName, lastName - `src/lib/auth-options.ts` - NextAuthOptions: CredentialsProvider, JWT callback, session callback, 24h maxAge - `src/lib/auth.ts` - Server helpers: getServerSession() and getCurrentUser() - `src/app/api/auth/[...nextauth]/route.ts` - NextAuth GET/POST route handler - `src/middleware.ts` - withAuth middleware protecting all routes except /login /signup /api/auth/* /_next/* - `src/app/(auth)/layout.tsx` - Centered auth card layout - `src/app/(auth)/login/page.tsx` - Login form with email/password, error, loading state, sign up link - `src/app/(dashboard)/layout.tsx` - Dashboard layout with Header component - `src/app/(dashboard)/dashboard/page.tsx` - Basic dashboard page (post-login landing) - `src/components/layout/header.tsx` - Authenticated header with user name + Sign out button - `src/components/providers.tsx` - SessionProvider wrapper for client-side useSession() - `prisma/seed.ts` - Idempotent seed: Demo ISP tenant, admin user, super-admin user - `src/lib/__tests__/auth.test.ts` - 8 unit tests for authOptions - `package.json` - Added db:seed script, prisma.seed config, tsx devDependency - `src/app/layout.tsx` - Wrapped children with Providers (SessionProvider) ## Decisions Made - **NextAuth v4 over v5:** v5/Auth.js credentials provider support is still evolving; v4 is the stable production choice for custom JWT + credentials auth - **JWT carries tenantId + roles:** No database lookup on each request — token is self-contained. 24h maxAge balances security and UX - **Super-admin authorize logic:** Uses `OR [{ isSuperAdmin: true }, { tenant: { status: ACTIVE } }]` in Prisma query — one query handles both cases - **Seed uses findFirst+create for super-admin:** PostgreSQL unique constraint on `(email, tenantId)` with `tenantId=null` means `NULL != NULL` — upsert where clause would create duplicate rows; findFirst+create is explicit and safe - **@types/jest installed:** Vitest globals (`describe`, `it`, `expect`) with `globals: true` config are compatible with @types/jest type definitions, fixing TypeScript errors without needing separate vitest type package ## Deviations from Plan ### Auto-fixed Issues **1. [Rule 3 - Blocking] Added @types/jest for Vitest globals TypeScript support** - **Found during:** Task 1 (TypeScript check after creating auth files) - **Issue:** `npx tsc --noEmit` reported errors in setup.test.ts — `describe`, `it`, `expect` unknown without type definitions. Vitest's `globals: true` config works at runtime but TypeScript needs explicit types - **Fix:** `npm install -D @types/jest` — compatible with Vitest's global API - **Files modified:** package.json, package-lock.json - **Verification:** `npx tsc --noEmit` passes with no errors in auth files - **Committed in:** 71a9277 (Task 1 commit) **2. [Rule 2 - Missing Critical] Added SessionProvider in root layout** - **Found during:** Task 2 (creating Header component with useSession) - **Issue:** `useSession()` in Header component requires SessionProvider ancestor — not in the plan but required for the header to function - **Fix:** Created `src/components/providers.tsx` as "use client" SessionProvider wrapper; added to root `src/app/layout.tsx` - **Files modified:** src/components/providers.tsx, src/app/layout.tsx - **Verification:** TypeScript check passes; useSession available in all client components - **Committed in:** 3c37cb1 (Task 2 commit) **3. [Rule 2 - Missing Critical] Created basic /dashboard page** - **Found during:** Task 2 (login redirects to /dashboard which didn't exist) - **Issue:** Login success redirects to `/dashboard` but no page existed — would 404 or error - **Fix:** Created `src/app/(dashboard)/dashboard/page.tsx` with welcome message and user info display - **Files modified:** src/app/(dashboard)/dashboard/page.tsx - **Verification:** Route exists; getCurrentUser() used for server-side auth guard - **Committed in:** 3c37cb1 (Task 2 commit) --- **Total deviations:** 3 auto-fixed (1 blocking, 2 missing critical) **Impact on plan:** All three fixes were essential for functionality and type safety. No scope creep — the SessionProvider and dashboard page are minimal stubs supporting the auth flow. ## Issues Encountered - Test file type casting for NextAuth callback parameters required `as unknown as` double-casting due to strict overlap checking between custom User type and NextAuth's internal AdapterUser type — resolved by casting through unknown - `prisma-tenant.ts` from parallel plan 01-03 has TypeScript errors (unrelated to this plan's files) — confirmed by running `npx tsc 2>&1 | grep "^src" | grep -v prisma-tenant` which shows 0 errors in auth files ## User Setup Required None - no external service configuration required. NEXTAUTH_SECRET and NEXTAUTH_URL are already in `.env`. ## Next Phase Readiness - Auth is fully functional. getCurrentUser() available for all Server Components in Phase 2+ - Seed data ready: admin@demo.com / admin123, superadmin@netforge.com / super123 - JWT token carries tenantId and roles — plan 01-03 (tenant provisioning) and all future plans can read these from session without extra DB queries - Middleware protects all routes — future plans can add routes without worrying about auth --- *Phase: 01-foundation* *Completed: 2026-03-04*