# Tasks: Authentication & User Management Module

## Relevant Files

### Core Auth Infrastructure
- `lib/auth.ts` - Better Auth server configuration with plugins
- `lib/auth-client.ts` - Better Auth client for React components
- `lib/auth-utils.ts` - Server-side auth utilities and permission checking
- `lib/permissions.ts` - RBAC permission definitions and access control
- `lib/bootstrap.ts` - Bootstrap and initial setup functions
- `lib/services/email.ts` - SMTP email service for magic links
- `lib/services/audit.ts` - Audit logging service
- `app/api/auth/[...all]/route.ts` - Better Auth API route handler
- `middleware.ts` - Route protection middleware

### Database Migrations
- `migrations/012_create_auth_tables.sql` - Better Auth core tables (user, session, account, verification, two_factor)
- `migrations/013_create_role_tables.sql` - Role and permission tables with default roles
- `migrations/014_create_admin_settings.sql` - App settings, session policies, email templates, and audit log tables

### Auth Pages
- `app/auth/sign-in/page.tsx` - Sign-in page with magic link and Microsoft options
- `app/auth/verify/page.tsx` - Magic link verification page
- `app/auth/2fa/page.tsx` - Two-factor authentication verification page
- `app/auth/setup/page.tsx` - Initial account setup page
- `app/auth/layout.tsx` - Auth pages layout (no navigation)

### Auth Components
- `components/auth/auth-provider.tsx` - Auth context provider for React
- `components/auth/sign-in-form.tsx` - Combined sign-in form with both auth methods
- `components/auth/magic-link-form.tsx` - Email input for magic link
- `components/auth/microsoft-button.tsx` - Microsoft 365 OAuth button
- `components/auth/two-factor-form.tsx` - TOTP code input form

### User Management Pages
- `app/admin/users/page.tsx` - User list page
- `app/admin/users/[id]/page.tsx` - User detail/edit page
- `app/admin/users/invite/page.tsx` - Invite user page

### User Management Components
- `components/admin/users/user-table.tsx` - User list table with actions
- `components/admin/users/user-form.tsx` - Create/edit user form
- `components/admin/users/invite-user-form.tsx` - Invite user via email form
- `components/admin/users/role-badge.tsx` - Role display badge
- `components/admin/users/user-actions.tsx` - User action dropdown menu
- `components/admin/users/user-sessions.tsx` - User session history

### Role Management Pages
- `app/admin/roles/page.tsx` - Role list page
- `app/admin/roles/[id]/page.tsx` - Role detail/edit page
- `app/admin/roles/new/page.tsx` - Create new role page

### Role Management Components
- `components/admin/roles/role-table.tsx` - Role list table
- `components/admin/roles/role-form.tsx` - Create/edit role form
- `components/admin/roles/permission-picker.tsx` - Permission selection UI

### Admin Settings Pages
- `app/admin/settings/page.tsx` - Admin settings page with tabs
- `app/admin/audit-log/page.tsx` - Audit log viewer page

### Admin Settings Components
- `components/admin/settings/microsoft-config.tsx` - Microsoft tenant configuration
- `components/admin/settings/session-policies.tsx` - CIDR session policy management
- `components/admin/settings/email-templates.tsx` - Email template editor
- `components/admin/audit/audit-log-table.tsx` - Audit log table with filters

### User Settings Pages
- `app/settings/page.tsx` - User settings page
- `app/settings/security/page.tsx` - Security settings (2FA, sessions)

### User Settings Components
- `components/settings/profile-form.tsx` - User profile edit form
- `components/settings/two-factor-setup.tsx` - 2FA setup wizard
- `components/settings/active-sessions.tsx` - Current user's active sessions

### API Routes
- `app/api/admin/users/route.ts` - User CRUD API
- `app/api/admin/users/[id]/route.ts` - Single user API
- `app/api/admin/users/invite/route.ts` - User invitation API
- `app/api/admin/roles/route.ts` - Role CRUD API
- `app/api/admin/roles/[id]/route.ts` - Single role API
- `app/api/admin/settings/route.ts` - App settings API
- `app/api/admin/settings/session-policies/route.ts` - Session policies API
- `app/api/admin/settings/email-templates/route.ts` - Email templates API
- `app/api/admin/audit-log/route.ts` - Audit log API
- `app/api/settings/profile/route.ts` - User profile API

### Notes

- Unit tests should typically be placed alongside the code files they are testing (e.g., `MyComponent.tsx` and `MyComponent.test.tsx` in the same directory).
- Use `npx jest [optional/path/to/test/file]` to run tests. Running without a path executes all tests found by the Jest configuration.
- Better Auth handles most auth logic internally; focus tests on custom business logic.
- Use existing shadcn/ui components from `/components/ui/` for consistency.

## Tasks

- [x] 1.0 Setup Better Auth Core Infrastructure
  - [x] 1.1 Install Better Auth dependencies (`better-auth`, `@better-auth/cli`)
  - [x] 1.2 Add required environment variables to `.env` and `.env.local` (BETTER_AUTH_SECRET, BETTER_AUTH_URL, SMTP_*, DEFAULT_ADMIN_*, SESSION_TIMEOUT_SECONDS, AUDIT_LOG_RETENTION_DAYS)
  - [x] 1.3 Create database migration for Better Auth core tables (user, session, account, verification)
  - [x] 1.4 Create `lib/auth.ts` with Better Auth server configuration
  - [x] 1.5 Create `lib/auth-client.ts` with Better Auth client for React
  - [x] 1.6 Create `app/api/auth/[...all]/route.ts` API route handler
  - [x] 1.7 Create `middleware.ts` for route protection (redirect unauthenticated users to /auth/sign-in)
  - [x] 1.8 Create `lib/services/email.ts` SMTP email service using environment variables
  - [x] 1.9 Update `app/layout.tsx` to wrap app with auth session provider

- [x] 2.0 Implement Authentication Methods (Magic Link & Microsoft 365)
  - [x] 2.1 Configure magic link plugin in `lib/auth.ts` with sendMagicLink callback using SMTP service
  - [x] 2.2 Configure Microsoft OAuth provider in `lib/auth.ts` with client ID/secret from env
  - [x] 2.3 Create `app/auth/layout.tsx` - minimal layout without main navigation
  - [x] 2.4 Create `app/auth/sign-in/page.tsx` - sign-in page container
  - [x] 2.5 Create `components/auth/magic-link-form.tsx` - email input with submit
  - [x] 2.6 Create `components/auth/microsoft-button.tsx` - Microsoft 365 OAuth button
  - [x] 2.7 Create `components/auth/sign-in-form.tsx` - combined form with both methods
  - [x] 2.8 Create `app/auth/verify/page.tsx` - magic link verification handler
  - [x] 2.9 Implement "check your email" success state in magic link form
  - [x] 2.10 Add error handling for failed auth attempts with toast notifications

- [x] 3.0 Implement RBAC & Permission System
  - [x] 3.1 Create database migration for role and permission tables
  - [x] 3.2 Create `lib/permissions.ts` with permission definitions (tickets, configItems, admin, users, roles, auditLog)
  - [x] 3.3 Define default roles (super-admin, admin, user) with their permissions
  - [x] 3.4 Configure Better Auth admin plugin with access control in `lib/auth.ts`
  - [x] 3.5 Update `lib/auth-client.ts` with admin client plugin
  - [x] 3.6 Create helper function `hasPermission(user, resource, action)` for checking permissions
  - [x] 3.7 Update `middleware.ts` to check roles for `/admin/*` routes (require admin or super-admin)
  - [x] 3.8 Create API middleware helper for permission checking in route handlers
  - [x] 3.9 Seed default roles into database on first run

- [x] 4.0 Build User Management Module
  - [x] 4.1 Create `app/api/admin/users/route.ts` - GET (list users), POST (create user)
  - [x] 4.2 Create `app/api/admin/users/[id]/route.ts` - GET, PATCH, DELETE single user
  - [x] 4.3 Create `app/api/admin/users/invite/route.ts` - POST to send invitation email
  - [x] 4.4 Create `components/admin/users/role-badge.tsx` - badge component for role display
  - [x] 4.5 Create `components/admin/users/user-table.tsx` - table with columns: name, email, role, status, actions
  - [x] 4.6 Create `components/admin/users/user-actions.tsx` - dropdown with edit, deactivate, delete, revoke sessions
  - [x] 4.7 Create `app/admin/users/page.tsx` - user list page with search/filter
  - [x] 4.8 Create `components/admin/users/user-form.tsx` - form for editing user (name, email, role)
  - [x] 4.9 Create `app/admin/users/[id]/page.tsx` - user detail page with edit form and session history
  - [x] 4.10 Create `components/admin/users/invite-user-form.tsx` - email input with role selection
  - [x] 4.11 Create `app/admin/users/invite/page.tsx` - invite user page
  - [x] 4.12 Create `components/admin/users/user-sessions.tsx` - table of user's sessions with revoke
  - [x] 4.13 Implement soft delete (deactivate) and reactivate functionality
  - [x] 4.14 Implement permanent delete with confirmation dialog
  - [x] 4.15 Add super-admin role check to all user management routes

- [x] 5.0 Build Role Management Module
  - [x] 5.1 Create `app/api/admin/roles/route.ts` - GET (list roles), POST (create role)
  - [x] 5.2 Create `app/api/admin/roles/[id]/route.ts` - GET, PATCH, DELETE single role
  - [x] 5.3 Create `components/admin/roles/permission-picker.tsx` - checkbox grid for selecting permissions
  - [x] 5.4 Create `components/admin/roles/role-table.tsx` - table with columns: name, permissions count, users count, actions
  - [x] 5.5 Create `app/admin/roles/page.tsx` - role list page
  - [x] 5.6 Create `components/admin/roles/role-form.tsx` - form with name input and permission picker
  - [x] 5.7 Create `app/admin/roles/new/page.tsx` - create new role page
  - [x] 5.8 Create `app/admin/roles/[id]/page.tsx` - edit role page
  - [x] 5.9 Prevent deletion of default roles (super-admin, admin, user)
  - [x] 5.10 Prevent deletion of roles that are assigned to users (show error)
  - [x] 5.11 Add super-admin role check to all role management routes

- [x] 6.0 Implement Admin Settings (Microsoft Tenant, Session Policies, Email Templates)
  - [x] 6.1 Create database migration for app_settings table
  - [x] 6.2 Create database migration for session_policy table (name, cidr, timeout_seconds, priority)
  - [x] 6.3 Create database migration for email_template table (type, subject, body_html)
  - [x] 6.4 Create `app/api/admin/settings/route.ts` - GET/PATCH app settings
  - [x] 6.5 Create `app/api/admin/settings/session-policies/route.ts` - CRUD for session policies
  - [x] 6.6 Create `app/api/admin/settings/email-templates/route.ts` - GET/PATCH email templates
  - [x] 6.7 Create `components/admin/settings/microsoft-config.tsx` - tenant ID input with validation
  - [x] 6.8 Create `components/admin/settings/session-policies.tsx` - table with add/edit/delete for CIDR policies
  - [x] 6.9 Implement CIDR notation validation (e.g., `192.168.1.0/24`)
  - [x] 6.10 Create `components/admin/settings/email-templates.tsx` - template editor with variable hints
  - [x] 6.11 Create `app/admin/settings/page.tsx` - settings page with tabs (Microsoft, Sessions, Email)
  - [x] 6.12 Seed default email templates (magic_link, invitation) on first run
  - [x] 6.13 Update auth config to dynamically load Microsoft tenant from app_settings
  - [x] 6.14 Update session creation to check CIDR policies and set appropriate timeout

- [x] 7.0 Implement Security Features (2FA, Session Management, Audit Logging)
  - [x] 7.1 Configure two-factor plugin in `lib/auth.ts`
  - [x] 7.2 Update `lib/auth-client.ts` with two-factor client plugin
  - [x] 7.3 Create `components/auth/two-factor-form.tsx` - TOTP code input
  - [x] 7.4 Create `app/auth/2fa/page.tsx` - 2FA verification page
  - [x] 7.5 Create `components/settings/two-factor-setup.tsx` - QR code display and verification
  - [x] 7.6 Create `components/settings/active-sessions.tsx` - current user's sessions with revoke
  - [x] 7.7 Create `app/settings/page.tsx` - user settings with profile tab
  - [x] 7.8 Create `app/settings/security/page.tsx` - security settings (2FA toggle, sessions)
  - [x] 7.9 Create database migration for audit_log table (timestamp, user_id, action, resource, details, ip_address)
  - [x] 7.10 Create `lib/services/audit.ts` - audit logging service with log() function
  - [x] 7.11 Add audit logging to auth events (sign-in, sign-out, failed attempts)
  - [x] 7.12 Add audit logging to user management actions (create, edit, delete, role change)
  - [x] 7.13 Add audit logging to role management actions
  - [x] 7.14 Create `app/api/admin/audit-log/route.ts` - GET with pagination and filters
  - [x] 7.15 Create `components/admin/audit/audit-log-table.tsx` - table with filters (date range, user, action)
  - [x] 7.16 Create `app/admin/audit-log/page.tsx` - audit log viewer page
  - [x] 7.17 Implement audit log retention (delete records older than AUDIT_LOG_RETENTION_DAYS)
  - [x] 7.18 Create scheduled job or API endpoint to purge old audit logs
  - [x] 7.19 Implement rate limiting on auth endpoints (sign-in, magic-link)

- [x] 8.0 Implement Bootstrap & Initial Setup Flow
  - [x] 8.1 Create bootstrap check function to detect if any users exist
  - [x] 8.2 Create seed script to create default super-admin from DEFAULT_ADMIN_EMAIL and DEFAULT_ADMIN_NAME env vars
  - [x] 8.3 Add `requires_setup` flag to user table for accounts needing reconfiguration
  - [x] 8.4 Create setup detection in middleware - redirect setup accounts to `/auth/setup`
  - [x] 8.5 Create `app/auth/setup/page.tsx` - forced setup page for default account
  - [x] 8.6 Create `components/auth/setup-form.tsx` - form to link Microsoft account or set up magic link
  - [x] 8.7 Clear `requires_setup` flag after successful setup completion
  - [x] 8.8 Display warning banner for setup accounts until reconfigured
  - [x] 8.9 Run bootstrap/seed on application startup if no users exist
  - [x] 8.10 Add documentation for initial setup process in README
