# Security API - Quick Start Guide

## Overview

The Security API provides endpoints to track and monitor:
- **Failed Login Attempts** (last 24 hours)
- **Password Changes** (last 7 days)

These endpoints are designed for the Security Overview feature in the dashboard.

---

## 🚀 Quick Setup (3 Steps)

### Step 1: Create Database Tables

Run the setup script:

```bash
cd backend
node setup_security_tables.js
```

Expected output:
```
🔧 Setting up security tables...
Creating failed_login_attempts table...
✅ failed_login_attempts table created successfully
Creating password_change_history table...
✅ password_change_history table created successfully
Creating performance indexes...
✅ Performance indexes created successfully

✅ Security tables setup completed successfully!
```

### Step 2: Restart Backend Server

```bash
# Stop the current server (Ctrl+C)
# Then restart:
npm start
```

### Step 3: Test the API

```bash
# Login first to get a token
curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"login_id":"super_admin","password":"admin123"}'

# Copy the token from the response, then:
export TOKEN="your_token_here"

# Get failed logins (last 24 hours)
curl -X GET http://localhost:3000/api/security/failed-logins \
  -H "Authorization: Bearer $TOKEN"

# Get password changes (last 7 days)
curl -X GET http://localhost:3000/api/security/password-changes \
  -H "Authorization: Bearer $TOKEN"

# Get security overview
curl -X GET http://localhost:3000/api/security/overview \
  -H "Authorization: Bearer $TOKEN"
```

Or run the automated test:

```bash
node test_security_api.js
```

---

## 📊 API Endpoints

### 1. Failed Logins

```
GET /api/security/failed-logins?hours=24
```

**Query Parameters:**
- `hours` (optional): Number of hours to look back (1-720, default: 24)

**Response:**
```json
{
  "status": "success",
  "data": {
    "attempts": [...],
    "summary": {
      "total_attempts": 45,
      "unique_users": 12,
      "unique_ips": 8
    }
  }
}
```

### 2. Password Changes

```
GET /api/security/password-changes?days=7
```

**Query Parameters:**
- `days` (optional): Number of days to look back (1-365, default: 7)

**Response:**
```json
{
  "status": "success",
  "data": {
    "changes": [...],
    "summary": {
      "total_changes": 23,
      "unique_users": 18,
      "self_changes": 20,
      "admin_resets": 3
    }
  }
}
```

### 3. Security Overview

```
GET /api/security/overview
```

**Response:**
```json
{
  "status": "success",
  "data": {
    "failed_logins_24h": {...},
    "password_changes_7d": {...},
    "recent_events": [...]
  }
}
```

---

## 🔐 How It Works

### Automatic Tracking

The system automatically logs security events:

#### Failed Login Attempts
- ✅ Invalid login ID
- ✅ Wrong password
- ✅ Deactivated account

#### Password Changes
- ✅ User changes own password
- ✅ Admin resets password
- ✅ Forced password change

### No Additional Code Needed

Security logging is already integrated into:
- `authController.login()` - Tracks failed logins
- `authController.changePassword()` - Tracks password changes

---

## 🎯 Frontend Integration

### Example: Fetch Security Data

```typescript
// Fetch security overview
const response = await fetch('/api/security/overview', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

const data = await response.json();

if (data.status === 'success') {
  // Display in your Security Overview component
  console.log('Failed Logins (24h):', data.data.failed_logins_24h);
  console.log('Password Changes (7d):', data.data.password_changes_7d);
  console.log('Recent Events:', data.data.recent_events);
}
```

### Example: Security Metrics Card

```typescript
interface SecurityMetricsProps {
  data: SecurityOverviewData;
}

const SecurityMetrics: React.FC<SecurityMetricsProps> = ({ data }) => {
  return (
    <div className="security-metrics">
      <div className="metric-card">
        <h3>Failed Logins (24h)</h3>
        <p className="metric-value">{data.failed_logins_24h.total_attempts}</p>
        <p className="metric-detail">
          {data.failed_logins_24h.unique_users} unique users
        </p>
      </div>
      
      <div className="metric-card">
        <h3>Password Changes (7d)</h3>
        <p className="metric-value">{data.password_changes_7d.total_changes}</p>
        <p className="metric-detail">
          {data.password_changes_7d.self_changes} self-initiated
        </p>
      </div>
    </div>
  );
};
```

---

## 🔍 Verifying Setup

### Check Database Tables

```sql
-- Check if tables exist
SHOW TABLES LIKE '%login%';
SHOW TABLES LIKE '%password%';

-- View table structure
DESCRIBE failed_login_attempts;
DESCRIBE password_change_history;

-- Check data
SELECT * FROM failed_login_attempts ORDER BY attempted_at DESC LIMIT 10;
SELECT * FROM password_change_history ORDER BY changed_at DESC LIMIT 10;
```

### Test Failed Login Tracking

1. Try to login with wrong password
2. Check the database:
   ```sql
   SELECT * FROM failed_login_attempts ORDER BY attempted_at DESC LIMIT 1;
   ```
3. Should see a new record with your login attempt

### Test Password Change Tracking

1. Change your password via `/api/auth/change-password`
2. Check the database:
   ```sql
   SELECT * FROM password_change_history ORDER BY changed_at DESC LIMIT 1;
   ```
3. Should see a new record with change_type = 'self'

---

## 📝 Access Control

### Regular Users
- Can view **only their own** security events
- Limited to 100 records per query

### Admins/Super_admins
- Can view **all security events** in their organization
- Limited to 1000 records per query
- Organization-level data isolation

---

## ⚙️ Configuration

### Time Range Limits

**Failed Logins:**
- Minimum: 1 hour
- Maximum: 720 hours (30 days)
- Default: 24 hours

**Password Changes:**
- Minimum: 1 day
- Maximum: 365 days (1 year)
- Default: 7 days

### Query Limits

- Admin queries: 1000 records
- User queries: 100 records

---

## 🛠️ Troubleshooting

### Tables Not Created

**Problem:** Setup script fails or tables don't exist

**Solution:**
```bash
# Check database connection
node -e "require('./src/config/database').testConnection()"

# Manually create tables
mysql -u root -p cms_db < backend/database/create_security_tables.sql
```

### No Data Appearing

**Problem:** API returns empty arrays

**Solutions:**
1. Generate some test data:
   - Try logging in with wrong password (creates failed login)
   - Change your password (creates password change record)

2. Verify tables exist and have data:
   ```sql
   SELECT COUNT(*) FROM failed_login_attempts;
   SELECT COUNT(*) FROM password_change_history;
   ```

3. Check time range parameters are correct

### API Returns 401 Unauthorized

**Problem:** Authentication error

**Solution:**
- Ensure you're sending valid JWT token
- Token format: `Authorization: Bearer <token>`
- Get fresh token by logging in again

### API Returns 400 Bad Request

**Problem:** Invalid parameters

**Solution:**
- Check hours/days parameter is within valid range
- Failed logins: 1-720 hours
- Password changes: 1-365 days

---

## 📚 Documentation

### Full Documentation
- **API Reference:** `SECURITY_API_DOCUMENTATION.md`
- **Implementation Details:** `SECURITY_IMPLEMENTATION_SUMMARY.md`

### File Structure
```
backend/
├── src/
│   ├── controllers/
│   │   ├── securityController.js      # Security API logic
│   │   └── authController.js          # Updated with logging
│   └── routes/
│       └── security.js                # Security routes
├── database/
│   └── create_security_tables.sql     # SQL script
├── setup_security_tables.js           # Setup script
├── test_security_api.js               # Test script
├── SECURITY_API_DOCUMENTATION.md      # Full API docs
├── SECURITY_IMPLEMENTATION_SUMMARY.md # Implementation details
└── SECURITY_API_QUICKSTART.md        # This file
```

---

## ✅ Checklist

Setup complete when you can:

- [x] Run `node setup_security_tables.js` successfully
- [x] Server starts without errors
- [x] Can call all 3 endpoints with valid token
- [x] Failed login attempts are automatically logged
- [x] Password changes are automatically logged
- [x] Data appears in API responses

---

## 🎉 You're Done!

Your Security API is now ready to use. The endpoints will automatically track:
- Failed login attempts ✅
- Password changes ✅

Perfect for the Security Overview dashboard feature!

---

## Need Help?

- Check `SECURITY_API_DOCUMENTATION.md` for detailed API reference
- Check `SECURITY_IMPLEMENTATION_SUMMARY.md` for technical details
- Run `node test_security_api.js` to verify everything works

