# Security API Documentation

## Overview
This document describes the Security API endpoints for tracking failed login attempts and password changes in the CMS Backend system. These endpoints are designed to provide security monitoring and auditing capabilities.

## Base URL
```
http://localhost:3000/api/security
```

## Authentication
All security endpoints require authentication via JWT token in the Authorization header:
```
Authorization: Bearer <token>
```

## Permissions
- **Regular Users**: Can view their own security events (failed logins and password changes)
- **Admin/Super_admin**: Can view all security events within their organization

---

## API Endpoints

### 1. Get Failed Login Attempts

**GET** `/api/security/failed-logins`

Get failed login attempts within a specified time period.

**Query Parameters:**
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| hours | integer | No | 24 | Number of hours to look back (1-720) |

**Request Example:**
```bash
GET /api/security/failed-logins?hours=24
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

**Response (Success):**
```json
{
  "status": "success",
  "data": {
    "attempts": [
      {
        "id": 1,
        "login_id": "user123",
        "ip_address": "192.168.1.100",
        "user_agent": "Mozilla/5.0...",
        "attempted_at": "2025-10-25T10:30:45.000Z",
        "reason": "Invalid password",
        "user_name": "John Doe",
        "user_email": "john.doe@navy.mil"
      },
      {
        "id": 2,
        "login_id": "test_user",
        "ip_address": "192.168.1.101",
        "user_agent": "Mozilla/5.0...",
        "attempted_at": "2025-10-25T09:15:30.000Z",
        "reason": "User not found",
        "user_name": null,
        "user_email": null
      }
    ],
    "summary": {
      "total_attempts": 45,
      "unique_users": 12,
      "unique_ips": 8,
      "first_attempt": "2025-10-24T10:30:45",
      "last_attempt": "2025-10-25T10:30:45"
    },
    "period_hours": 24,
    "timestamp": "2025-10-25T11:00:00.000Z"
  }
}
```

**Response (Error):**
```json
{
  "status": "error",
  "message": "Hours must be between 1 and 720 (30 days)"
}
```

**Failed Login Reasons:**
- `Invalid password` - Incorrect password provided
- `User not found` - Login ID does not exist
- `Account is deactivated` - User account is disabled

---

### 2. Get Password Changes

**GET** `/api/security/password-changes`

Get password changes within a specified time period.

**Query Parameters:**
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| days | integer | No | 7 | Number of days to look back (1-365) |

**Request Example:**
```bash
GET /api/security/password-changes?days=7
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

**Response (Success):**
```json
{
  "status": "success",
  "data": {
    "changes": [
      {
        "id": 1,
        "user_id": 10,
        "changed_by": 10,
        "ip_address": "192.168.1.100",
        "user_agent": "Mozilla/5.0...",
        "changed_at": "2025-10-24T14:20:30.000Z",
        "change_type": "self",
        "user_name": "John Doe",
        "user_email": "john.doe@navy.mil",
        "login_id": "johnd",
        "changed_by_name": "John Doe",
        "changed_by_email": "john.doe@navy.mil"
      },
      {
        "id": 2,
        "user_id": 15,
        "changed_by": 2,
        "ip_address": "192.168.1.5",
        "user_agent": "Mozilla/5.0...",
        "changed_at": "2025-10-23T09:15:00.000Z",
        "change_type": "admin_reset",
        "user_name": "Jane Smith",
        "user_email": "jane.smith@navy.mil",
        "login_id": "janes",
        "changed_by_name": "Super Admin",
        "changed_by_email": "admin@navy.mil"
      }
    ],
    "summary": {
      "total_changes": 23,
      "unique_users": 18,
      "self_changes": 20,
      "admin_resets": 3,
      "forced_changes": 0,
      "first_change": "2025-10-18T14:20:30",
      "last_change": "2025-10-24T14:20:30"
    },
    "period_days": 7,
    "timestamp": "2025-10-25T11:00:00.000Z"
  }
}
```

**Response (Error):**
```json
{
  "status": "error",
  "message": "Days must be between 1 and 365"
}
```

**Password Change Types:**
- `self` - User changed their own password
- `admin_reset` - Admin/Super_admin reset the user's password
- `forced` - Forced password change (e.g., after security breach)

---

### 3. Get Security Overview

**GET** `/api/security/overview`

Get a comprehensive security overview including failed logins (24h) and password changes (7d).

**Request Example:**
```bash
GET /api/security/overview
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

**Response (Success):**
```json
{
  "status": "success",
  "data": {
    "failed_logins_24h": {
      "total_attempts": 45,
      "unique_users": 12,
      "unique_ips": 8
    },
    "password_changes_7d": {
      "total_changes": 23,
      "unique_users": 18,
      "self_changes": 20,
      "admin_resets": 3
    },
    "recent_events": [
      {
        "event_type": "failed_login",
        "user_identifier": "user123",
        "user_name": "John Doe",
        "ip_address": "192.168.1.100",
        "event_time": "2025-10-25T10:30:45.000Z",
        "details": "Invalid password"
      },
      {
        "event_type": "password_change",
        "user_identifier": "johnd",
        "user_name": "John Doe",
        "ip_address": "192.168.1.100",
        "event_time": "2025-10-24T14:20:30.000Z",
        "details": "self"
      }
    ],
    "timestamp": "2025-10-25T11:00:00.000Z"
  }
}
```

---

## Database Schema

### failed_login_attempts

Tracks all failed login attempts for security monitoring.

```sql
CREATE TABLE `failed_login_attempts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `login_id` varchar(100) DEFAULT NULL,
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `attempted_at` timestamp NULL DEFAULT current_timestamp(),
  `reason` varchar(255) DEFAULT 'Invalid credentials',
  PRIMARY KEY (`id`),
  KEY `idx_login_id` (`login_id`),
  KEY `idx_attempted_at` (`attempted_at`),
  KEY `idx_ip_address` (`ip_address`)
);
```

### password_change_history

Tracks password change history for security auditing.

```sql
CREATE TABLE `password_change_history` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `changed_by` int(11) NOT NULL,
  `ip_address` varchar(45) DEFAULT NULL,
  `user_agent` text DEFAULT NULL,
  `changed_at` timestamp NULL DEFAULT current_timestamp(),
  `change_type` enum('self','admin_reset','forced') DEFAULT 'self',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_changed_by` (`changed_by`),
  KEY `idx_changed_at` (`changed_at`),
  CONSTRAINT `password_change_history_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `password_change_history_ibfk_2` FOREIGN KEY (`changed_by`) REFERENCES `users` (`id`) ON DELETE CASCADE
);
```

---

## Setup Instructions

### 1. Create Database Tables

Run the SQL script to create the required tables:

```bash
mysql -u root -p cms_db < backend/database/create_security_tables.sql
```

Or execute the SQL directly in your database client:

```sql
USE cms_db;

-- Execute the contents of create_security_tables.sql
```

### 2. Restart Backend Server

After creating the tables, restart your backend server:

```bash
cd backend
npm start
```

### 3. Test the Endpoints

Test the security endpoints using curl or Postman:

```bash
# Get failed logins (24 hours)
curl -X GET http://localhost:3000/api/security/failed-logins \
  -H "Authorization: Bearer YOUR_TOKEN"

# Get failed logins (48 hours)
curl -X GET http://localhost:3000/api/security/failed-logins?hours=48 \
  -H "Authorization: Bearer YOUR_TOKEN"

# Get password changes (7 days)
curl -X GET http://localhost:3000/api/security/password-changes \
  -H "Authorization: Bearer YOUR_TOKEN"

# Get password changes (30 days)
curl -X GET http://localhost:3000/api/security/password-changes?days=30 \
  -H "Authorization: Bearer YOUR_TOKEN"

# Get security overview
curl -X GET http://localhost:3000/api/security/overview \
  -H "Authorization: Bearer YOUR_TOKEN"
```

---

## Integration with Login Flow

The security tracking is automatically integrated into the authentication flow:

### Failed Login Tracking

Failed login attempts are automatically logged when:
- User provides an invalid login ID
- User provides an incorrect password
- User account is deactivated

This is handled in `authController.js`:

```javascript
// Log failed login attempt - invalid password
await SecurityController.logFailedLoginAttempt(
  login_id, 
  ipAddress, 
  userAgent, 
  'Invalid password'
)
```

### Password Change Tracking

Password changes are automatically logged when:
- User successfully changes their password via `/api/auth/change-password`

This is handled in `authController.js`:

```javascript
// Log password change
await SecurityController.logPasswordChange(
  userId, 
  userId, 
  ipAddress, 
  userAgent, 
  'self'
)
```

---

## Security Considerations

1. **Data Retention**: Consider implementing a data retention policy to automatically clean up old security logs (e.g., delete records older than 90 days)

2. **Rate Limiting**: Failed login attempts are tracked but not automatically blocked. Consider implementing account lockout after multiple failed attempts.

3. **IP Tracking**: IP addresses are logged for security analysis. Ensure compliance with privacy regulations.

4. **User Agent Storage**: User agent strings are stored to help identify suspicious activity patterns.

5. **Access Control**: 
   - Regular users can only view their own security events
   - Admins can view all security events within their organization
   - Cross-organization access is prevented

---

## Error Handling

All endpoints use consistent error response format:

```json
{
  "status": "error",
  "message": "Error description"
}
```

Common error codes:
- `400` - Bad Request (invalid parameters)
- `401` - Unauthorized (missing or invalid token)
- `500` - Internal Server Error

---

## Performance Considerations

1. **Indexing**: The tables are indexed on frequently queried columns (`attempted_at`, `changed_at`, `login_id`, `user_id`)

2. **Query Limits**: Queries are limited to prevent performance issues:
   - Admin queries: 1000 records max
   - User queries: 100 records max

3. **Time Range Limits**:
   - Failed logins: 1-720 hours (30 days)
   - Password changes: 1-365 days (1 year)

---

## Future Enhancements

Potential future improvements:

1. **Real-time Alerts**: Send notifications for suspicious activity (multiple failed logins, etc.)
2. **Account Lockout**: Automatically lock accounts after N failed login attempts
3. **Geolocation**: Track geographic location of login attempts
4. **Export Functionality**: Allow exporting security logs to CSV/PDF
5. **Advanced Analytics**: Provide charts and visualizations for security trends
6. **Two-Factor Authentication**: Integrate 2FA for enhanced security
7. **Session Management**: Track active sessions and allow users to revoke sessions

---

## Support

For issues or questions regarding the Security API, please contact the development team or refer to the main project documentation.

