# Task 003 — Authentication

## Objective

Implement internal user authentication with NextAuth.js and protect app routes and APIs.

## Scope

- NextAuth configuration with credentials provider
- User model/session integration with MongoDB
- Login page and session provider in root layout
- Middleware for authenticated routes
- Role field on user for RBAC foundation
- Bootstrap route for initial admin

**Out of scope:** Full user admin UI, SSO, MFA, CRM modules.

## Requirements

1. Unauthenticated users redirect to login.
2. `NEXTAUTH_SECRET` and `NEXTAUTH_URL` required at startup.
3. API routes return 401 without session (except `/api/health`, `/api/auth/*`, `/api/admin/bootstrap`).
4. Session includes user id, email, name, role.

## Files to create or modify

| Path | Action |
|------|--------|
| `src/server/models/user.model.ts` | Create |
| `src/server/services/auth.service.ts` | Create |
| `src/lib/auth.ts` | Create |
| `src/app/api/auth/[...nextauth]/route.ts` | Create |
| `src/app/api/admin/bootstrap/route.ts` | Create |
| `src/middleware.ts` | Create |
| `src/app/login/**` | Create |
| `src/app/dashboard/page.tsx` | Create |
| `src/components/layout/**` | Create |
| `src/types/next-auth.d.ts` | Create |
| `src/lib/env.ts`, `.env.example` | Bootstrap env vars |
| `docs/**` | Updated |

## Acceptance criteria

- [x] Login/logout works locally
- [x] Protected page inaccessible when logged out
- [x] API returns 401 for protected routes without session
- [x] Roles stored and available in session
- [x] Bootstrap route requires `BOOTSTRAP_SECRET`
- [x] Passwords hashed with bcrypt
- [x] `npm run build` and `npm run lint` succeed

## Documentation updates required

- [x] `docs/02-database-schema.md`
- [x] `docs/03-api-specification.md`
- [x] `docs/04-ui-pages.md`
- [x] `docs/01-architecture.md`
- [x] `docs/10-environment-variables.md`
- [x] `docs/11-security.md`
- [x] `docs/16-changelog.md`

**Status:** Complete
