# Security API Architecture

## System Overview

```
┌─────────────────────────────────────────────────────────────────┐
│                         Frontend Dashboard                       │
│                                                                   │
│  ┌────────────────┐  ┌────────────────┐  ┌──────────────────┐  │
│  │ Failed Logins  │  │Password Changes│  │ Security Events  │  │
│  │    Widget      │  │     Widget     │  │     Timeline     │  │
│  └────────────────┘  └────────────────┘  └──────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ HTTP Requests (JWT Auth)
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      Backend API Server                          │
│                                                                   │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │                  Security Routes                          │  │
│  │  /api/security/failed-logins                             │  │
│  │  /api/security/password-changes                          │  │
│  │  /api/security/overview                                  │  │
│  └──────────────────────────────────────────────────────────┘  │
│                              │                                   │
│                              ▼                                   │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │            Security Controller                            │  │
│  │  - getFailedLogins()                                     │  │
│  │  - getPasswordChanges()                                  │  │
│  │  - getSecurityOverview()                                 │  │
│  │  - logFailedLoginAttempt()                               │  │
│  │  - logPasswordChange()                                   │  │
│  └──────────────────────────────────────────────────────────┘  │
│                              │                                   │
│                              ▼                                   │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │               Authentication Flow                         │  │
│  │                                                           │  │
│  │  AuthController.login()     ──►  Log Failed Attempts     │  │
│  │  AuthController.changePassword()  ──►  Log Changes       │  │
│  └──────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ Database Queries
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                        MySQL Database                            │
│                                                                   │
│  ┌──────────────────────┐         ┌─────────────────────────┐  │
│  │ failed_login_attempts│         │password_change_history  │  │
│  ├──────────────────────┤         ├─────────────────────────┤  │
│  │ id                   │         │ id                      │  │
│  │ login_id             │         │ user_id                 │  │
│  │ ip_address           │         │ changed_by              │  │
│  │ user_agent           │         │ ip_address              │  │
│  │ attempted_at         │         │ user_agent              │  │
│  │ reason               │         │ changed_at              │  │
│  └──────────────────────┘         │ change_type             │  │
│                                    └─────────────────────────┘  │
│                                                                   │
│  ┌──────────────────────┐                                       │
│  │ users                │                                       │
│  ├──────────────────────┤                                       │
│  │ id                   │                                       │
│  │ login_id             │                                       │
│  │ name                 │                                       │
│  │ email                │                                       │
│  │ organization_id      │                                       │
│  │ ...                  │                                       │
│  └──────────────────────┘                                       │
└─────────────────────────────────────────────────────────────────┘
```

---

## Request Flow Diagrams

### 1. Failed Login Tracking

```
┌──────────┐
│  User    │
└────┬─────┘
     │
     │ POST /api/auth/login
     │ { login_id, password }
     ▼
┌──────────────────────┐
│ AuthController       │
│ .login()             │
└──────┬───────────────┘
       │
       │ Validate Credentials
       ▼
   ┌────────┐
   │ Valid? │
   └───┬────┘
       │
    ┌──┴──┐
    │ No  │                     ┌───┐
    └──┬──┘                     │Yes│
       │                        └─┬─┘
       │                          │
       ▼                          │
┌──────────────────────┐          │
│ SecurityController   │          │
│ .logFailedLogin()    │          │
└──────┬───────────────┘          │
       │                          │
       ▼                          │
┌──────────────────────┐          │
│ INSERT INTO          │          │
│failed_login_attempts │          │
└──────────────────────┘          │
                                  │
    ┌─────────────────────────────┘
    │
    ▼
┌──────────────────────┐
│ Generate JWT Token   │
│ Update last_seen     │
└──────┬───────────────┘
       │
       ▼
┌──────────────────────┐
│ Return Success +     │
│ Token to User        │
└──────────────────────┘
```

### 2. Password Change Tracking

```
┌──────────┐
│  User    │
└────┬─────┘
     │
     │ PUT /api/auth/change-password
     │ { currentPassword, newPassword }
     │ + JWT Token
     ▼
┌──────────────────────┐
│ AuthController       │
│ .changePassword()    │
└──────┬───────────────┘
       │
       │ Validate Current Password
       │ Hash New Password
       ▼
┌──────────────────────┐
│ UPDATE users         │
│ SET password_hash    │
└──────┬───────────────┘
       │
       ▼
┌──────────────────────┐
│ SecurityController   │
│ .logPasswordChange() │
└──────┬───────────────┘
       │
       ▼
┌──────────────────────┐
│ INSERT INTO          │
│password_change_history│
└──────┬───────────────┘
       │
       ▼
┌──────────────────────┐
│ Return Success       │
│ to User              │
└──────────────────────┘
```

### 3. Get Security Data

```
┌──────────┐
│  User    │
└────┬─────┘
     │
     │ GET /api/security/overview
     │ + JWT Token
     ▼
┌──────────────────────────┐
│ Authenticate Token       │
└──────┬───────────────────┘
       │
       ▼
┌──────────────────────────┐
│ SecurityController       │
│ .getSecurityOverview()   │
└──────┬───────────────────┘
       │
       ├──────────────────────┐
       │                      │
       ▼                      ▼
┌────────────────┐   ┌──────────────────┐
│ Query Failed   │   │ Query Password   │
│ Logins (24h)   │   │ Changes (7d)     │
└────────┬───────┘   └────────┬─────────┘
         │                    │
         │  ┌─────────────────┘
         │  │
         ▼  ▼
┌────────────────────────┐
│ Query Recent Events    │
│ (Combined Timeline)    │
└──────┬─────────────────┘
       │
       ▼
┌────────────────────────┐
│ Check User Role        │
└──────┬─────────────────┘
       │
    ┌──┴───┐
    │      │
    ▼      ▼
┌────────┐ ┌─────────────┐
│ Admin? │ │ User?       │
└───┬────┘ └──┬──────────┘
    │         │
    │         │ Filter to own data only
    │         │
    │         │
    └────┬────┘
         │
         ▼
┌────────────────────────┐
│ Format & Return JSON   │
└────────────────────────┘
```

---

## Data Flow

### Security Event Logging

```
Event Trigger (Login/Password Change)
         │
         ▼
Capture Context Data
  - IP Address
  - User Agent
  - Timestamp
  - Event Details
         │
         ▼
SecurityController.log...()
         │
         ▼
INSERT INTO Database
  (Non-blocking - won't fail auth flow)
         │
         ▼
Event Logged Successfully
```

### Security Data Retrieval

```
API Request + JWT Token
         │
         ▼
Authenticate & Authorize
         │
         ▼
Determine User Role
    ┌────┴────┐
    ▼         ▼
  Admin      User
    │         │
    │         │ Filter by user_id
    │         │
    └────┬────┘
         │
         ▼
Execute SQL Query
  - Time range filtering
  - Organization filtering
  - Result limiting
         │
         ▼
Aggregate Statistics
  - Count totals
  - Count unique values
  - Calculate summaries
         │
         ▼
Format Response
         │
         ▼
Return JSON to Client
```

---

## Database Relationships

```
┌──────────────────────┐
│      users           │
│  ┌────────────────┐  │
│  │ id (PK)        │  │
│  │ login_id       │◄─┐
│  │ organization_id│  │
│  └────────────────┘  │
└──────────────────────┘
           ▲
           │
           │ Foreign Key
           │
    ┌──────┴───────┐
    │              │
    │              │
┌───┴──────────────┴────┐    ┌─────────────────────────┐
│failed_login_attempts  │    │password_change_history  │
├───────────────────────┤    ├─────────────────────────┤
│ id (PK)               │    │ id (PK)                 │
│ login_id              │    │ user_id (FK)            │───┐
│ ip_address            │    │ changed_by (FK)         │───┤
│ user_agent            │    │ ip_address              │   │
│ attempted_at          │    │ user_agent              │   │
│ reason                │    │ changed_at              │   │
└───────────────────────┘    │ change_type             │   │
                             └─────────────────────────┘   │
                                       ▲                   │
                                       │                   │
                                       └───────────────────┘
                                       References users.id
```

---

## Security & Access Control

```
┌─────────────────────────────────────────────────────────────┐
│                    User Makes Request                        │
└──────────────────────────┬──────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────┐
│              JWT Token Authentication                        │
│  - Verify token signature                                    │
│  - Check token expiration                                    │
│  - Extract user info (id, role, org_id)                      │
└──────────────────────────┬──────────────────────────────────┘
                           │
                    ┌──────┴──────┐
                    ▼             ▼
        ┌──────────────┐    ┌──────────────┐
        │ Super_admin  │    │    Admin     │
        │   or Admin   │    │              │
        └──────┬───────┘    └──────┬───────┘
               │                   │
               ▼                   ▼
┌──────────────────────────────────────────────────────────────┐
│              Organization-Level Filtering                     │
│  WHERE organization_id = user.organization_id                │
└──────────────────────────┬───────────────────────────────────┘
                           │
                           ▼
                ┌──────────────────┐
                │   Regular User   │
                └────────┬─────────┘
                         │
                         ▼
┌──────────────────────────────────────────────────────────────┐
│              User-Level Filtering                             │
│  WHERE user_id = user.id OR login_id = user.login_id         │
└──────────────────────────┬───────────────────────────────────┘
                           │
                           ▼
                ┌──────────────────┐
                │  Return Results  │
                └──────────────────┘
```

---

## Component Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    Backend Components                        │
├─────────────────────────────────────────────────────────────┤
│                                                               │
│  ┌───────────────────────────────────────────────────────┐  │
│  │                 Express Middleware                     │  │
│  │  - CORS                                                │  │
│  │  - Rate Limiting                                       │  │
│  │  - Body Parser                                         │  │
│  │  - JWT Authentication (authenticateToken)             │  │
│  └───────────────────────────────────────────────────────┘  │
│                           │                                  │
│                           ▼                                  │
│  ┌───────────────────────────────────────────────────────┐  │
│  │                    Route Layer                         │  │
│  │  /api/security/failed-logins                          │  │
│  │  /api/security/password-changes                       │  │
│  │  /api/security/overview                               │  │
│  └───────────────────────────────────────────────────────┘  │
│                           │                                  │
│                           ▼                                  │
│  ┌───────────────────────────────────────────────────────┐  │
│  │                 Controller Layer                       │  │
│  │                                                         │  │
│  │  SecurityController                                    │  │
│  │  - Business logic                                      │  │
│  │  - Data validation                                     │  │
│  │  - Access control                                      │  │
│  │  - Response formatting                                 │  │
│  │                                                         │  │
│  │  AuthController (updated)                              │  │
│  │  - Login with logging                                  │  │
│  │  - Password change with logging                        │  │
│  └───────────────────────────────────────────────────────┘  │
│                           │                                  │
│                           ▼                                  │
│  ┌───────────────────────────────────────────────────────┐  │
│  │                 Database Layer                         │  │
│  │  - MySQL connection pool                              │  │
│  │  - Prepared statements                                │  │
│  │  - Transaction handling                               │  │
│  └───────────────────────────────────────────────────────┘  │
│                           │                                  │
└───────────────────────────┼──────────────────────────────────┘
                            │
                            ▼
                 ┌──────────────────┐
                 │  MySQL Database  │
                 └──────────────────┘
```

---

## Error Handling Flow

```
Request
   │
   ▼
┌────────────────┐
│ Try Block      │
└────┬───────────┘
     │
     │ Execute Logic
     ▼
  ┌─────┐
  │Error?│
  └──┬──┘
     │
  ┌──┴──┐
  │ No  │               ┌───┐
  └──┬──┘               │Yes│
     │                  └─┬─┘
     │                    │
     ▼                    ▼
┌──────────┐      ┌────────────────┐
│ Return   │      │ Catch Block    │
│ Success  │      └────┬───────────┘
└──────────┘           │
                       │ Identify Error Type
                       ▼
                 ┌──────────────┐
                 │ Error Type?  │
                 └──┬───────────┘
                    │
        ┌───────────┼────────────┐
        │           │            │
        ▼           ▼            ▼
    ┌─────┐   ┌──────────┐  ┌──────┐
    │ 400 │   │   401    │  │ 500  │
    │ Bad │   │Unauthorized│ │Server│
    │Request  │          │  │Error │
    └─────┘   └──────────┘  └──────┘
        │           │            │
        └───────────┼────────────┘
                    │
                    ▼
            ┌───────────────┐
            │ Format Error  │
            │ Response JSON │
            └───────┬───────┘
                    │
                    ▼
            ┌───────────────┐
            │ Return to     │
            │ Client        │
            └───────────────┘
```

---

## Performance Optimizations

### Database Indexes

```
failed_login_attempts
├── PRIMARY KEY (id)
├── INDEX idx_login_id (login_id)
├── INDEX idx_attempted_at (attempted_at)
├── INDEX idx_ip_address (ip_address)
└── INDEX idx_failed_login_attempts_24h (attempted_at DESC)

password_change_history
├── PRIMARY KEY (id)
├── INDEX idx_user_id (user_id)
├── INDEX idx_changed_by (changed_by)
├── INDEX idx_changed_at (changed_at)
└── INDEX idx_password_change_history_7d (changed_at DESC)

Query Optimization:
  - Time-based queries use DESC index
  - JOIN operations use indexed foreign keys
  - WHERE clauses match index columns
```

### Query Limits

```
┌─────────────────┐
│   User Role     │
└────────┬────────┘
         │
    ┌────┴────┐
    │         │
    ▼         ▼
┌────────┐ ┌──────────┐
│ Admin  │ │   User   │
└───┬────┘ └────┬─────┘
    │           │
    │ LIMIT     │ LIMIT
    │ 1000      │ 100
    │           │
    └─────┬─────┘
          │
          ▼
    ┌──────────┐
    │ Results  │
    └──────────┘
```

---

## Deployment Checklist

```
Setup:
  ☐ Run setup_security_tables.js
  ☐ Verify tables created in database
  ☐ Restart backend server
  ☐ Run test_security_api.js

Verification:
  ☐ Try failed login - check if logged
  ☐ Change password - check if logged
  ☐ Call API endpoints - check responses
  ☐ Verify role-based access control

Monitoring:
  ☐ Monitor database table sizes
  ☐ Monitor API response times
  ☐ Check for any errors in logs
  ☐ Verify data retention policy

Documentation:
  ☐ Review SECURITY_API_QUICKSTART.md
  ☐ Review SECURITY_API_DOCUMENTATION.md
  ☐ Update frontend integration docs
```

---

## Technology Stack

```
┌──────────────────────────────────────────┐
│            Technology Stack              │
├──────────────────────────────────────────┤
│                                          │
│  Backend Framework:                      │
│    ✓ Node.js                             │
│    ✓ Express.js                          │
│                                          │
│  Database:                               │
│    ✓ MySQL / MariaDB                     │
│    ✓ Connection Pool                     │
│                                          │
│  Authentication:                         │
│    ✓ JWT (JSON Web Tokens)              │
│    ✓ bcryptjs (password hashing)         │
│                                          │
│  Security:                               │
│    ✓ Helmet (security headers)           │
│    ✓ CORS                                │
│    ✓ Rate Limiting                       │
│                                          │
│  Additional:                             │
│    ✓ express-validator                   │
│    ✓ morgan (logging)                    │
│    ✓ compression                         │
│                                          │
└──────────────────────────────────────────┘
```

---

This architecture provides a robust, scalable, and secure foundation for tracking security events in your CMS application.

