# Backend API Documentation

## Overview

The serdark.digital backend is a secure, production-ready Express.js API built with:
- **Authentication**: JWT tokens with refresh capability
- **Security**: Password hashing, CSRF protection, rate limiting, audit logging
- **Validation**: Input validation on all endpoints
- **Modern Stack**: Node.js v18+, PostgreSQL, async/await, ES6 modules

## Base URL

```
Development: http://localhost:5000/api/v1
Production: https://api.serdark.digital/api/v1
```

## Response Format

All responses use JSON format:

```json
{
  "success": true,
  "message": "Operation successful",
  "data": {}
}
```

Error responses:

```json
{
  "success": false,
  "error": {
    "type": "ERROR_TYPE",
    "message": "Error description",
    "timestamp": "2024-01-30T10:00:00.000Z"
  }
}
```

## Authentication

### Bearer Token

Include JWT in Authorization header:

```
Authorization: Bearer YOUR_ACCESS_TOKEN
```

If token expires, use the refresh endpoint to get a new one.

### CSRF Protection

For state-changing requests (POST, PUT, DELETE), include:

```
X-CSRF-Token: your-csrf-token
```

Get CSRF token from response headers (`X-CSRF-Token`) after login or any GET request.

## Rate Limiting

Rate limits by endpoint:

| Endpoint | Limit | Window |
|----------|-------|--------|
| `/auth/login` | 5 | 15 minutes |
| `/auth/register` | 3 | 1 hour |
| `/payment/*` | 10 | 1 hour |
| `/upload` | 20 | 1 day |
| General API | 100 | 1 minute |

Rate limit info in response headers:

```
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 2
X-RateLimit-Reset: 1675000000
```

If rate limited (HTTP 429):

```
Retry-After: 120
``````

## Endpoints

### Authentication

#### Register User

```http
POST /auth/register
Content-Type: application/json

{
  "firstName": "John",
  "lastName": "Doe",
  "email": "john@example.com",
  "phone": "+1234567890",
  "password": "SecurePassword123!@#",
  "passwordConfirm": "SecurePassword123!@#",
  "termsAccepted": true
}
```

**Response (201)**:
```json
{
  "success": true,
  "message": "User registered successfully",
  "user": {
    "id": 1,
    "uuid": "uuid-here",
    "email": "john@example.com",
    "firstName": "John",
    "lastName": "Doe",
    "role": "user",
    "createdAt": "2024-01-30T10:00:00Z"
  }
}
```

#### Login

```http
POST /auth/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "SecurePassword123!@#",
  "rememberMe": true
}
```

**Response (200)**:
```json
{
  "success": true,
  "message": "Login successful",
  "accessToken": "eyJhbGc...",
  "refreshToken": "eyJhbGc...",
  "expiresIn": "24h",
  "user": {
    "id": 1,
    "email": "john@example.com",
    "firstName": "John",
    "role": "user"
  }
}
```

**If 2FA Enabled (200)**:
```json
{
  "success": true,
  "message": "2FA verification required",
  "requiresTwoFA": true,
  "tempToken": "eyJhbGc...",
  "user": {
    "id": 1,
    "email": "john@example.com"
  }
}
```

#### Logout

```http
POST /auth/logout
Authorization: Bearer YOUR_ACCESS_TOKEN
```

**Response (200)**:
```json
{
  "success": true,
  "message": "Logged out successfully"
}
```

#### Refresh Token

```http
POST /auth/refresh
Content-Type: application/json

{
  "refreshToken": "eyJhbGc..."
}
```

**Response (200)**:
```json
{
  "success": true,
  "message": "Token refreshed",
  "accessToken": "eyJhbGc...",
  "expiresIn": "24h"
}
```

#### Request Password Reset

```http
POST /auth/password-reset
Content-Type: application/json

{
  "email": "john@example.com"
}
```

**Response (200)**:
```json
{
  "success": true,
  "message": "If an account exists, a reset link has been sent to your email"
}
```

#### Reset Password

```http
POST /auth/password-reset-confirm
Content-Type: application/json

{
  "token": "reset-token-from-email",
  "newPassword": "NewPassword123!@#",
  "confirmPassword": "NewPassword123!@#"
}
```

**Response (200)**:
```json
{
  "success": true,
  "message": "Password reset successfully"
}
```

#### Change Password

```http
POST /auth/change-password
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json

{
  "currentPassword": "OldPassword123!@#",
  "newPassword": "NewPassword123!@#"
}
```

**Response (200)**:
```json
{
  "success": true,
  "message": "Password changed successfully"
}
```

### 2FA Endpoints

#### Generate 2FA Secret

```http
POST /auth/2fa/generate
Authorization: Bearer YOUR_ACCESS_TOKEN
```

**Response (200)**:
```json
{
  "success": true,
  "message": "2FA secret generated",
  "secret": "JBSWY3DPEBLW64TMMQ......",
  "qrCode": "data:image/png;base64,...",
  "manualEntryKey": "JBSWY3DPEBLW64TMMQ......",
  "backupCodes": ["ABC12345", "DEF67890", ...],
  "warning": "Save these backup codes..."
}
```

#### Enable 2FA

```http
POST /auth/2fa/enable
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json

{
  "secret": "JBSWY3DPEBLW64TMMQ......",
  "code": "123456",
  "backupCodes": ["ABC12345", "DEF67890", ...],
  "password": "YourPassword123!@#"
}
```

**Response (200)**:
```json
{
  "success": true,
  "message": "2FA enabled successfully"
}
```

#### Verify 2FA Code

```http
POST /auth/2fa/verify
Content-Type: application/json

{
  "code": "123456"
}
```

**Response (200)**:
```json
{
  "success": true,
  "message": "2FA verification successful",
  "accessToken": "eyJhbGc..."
}
```

#### Get 2FA Status

```http
GET /auth/2fa/status
Authorization: Bearer YOUR_ACCESS_TOKEN
```

**Response (200)**:
```json
{
  "success": true,
  "twoFAEnabled": true,
  "backupCodesCount": 8,
  "warningLowBackupCodes": false
}
```

### User Endpoints

#### Get Own Profile

```http
GET /users/me
Authorization: Bearer YOUR_ACCESS_TOKEN
```

**Response (200)**:
```json
{
  "success": true,
  "user": {
    "id": 1,
    "uuid": "uuid-here",
    "email": "john@example.com",
    "firstName": "John",
    "lastName": "Doe",
    "phone": "+1234567890",
    "role": "user",
    "isActive": true,
    "twoFAEnabled": true,
    "bio": "Music lover",
    "preferences": {},
    "lastLogin": "2024-01-30T10:00:00Z",
    "createdAt": "2024-01-25T10:00:00Z"
  }
}
```

#### Update Profile

```http
PATCH /users/me/profile
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json

{
  "firstName": "Jane",
  "lastName": "Doe",
  "bio": "New bio",
  "profilePicture": "https://example.com/pic.jpg"
}
```

**Response (200)**:
```json
{
  "success": true,
  "message": "Profile updated successfully",
  "user": {
    "id": 1,
    "email": "john@example.com",
    "firstName": "Jane",
    ...
  }
}
```

#### Get Sessions

```http
GET /users/me/sessions
Authorization: Bearer YOUR_ACCESS_TOKEN
```

**Response (200)**:
```json
{
  "success": true,
  "sessions": [
    {
      "session_id": "uuid",
      "ip_address": "192.168.1.1",
      "user_agent": "Mozilla/5.0...",
      "created_at": "2024-01-30T10:00:00Z",
      "expires_at": "2024-02-06T10:00:00Z"
    }
  ]
}
```

#### Delete Account

```http
DELETE /users/me/account
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json

{
  "password": "YourPassword123!@#"
}
```

**Response (200)**:
```json
{
  "success": true,
  "message": "Account deleted successfully"
}
```

### Audit Endpoints

#### Get My Audit Logs

```http
GET /audit/my?page=1&limit=20
Authorization: Bearer YOUR_ACCESS_TOKEN
```

**Response (200)**:
```json
{
  "success": true,
  "logs": [
    {
      "event_type": "USER_LOGIN",
      "action": "login_success",
      "ip_address": "192.168.1.1",
      "created_at": "2024-01-30T10:00:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20
  }
}
```

#### Get All Audit Logs (Admin)

```http
GET /audit?page=1&limit=50&eventType=USER_LOGIN&severity=info
Authorization: Bearer YOUR_ADMIN_TOKEN
```

**Response (200)**:
```json
{
  "success": true,
  "logs": [...],
  "pagination": {
    "page": 1,
    "limit": 50,
    "total": 1234,
    "pages": 25
  }
}
```

## Error Codes

| Code | Description |
|------|-------------|
| 400 | Bad Request - Validation failed |
| 401 | Unauthorized - Invalid/expired token |
| 403 | Forbidden - Insufficient permissions |
| 404 | Not Found - Resource doesn't exist |
| 409 | Conflict - Resource already exists |
| 429 | Rate Limited - Too many requests |
| 500 | Internal Server Error |

## Example Workflow

### 1. Register
```bash
curl -X POST http://localhost:5000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com",
    "password": "SecurePassword123!@#",
    "passwordConfirm": "SecurePassword123!@#",
    "termsAccepted": true
  }'
```

### 2. Login
```bash
curl -X POST http://localhost:5000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "SecurePassword123!@#"
  }'
```

### 3. Use Access Token
```bash
curl -X GET http://localhost:5000/api/v1/users/me \
  -H "Authorization: Bearer eyJhbGc..."
```

### 4. Refresh Token (if expired)
```bash
curl -X POST http://localhost:5000/api/v1/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{"refreshToken": "eyJhbGc..."}'
```

## Frontend Integration

See frontend documentation for integration examples with React and security best practices.
