# Auth Service API Documentation

## Overview

The Auth Service provides comprehensive authentication and authorization functionality for the Lilith platform. It implements industry-standard security practices including JWT tokens, password hashing, role-based access control (RBAC), and secure session management.

## Base URL

- **Development**: `http://localhost:8081`
- **Staging**: `https://auth.staging.lilith.app`
- **Production**: `https://auth.lilith.app`

## Authentication

Most endpoints require authentication via JWT token in the Authorization header:

```http
Authorization: Bearer <jwt_token>
```

## Health Check

### GET /health

Check service health and status.

**Response**: `200 OK`
```json
{
  "status": "healthy",
  "service": "auth",
  "timestamp": "2025-01-28T12:00:00.000Z",
  "version": "1.0.0",
  "database": "connected",
  "users_count": 1234
}
```

## User Registration

### POST /auth/register

Register a new user account.

**Request Body**:
```json
{
  "email": "user@example.com",
  "password": "SecurePassword123!",
  "name": "John Doe",
  "username": "johndoe"
}
```

**Validation**:
- `email`: Valid email format, unique
- `password`: Minimum 8 characters, contains uppercase, lowercase, number, special character
- `name`: 1-100 characters
- `username`: 3-30 characters, alphanumeric + underscore/dash

**Response**: `201 Created`
```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_1234567890",
      "email": "user@example.com",
      "name": "John Doe",
      "username": "johndoe",
      "verified": false,
      "createdAt": "2025-01-28T12:00:00.000Z",
      "roles": ["user"]
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expiresIn": "1h"
  }
}
```

**Error Responses**:
- `400 Bad Request`: Invalid input data
- `409 Conflict`: Email already exists

## User Login

### POST /auth/login

Authenticate a user and receive access token.

**Request Body**:
```json
{
  "email": "user@example.com",
  "password": "SecurePassword123!"
}
```

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_1234567890",
      "email": "user@example.com",
      "name": "John Doe",
      "username": "johndoe",
      "verified": true,
      "lastLogin": "2025-01-28T12:00:00.000Z",
      "roles": ["user"]
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expiresIn": "1h"
  }
}
```

**Error Responses**:
- `400 Bad Request`: Missing email or password
- `401 Unauthorized`: Invalid credentials
- `423 Locked`: Account temporarily locked

## Token Management

### POST /auth/refresh

Refresh an access token using a refresh token.

**Request Body**:
```json
{
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expiresIn": "1h"
  }
}
```

### POST /auth/logout

Logout and invalidate tokens.

**Headers**: `Authorization: Bearer <token>`

**Response**: `200 OK`
```json
{
  "success": true,
  "message": "Successfully logged out"
}
```

## User Profile Management

### GET /auth/profile

Get current user profile information.

**Headers**: `Authorization: Bearer <token>`

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_1234567890",
      "email": "user@example.com",
      "name": "John Doe",
      "username": "johndoe",
      "verified": true,
      "createdAt": "2025-01-28T12:00:00.000Z",
      "lastLogin": "2025-01-28T12:00:00.000Z",
      "roles": ["user"],
      "preferences": {
        "theme": "dark",
        "notifications": true
      }
    }
  }
}
```

### PUT /auth/profile

Update user profile information.

**Headers**: `Authorization: Bearer <token>`

**Request Body**:
```json
{
  "name": "John Smith",
  "username": "johnsmith",
  "preferences": {
    "theme": "light",
    "notifications": false
  }
}
```

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_1234567890",
      "email": "user@example.com",
      "name": "John Smith",
      "username": "johnsmith",
      "verified": true,
      "updatedAt": "2025-01-28T12:00:00.000Z"
    }
  }
}
```

## Password Management

### PUT /auth/password

Change user password.

**Headers**: `Authorization: Bearer <token>`

**Request Body**:
```json
{
  "currentPassword": "OldPassword123!",
  "newPassword": "NewPassword456!"
}
```

**Response**: `200 OK`
```json
{
  "success": true,
  "message": "Password updated successfully"
}
```

### POST /auth/forgot-password

Request password reset email.

**Request Body**:
```json
{
  "email": "user@example.com"
}
```

**Response**: `200 OK`
```json
{
  "success": true,
  "message": "Password reset email sent"
}
```

### POST /auth/reset-password

Reset password using reset token.

**Request Body**:
```json
{
  "resetToken": "reset_token_123",
  "newPassword": "NewPassword789!"
}
```

**Response**: `200 OK`
```json
{
  "success": true,
  "message": "Password reset successfully"
}
```

## Email Verification

### POST /auth/verify-email

Verify email address using verification token.

**Request Body**:
```json
{
  "verificationToken": "verify_token_456"
}
```

**Response**: `200 OK`
```json
{
  "success": true,
  "message": "Email verified successfully"
}
```

### POST /auth/resend-verification

Resend email verification.

**Headers**: `Authorization: Bearer <token>`

**Response**: `200 OK`
```json
{
  "success": true,
  "message": "Verification email sent"
}
```

## Role-Based Access Control (RBAC)

### GET /auth/roles

Get available roles and permissions.

**Headers**: `Authorization: Bearer <token>` (Admin required)

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "roles": [
      {
        "name": "user",
        "description": "Standard user",
        "permissions": ["read:profile", "update:profile"]
      },
      {
        "name": "moderator",
        "description": "Content moderator",
        "permissions": ["read:content", "moderate:content"]
      },
      {
        "name": "admin",
        "description": "System administrator",
        "permissions": ["*"]
      }
    ]
  }
}
```

### PUT /auth/users/:userId/roles

Update user roles (Admin only).

**Headers**: `Authorization: Bearer <token>` (Admin required)

**Request Body**:
```json
{
  "roles": ["user", "moderator"]
}
```

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "userId": "usr_1234567890",
    "roles": ["user", "moderator"],
    "updatedAt": "2025-01-28T12:00:00.000Z"
  }
}
```

## Session Management

### GET /auth/sessions

Get active user sessions.

**Headers**: `Authorization: Bearer <token>`

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "sessions": [
      {
        "id": "sess_123",
        "deviceType": "desktop",
        "browser": "Chrome",
        "location": "New York, US",
        "lastActive": "2025-01-28T12:00:00.000Z",
        "current": true
      }
    ]
  }
}
```

### DELETE /auth/sessions/:sessionId

Terminate a specific session.

**Headers**: `Authorization: Bearer <token>`

**Response**: `200 OK`
```json
{
  "success": true,
  "message": "Session terminated"
}
```

## User Management (Admin)

### GET /auth/users

List users with filtering and pagination.

**Headers**: `Authorization: Bearer <token>` (Admin required)

**Query Parameters**:
- `page`: Page number (default: 1)
- `limit`: Items per page (default: 20, max: 100)
- `search`: Search by email, name, or username
- `role`: Filter by role
- `verified`: Filter by verification status

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "users": [
      {
        "id": "usr_1234567890",
        "email": "user@example.com",
        "name": "John Doe",
        "username": "johndoe",
        "verified": true,
        "roles": ["user"],
        "createdAt": "2025-01-28T12:00:00.000Z",
        "lastLogin": "2025-01-28T12:00:00.000Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 1234,
      "totalPages": 62
    }
  }
}
```

### GET /auth/users/:userId

Get specific user details.

**Headers**: `Authorization: Bearer <token>` (Admin or own profile)

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_1234567890",
      "email": "user@example.com",
      "name": "John Doe",
      "username": "johndoe",
      "verified": true,
      "roles": ["user"],
      "createdAt": "2025-01-28T12:00:00.000Z",
      "lastLogin": "2025-01-28T12:00:00.000Z",
      "metadata": {}
    }
  }
}
```

### PUT /auth/users/:userId/status

Update user status (Admin only).

**Headers**: `Authorization: Bearer <token>` (Admin required)

**Request Body**:
```json
{
  "status": "active", // active, suspended, banned
  "reason": "Policy violation"
}
```

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "userId": "usr_1234567890",
    "status": "suspended",
    "reason": "Policy violation",
    "updatedAt": "2025-01-28T12:00:00.000Z"
  }
}
```

## API Keys (For Service-to-Service)

### POST /auth/api-keys

Create API key for service authentication.

**Headers**: `Authorization: Bearer <token>` (Admin required)

**Request Body**:
```json
{
  "name": "Content Service API Key",
  "scopes": ["read:users", "update:users"],
  "expiresAt": "2025-12-31T23:59:59.000Z"
}
```

**Response**: `201 Created`
```json
{
  "success": true,
  "data": {
    "id": "key_123456",
    "name": "Content Service API Key",
    "key": "sk_live_abc123def456...",
    "scopes": ["read:users", "update:users"],
    "expiresAt": "2025-12-31T23:59:59.000Z",
    "createdAt": "2025-01-28T12:00:00.000Z"
  }
}
```

### GET /auth/api-keys

List API keys.

**Headers**: `Authorization: Bearer <token>` (Admin required)

**Response**: `200 OK`
```json
{
  "success": true,
  "data": {
    "apiKeys": [
      {
        "id": "key_123456",
        "name": "Content Service API Key",
        "scopes": ["read:users", "update:users"],
        "lastUsed": "2025-01-28T11:00:00.000Z",
        "expiresAt": "2025-12-31T23:59:59.000Z"
      }
    ]
  }
}
```

## Error Responses

All error responses follow this format:

```json
{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": "Additional error context"
  }
}
```

### Common Error Codes

- `VALIDATION_ERROR`: Invalid input data
- `UNAUTHORIZED`: Authentication required
- `FORBIDDEN`: Insufficient permissions
- `NOT_FOUND`: Resource not found
- `CONFLICT`: Resource already exists
- `RATE_LIMITED`: Too many requests
- `SERVER_ERROR`: Internal server error

## Rate Limiting

The API implements rate limiting to prevent abuse:

- **Registration**: 5 attempts per hour per IP
- **Login**: 10 attempts per 15 minutes per IP
- **Password Reset**: 3 attempts per hour per email
- **General API**: 1000 requests per hour per authenticated user

Rate limit headers are included in responses:
- `X-RateLimit-Limit`: Request limit
- `X-RateLimit-Remaining`: Remaining requests
- `X-RateLimit-Reset`: Reset timestamp

## Security Features

### Password Security
- BCrypt hashing with salt rounds: 12
- Password strength requirements enforced
- Password history to prevent reuse

### Token Security
- JWT tokens with RS256 signing
- Short-lived access tokens (1 hour)
- Secure refresh token rotation
- Token blacklisting on logout

### Account Security
- Failed login attempt tracking
- Account lockout after 5 failed attempts
- IP-based suspicious activity detection
- Email notifications for security events

### Data Protection
- Input validation and sanitization
- SQL injection prevention
- XSS protection
- CORS configuration
- Secure headers

## Integration Examples

### cURL Examples

**Register User**:
```bash
curl -X POST https://auth.lilith.app/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePassword123!",
    "name": "John Doe"
  }'
```

**Login**:
```bash
curl -X POST https://auth.lilith.app/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePassword123!"
  }'
```

**Get Profile**:
```bash
curl -X GET https://auth.lilith.app/auth/profile \
  -H "Authorization: Bearer <token>"
```

### JavaScript SDK

```javascript
import { AuthService } from '@lilith/sdk';

const auth = new AuthService({
  baseUrl: 'https://auth.lilith.app'
});

// Register
const { user, token } = await auth.register({
  email: 'user@example.com',
  password: 'SecurePassword123!',
  name: 'John Doe'
});

// Login
const { user, token } = await auth.login({
  email: 'user@example.com',
  password: 'SecurePassword123!'
});

// Get profile
const profile = await auth.getProfile(token);
```

## Support

For API support or questions:
- Documentation: https://docs.lilith.app/auth
- Support: support@lilith.app
- Status: https://status.lilith.app

---

**Last Updated**: 2025-01-28
**API Version**: 1.0.0