# Authentication & User Management Flow Guide

This document explains how authentication and user management works in the Notification Microservice.

## Overview

The system uses **two types of authentication**:

1. **API Key Authentication** (Server-to-Server)
   - Used for: Event ingestion, user creation, project operations
   - Headers: `X-API-Key` and `X-API-Secret`
   - No user context required

2. **JWT Authentication** (User Operations)
   - Used for: User profile, notifications, rules management
   - Header: `Authorization: Bearer <jwt_token>`
   - Requires an authenticated user

---

## User Status Flow

Users can have one of four statuses:

```
┌─────────┐
│ PENDING │  ← New users start here (awaiting admin approval)
└────┬────┘
     │ Admin approves
     ▼
┌─────────┐
│ ACTIVE  │  ← Only active users can login
└────┬────┘
     │ Admin disables
     ▼
┌──────────┐
│ DISABLED │  ← Cannot login
└──────────┘

┌────────────┐
│ UNVERIFIED │  ← Created without password (via API)
└────────────┘
```

---

## Complete User Lifecycle Flow

### Flow 1: User Self-Registration (Recommended for End Users)

```
┌─────────────────────────────────────────────────────────────┐
│ Step 1: User Registration                                    │
│ POST /api/v1/auth/register                                   │
│ Headers: X-API-Key, X-API-Secret                             │
│ Body: { email, password, fullName, externalUserId, roles }  │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│ User Created with Status: "pending"                         │
│ Returns: JWT tokens (but user cannot use them yet)           │
│ Webhook: "user.registered" event sent                       │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│ Step 2: Admin Approval (Required)                           │
│ POST /api/v1/users/:id/approve                               │
│ Headers: Authorization: Bearer <admin_jwt_token>             │
│ Body: { roles: ["user", "admin"] }                           │
│ Requires: Admin role                                         │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│ User Status Changed: "pending" → "active"                    │
│ Roles assigned                                                │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│ Step 3: User Login                                           │
│ POST /api/v1/auth/login                                      │
│ Headers: X-API-Key, X-API-Secret                             │
│ Body: { email, password }                                    │
│ Note: Only "active" users can login                          │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│ Returns: JWT Access Token + Refresh Token                     │
│ User can now access protected endpoints                      │
└─────────────────────────────────────────────────────────────┘
```

### Flow 2: Server-Side User Creation (For Bulk Operations)

```
┌─────────────────────────────────────────────────────────────┐
│ Step 1: Create User (Server-to-Server)                      │
│ POST /api/v1/users                                            │
│ Headers: X-API-Key, X-API-Secret                             │
│ Body: { email, password, fullName, externalUserId, roles }  │
│ Note: No JWT tokens returned                                 │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│ User Created with Status: "pending" (if password provided)   │
│                      or "unverified" (if no password)         │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│ Step 2: Admin Approval (Same as Flow 1)                      │
│ POST /api/v1/users/:id/approve                               │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│ Step 3: User Login (Same as Flow 1)                          │
│ POST /api/v1/auth/login                                      │
└─────────────────────────────────────────────────────────────┘
```

---

## Authentication Endpoints Explained

### 1. User Registration (`POST /api/v1/auth/register`)

**Purpose:** Allow end users to self-register

**Authentication:** Requires API Key (X-API-Key, X-API-Secret)
- The API Key identifies which project the user belongs to
- The endpoint is "public" (no JWT needed) but requires API Key

**What happens:**
1. System extracts project ID from API Key
2. Checks if user with email already exists in project
3. Hashes password with bcrypt
4. Creates user with status = `"pending"`
5. Generates JWT tokens (but user cannot use them until approved)
6. Sends webhook event `user.registered`
7. Returns tokens + user info

**Important:** User receives tokens but **cannot login** until admin approves them.

**Example Request:**
```bash
curl -X POST http://localhost:3000/api/v1/auth/register \
  -H "X-API-Key: pk_dev_abc123" \
  -H "X-API-Secret: sk_dev_xyz789" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "securePassword123!",
    "fullName": "John Doe",
    "externalUserId": "ext_user_123",
    "roles": ["user"]
  }'
```

**Example Response:**
```json
{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "12345678-9abc-def0-1234-567890abcdef01",
    "email": "user@example.com",
    "fullName": "John Doe",
    "roles": ["user"],
    "status": "pending"  ← Note: status is "pending"
  }
}
```

---

### 2. User Login (`POST /api/v1/auth/login`)

**Purpose:** Authenticate an existing user and get JWT tokens

**Authentication:** Requires API Key (X-API-Key, X-API-Secret)
- API Key identifies the project
- User provides email + password

**What happens:**
1. System extracts project ID from API Key
2. Finds user by email in that project
3. Verifies password with bcrypt
4. **Checks user status - only "active" users can login**
5. Updates `lastLoginAt` timestamp
6. Generates new JWT tokens
7. Returns tokens + user info

**Important:** Users with status `"pending"`, `"disabled"`, or `"unverified"` **cannot login**.

**Example Request:**
```bash
curl -X POST http://localhost:3000/api/v1/auth/login \
  -H "X-API-Key: pk_dev_abc123" \
  -H "X-API-Secret: sk_dev_xyz789" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "securePassword123!"
  }'
```

**Example Response:**
```json
{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "12345678-9abc-def0-1234-567890abcdef01",
    "email": "user@example.com",
    "fullName": "John Doe",
    "roles": ["user"],
    "status": "active"  ← Note: must be "active"
  }
}
```

**Error if user is not active:**
```json
{
  "statusCode": 401,
  "message": "User account is pending. Please contact an administrator."
}
```

---

### 3. Refresh Token (`POST /api/v1/auth/refresh`)

**Purpose:** Get new access token when current one expires

**Authentication:** None required (public endpoint)
- Only needs a valid refresh token

**What happens:**
1. Verifies refresh token signature
2. Extracts user ID and project ID from token
3. Finds user and verifies status is "active"
4. Generates new access + refresh tokens
5. Returns new tokens

**Example Request:**
```bash
curl -X POST http://localhost:3000/api/v1/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{
    "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }'
```

---

## User Management Endpoints Explained

### 1. Create User (Server-to-Server) (`POST /api/v1/users`)

**Purpose:** Create users programmatically (bulk operations, syncing)

**Authentication:** API Key only (X-API-Key, X-API-Secret)

**Difference from `/auth/register`:**
- No JWT tokens returned
- Can create users without passwords (status = "unverified")
- Used for server-to-server operations
- Better for bulk user syncing

**Example Request:**
```bash
curl -X POST http://localhost:3000/api/v1/users \
  -H "X-API-Key: pk_dev_abc123" \
  -H "X-API-Secret: sk_dev_xyz789" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user2@example.com",
    "password": "securePassword123!",
    "fullName": "Jane Doe",
    "externalUserId": "ext_user_456",
    "roles": ["user"]
  }'
```

---

### 2. Approve User (`POST /api/v1/users/:id/approve`)

**Purpose:** Admin approves a pending user and assigns roles

**Authentication:** JWT token with "admin" role

**What happens:**
1. Changes user status from "pending" → "active"
2. Assigns/updates user roles
3. User can now login

**Example Request:**
```bash
curl -X POST http://localhost:3000/api/v1/users/12345678-9abc-def0-1234-567890abcdef01/approve \
  -H "Authorization: Bearer <admin_jwt_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "roles": ["user", "finance"]
  }'
```

---

### 3. Get Current User (`GET /api/v1/users/me`)

**Purpose:** Get authenticated user's profile

**Authentication:** JWT token (any active user)

**Example Request:**
```bash
curl -X GET http://localhost:3000/api/v1/users/me \
  -H "Authorization: Bearer <jwt_token>"
```

---

## Complete Example Flow

### Scenario: New User Registration and Login

```bash
# Step 1: User registers
POST /api/v1/auth/register
Headers: X-API-Key, X-API-Secret
Body: { email, password, fullName }
Response: { accessToken, refreshToken, user: { status: "pending" } }

# Step 2: Admin views pending users
GET /api/v1/users/pending
Headers: Authorization: Bearer <admin_jwt_token>
Response: [ { id, email, status: "pending" } ]

# Step 3: Admin approves user
POST /api/v1/users/:id/approve
Headers: Authorization: Bearer <admin_jwt_token>
Body: { roles: ["user"] }
Response: { id, email, status: "active", roles: ["user"] }

# Step 4: User logs in (now that they're active)
POST /api/v1/auth/login
Headers: X-API-Key, X-API-Secret
Body: { email, password }
Response: { accessToken, refreshToken, user: { status: "active" } }

# Step 5: User accesses their profile
GET /api/v1/users/me
Headers: Authorization: Bearer <jwt_token>
Response: { id, email, fullName, roles, status: "active" }

# Step 6: User updates push tokens
PATCH /api/v1/users/me/push-tokens
Headers: Authorization: Bearer <jwt_token>
Body: { fcm: "fcm_token", apns: "apns_token" }
Response: { pushTokens: { fcm, apns } }
```

---

## Key Points to Remember

1. **API Key Authentication** is for:
   - Server-to-server operations
   - Event ingestion
   - User creation (both `/auth/register` and `/users`)
   - Project operations

2. **JWT Authentication** is for:
   - User-specific operations
   - Viewing notifications
   - Managing profile
   - Admin operations (requires admin role)

3. **User Status Matters:**
   - `pending`: Just registered, awaiting approval
   - `active`: Approved, can login
   - `disabled`: Cannot login
   - `unverified`: Created without password

4. **Registration vs Login:**
   - Registration returns tokens but user cannot use them until approved
   - Login only works for "active" users
   - Always check user status in responses

5. **Two Ways to Create Users:**
   - `/auth/register`: For end-user self-registration (returns tokens)
   - `/users`: For server-side bulk operations (no tokens)

---

## Common Issues and Solutions

### Issue: "User account is pending. Please contact an administrator."
**Solution:** User needs to be approved by admin via `POST /api/v1/users/:id/approve`

### Issue: "Project context not set"
**Solution:** Make sure you're sending `X-API-Key` and `X-API-Secret` headers

### Issue: "Invalid credentials"
**Solution:** Check email/password, or user might not exist in this project

### Issue: JWT token expired
**Solution:** Use `POST /api/v1/auth/refresh` with refresh token

---

## Security Notes

1. **API Keys** should be kept secret and rotated regularly
2. **JWT tokens** expire after 1 hour (access) or 30 days (refresh)
3. **Passwords** are hashed with bcrypt (12 rounds)
4. **User status** is checked on every login
5. **Project isolation** - users are scoped to their project via API Key



