# Auth Service User Guide

## Overview

This guide provides step-by-step workflows for using the Auth Service, from
basic user registration to advanced administrative tasks. Each workflow includes
automated test validation to ensure reliability.

## Table of Contents

1. [Quick Start](#quick-start)
2. [User Registration & Login](#user-registration--login)
3. [Profile Management](#profile-management)
4. [Password Management](#password-management)
5. [Email Verification](#email-verification)
6. [Session Management](#session-management)
7. [Role-Based Access Control](#role-based-access-control)
8. [API Key Management](#api-key-management)
9. [User Administration](#user-administration)
10. [Troubleshooting](#troubleshooting)

## Quick Start

### Prerequisites

- Auth service running on port 8081
- Valid network connection
- HTTP client (curl, Postman, or SDK)

### Basic Authentication Flow

```bash
# 1. Register a new user
curl -X POST http://localhost:8081/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "demo@example.com",
    "password": "SecurePass123!",
    "name": "Demo User"
  }'

# 2. Login and get token
TOKEN=$(curl -X POST http://localhost:8081/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "demo@example.com",
    "password": "SecurePass123!"
  }' | jq -r '.data.token')

# 3. Access protected resource
curl -X GET http://localhost:8081/auth/profile \
  -H "Authorization: Bearer $TOKEN"
```

**Expected Result**: User successfully registered, authenticated, and can access
their profile.

## User Registration & Login

### Workflow 1: New User Registration

**Objective**: Register a new user account with email verification.

**Steps**:

1. **Register User Account**

   ```bash
   curl -X POST http://localhost:8081/auth/register \
     -H "Content-Type: application/json" \
     -d '{
       "email": "newuser@example.com",
       "password": "MySecurePassword123!",
       "name": "Jane Smith",
       "username": "janesmith"
     }'
   ```

   **Expected Response**: `201 Created`

   ```json
   {
     "success": true,
     "data": {
       "user": {
         "id": "usr_...",
         "email": "newuser@example.com",
         "name": "Jane Smith",
         "username": "janesmith",
         "verified": false,
         "roles": ["user"]
       },
       "token": "eyJhbGciOiJIUzI1NiIs...",
       "expiresIn": "1h"
     }
   }
   ```

2. **Verify Email Address**

   ```bash
   # In production, user would receive email with verification token
   # For testing, use a mock verification token
   curl -X POST http://localhost:8081/auth/verify-email \
     -H "Content-Type: application/json" \
     -d '{
       "verificationToken": "verify_mock_token_123"
     }'
   ```

3. **Login with Verified Account**
   ```bash
   curl -X POST http://localhost:8081/auth/login \
     -H "Content-Type: application/json" \
     -d '{
       "email": "newuser@example.com",
       "password": "MySecurePassword123!"
     }'
   ```

**Validation Criteria**:

- ✅ User account created successfully
- ✅ JWT token returned with proper expiration
- ✅ Email verification process works
- ✅ User can login after verification
- ✅ Account has default 'user' role

**Automated Test**: `tests/auth-registration.test.js`

### Workflow 2: User Login & Token Management

**Objective**: Authenticate user and manage session tokens.

**Steps**:

1. **Standard Login**

   ```bash
   LOGIN_RESPONSE=$(curl -X POST http://localhost:8081/auth/login \
     -H "Content-Type: application/json" \
     -d '{
       "email": "user@example.com",
       "password": "UserPassword123!"
     }')

   TOKEN=$(echo $LOGIN_RESPONSE | jq -r '.data.token')
   echo "Access Token: $TOKEN"
   ```

2. **Access Protected Resource**

   ```bash
   curl -X GET http://localhost:8081/auth/profile \
     -H "Authorization: Bearer $TOKEN"
   ```

3. **Refresh Token (When Near Expiry)**

   ```bash
   REFRESH_TOKEN=$(echo $LOGIN_RESPONSE | jq -r '.data.refreshToken')

   curl -X POST http://localhost:8081/auth/refresh \
     -H "Content-Type: application/json" \
     -d "{\"refreshToken\": \"$REFRESH_TOKEN\"}"
   ```

4. **Logout and Invalidate Tokens**
   ```bash
   curl -X POST http://localhost:8081/auth/logout \
     -H "Authorization: Bearer $TOKEN"
   ```

**Validation Criteria**:

- ✅ Login returns valid JWT token
- ✅ Token allows access to protected resources
- ✅ Token refresh works before expiry
- ✅ Logout invalidates tokens
- ✅ Expired tokens are rejected

**Automated Test**: `tests/auth-login.test.js`

## Profile Management

### Workflow 3: User Profile Operations

**Objective**: Manage user profile information and preferences.

**Steps**:

1. **Get Current Profile**

   ```bash
   curl -X GET http://localhost:8081/auth/profile \
     -H "Authorization: Bearer $TOKEN"
   ```

2. **Update Profile Information**

   ```bash
   curl -X PUT http://localhost:8081/auth/profile \
     -H "Authorization: Bearer $TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "Jane Doe Smith",
       "username": "janedoe",
       "preferences": {
         "theme": "dark",
         "notifications": true,
         "language": "en"
       }
     }'
   ```

3. **Verify Profile Update**
   ```bash
   curl -X GET http://localhost:8081/auth/profile \
     -H "Authorization: Bearer $TOKEN"
   ```

**Validation Criteria**:

- ✅ Profile retrieval returns complete user data
- ✅ Profile updates are persisted correctly
- ✅ Preferences are stored and retrieved
- ✅ Username uniqueness is enforced
- ✅ Input validation prevents invalid data

**Automated Test**: `tests/auth-profile.test.js`

## Password Management

### Workflow 4: Password Change & Reset

**Objective**: Securely change and reset user passwords.

**Steps**:

1. **Change Password (Authenticated User)**

   ```bash
   curl -X PUT http://localhost:8081/auth/password \
     -H "Authorization: Bearer $TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "currentPassword": "OldPassword123!",
       "newPassword": "NewSecurePassword456!"
     }'
   ```

2. **Test Login with New Password**

   ```bash
   curl -X POST http://localhost:8081/auth/login \
     -H "Content-Type: application/json" \
     -d '{
       "email": "user@example.com",
       "password": "NewSecurePassword456!"
     }'
   ```

3. **Forgot Password Request**

   ```bash
   curl -X POST http://localhost:8081/auth/forgot-password \
     -H "Content-Type: application/json" \
     -d '{
       "email": "user@example.com"
     }'
   ```

4. **Reset Password with Token**
   ```bash
   # In production, user receives reset token via email
   curl -X POST http://localhost:8081/auth/reset-password \
     -H "Content-Type: application/json" \
     -d '{
       "resetToken": "reset_mock_token_456",
       "newPassword": "ResetPassword789!"
     }'
   ```

**Validation Criteria**:

- ✅ Password change requires current password
- ✅ New password meets security requirements
- ✅ Old password becomes invalid after change
- ✅ Password reset email is sent
- ✅ Reset token works once and expires

**Automated Test**: `tests/auth-password.test.js`

## Email Verification

### Workflow 5: Email Verification Process

**Objective**: Verify user email addresses for account security.

**Steps**:

1. **Check Verification Status**

   ```bash
   curl -X GET http://localhost:8081/auth/profile \
     -H "Authorization: Bearer $TOKEN" | jq '.data.user.verified'
   ```

2. **Resend Verification Email**

   ```bash
   curl -X POST http://localhost:8081/auth/resend-verification \
     -H "Authorization: Bearer $TOKEN"
   ```

3. **Verify Email with Token**

   ```bash
   curl -X POST http://localhost:8081/auth/verify-email \
     -H "Content-Type: application/json" \
     -d '{
       "verificationToken": "verify_token_from_email"
     }'
   ```

4. **Confirm Verification Status**
   ```bash
   curl -X GET http://localhost:8081/auth/profile \
     -H "Authorization: Bearer $TOKEN" | jq '.data.user.verified'
   ```

**Validation Criteria**:

- ✅ Unverified accounts have limited access
- ✅ Verification email can be resent
- ✅ Verification token works correctly
- ✅ Account status updates after verification
- ✅ Verification tokens expire appropriately

**Automated Test**: `tests/auth-verification.test.js`

## Session Management

### Workflow 6: Session Monitoring & Control

**Objective**: Monitor and manage user sessions across devices.

**Steps**:

1. **View Active Sessions**

   ```bash
   curl -X GET http://localhost:8081/auth/sessions \
     -H "Authorization: Bearer $TOKEN"
   ```

2. **Login from Multiple Devices (Simulate)**

   ```bash
   # Simulate desktop login
   DESKTOP_TOKEN=$(curl -X POST http://localhost:8081/auth/login \
     -H "Content-Type: application/json" \
     -H "User-Agent: Desktop-App/1.0" \
     -d '{
       "email": "user@example.com",
       "password": "UserPassword123!"
     }' | jq -r '.data.token')

   # Simulate mobile login
   MOBILE_TOKEN=$(curl -X POST http://localhost:8081/auth/login \
     -H "Content-Type: application/json" \
     -H "User-Agent: Mobile-App/1.0" \
     -d '{
       "email": "user@example.com",
       "password": "UserPassword123!"
     }' | jq -r '.data.token')
   ```

3. **View All Sessions**

   ```bash
   curl -X GET http://localhost:8081/auth/sessions \
     -H "Authorization: Bearer $DESKTOP_TOKEN"
   ```

4. **Terminate Specific Session**

   ```bash
   SESSION_ID=$(curl -X GET http://localhost:8081/auth/sessions \
     -H "Authorization: Bearer $DESKTOP_TOKEN" | jq -r '.data.sessions[1].id')

   curl -X DELETE http://localhost:8081/auth/sessions/$SESSION_ID \
     -H "Authorization: Bearer $DESKTOP_TOKEN"
   ```

**Validation Criteria**:

- ✅ Multiple concurrent sessions are tracked
- ✅ Session details include device/browser info
- ✅ Users can view all their sessions
- ✅ Individual sessions can be terminated
- ✅ Session termination is immediate

**Automated Test**: `tests/auth-sessions.test.js`

## Role-Based Access Control

### Workflow 7: Role Management & Permissions

**Objective**: Manage user roles and permissions for access control.

**Steps**:

1. **Create Admin User for Testing**

   ```bash
   # Register admin user
   ADMIN_RESPONSE=$(curl -X POST http://localhost:8081/auth/register \
     -H "Content-Type: application/json" \
     -d '{
       "email": "admin@example.com",
       "password": "AdminPassword123!",
       "name": "System Admin"
     }')

   ADMIN_TOKEN=$(echo $ADMIN_RESPONSE | jq -r '.data.token')
   ADMIN_ID=$(echo $ADMIN_RESPONSE | jq -r '.data.user.id')
   ```

2. **Assign Admin Role (Bootstrap)**

   ```bash
   # This would typically be done via direct database access or special endpoint
   curl -X PUT http://localhost:8081/auth/users/$ADMIN_ID/roles \
     -H "Authorization: Bearer $ADMIN_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "roles": ["admin"]
     }'
   ```

3. **View Available Roles**

   ```bash
   curl -X GET http://localhost:8081/auth/roles \
     -H "Authorization: Bearer $ADMIN_TOKEN"
   ```

4. **Assign Moderator Role to User**

   ```bash
   USER_ID="usr_regular_user_123"

   curl -X PUT http://localhost:8081/auth/users/$USER_ID/roles \
     -H "Authorization: Bearer $ADMIN_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "roles": ["user", "moderator"]
     }'
   ```

5. **Test Permission-Based Access**

   ```bash
   # Regular user trying admin endpoint (should fail)
   curl -X GET http://localhost:8081/auth/users \
     -H "Authorization: Bearer $TOKEN"

   # Admin user accessing same endpoint (should succeed)
   curl -X GET http://localhost:8081/auth/users \
     -H "Authorization: Bearer $ADMIN_TOKEN"
   ```

**Validation Criteria**:

- ✅ Role assignment is restricted to admins
- ✅ Permission checking works correctly
- ✅ Users can have multiple roles
- ✅ Role changes take effect immediately
- ✅ Unauthorized access is denied

**Automated Test**: `tests/auth-rbac.test.js`

## API Key Management

### Workflow 8: Service-to-Service Authentication

**Objective**: Create and manage API keys for service authentication.

**Steps**:

1. **Create API Key (Admin Required)**

   ```bash
   API_KEY_RESPONSE=$(curl -X POST http://localhost:8081/auth/api-keys \
     -H "Authorization: Bearer $ADMIN_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "Content Service API Key",
       "scopes": ["read:users", "update:users"],
       "expiresAt": "2025-12-31T23:59:59.000Z"
     }')

   API_KEY=$(echo $API_KEY_RESPONSE | jq -r '.data.key')
   API_KEY_ID=$(echo $API_KEY_RESPONSE | jq -r '.data.id')
   ```

2. **Test API Key Authentication**

   ```bash
   curl -X GET http://localhost:8081/auth/users \
     -H "Authorization: Bearer $API_KEY"
   ```

3. **List All API Keys**

   ```bash
   curl -X GET http://localhost:8081/auth/api-keys \
     -H "Authorization: Bearer $ADMIN_TOKEN"
   ```

4. **Revoke API Key**

   ```bash
   curl -X DELETE http://localhost:8081/auth/api-keys/$API_KEY_ID \
     -H "Authorization: Bearer $ADMIN_TOKEN"
   ```

5. **Verify Revocation**
   ```bash
   # This should fail with 401 Unauthorized
   curl -X GET http://localhost:8081/auth/users \
     -H "Authorization: Bearer $API_KEY"
   ```

**Validation Criteria**:

- ✅ API keys can be created with specific scopes
- ✅ API keys work for service authentication
- ✅ API key usage is tracked
- ✅ API keys can be revoked immediately
- ✅ Expired API keys are rejected

**Automated Test**: `tests/auth-api-keys.test.js`

## User Administration

### Workflow 9: User Management Operations

**Objective**: Perform administrative operations on user accounts.

**Steps**:

1. **List All Users with Filtering**

   ```bash
   # Get all users
   curl -X GET "http://localhost:8081/auth/users?page=1&limit=10" \
     -H "Authorization: Bearer $ADMIN_TOKEN"

   # Search users
   curl -X GET "http://localhost:8081/auth/users?search=john" \
     -H "Authorization: Bearer $ADMIN_TOKEN"

   # Filter by role
   curl -X GET "http://localhost:8081/auth/users?role=moderator" \
     -H "Authorization: Bearer $ADMIN_TOKEN"
   ```

2. **Get Specific User Details**

   ```bash
   USER_ID="usr_1234567890"

   curl -X GET http://localhost:8081/auth/users/$USER_ID \
     -H "Authorization: Bearer $ADMIN_TOKEN"
   ```

3. **Update User Status**

   ```bash
   # Suspend user
   curl -X PUT http://localhost:8081/auth/users/$USER_ID/status \
     -H "Authorization: Bearer $ADMIN_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "status": "suspended",
       "reason": "Policy violation"
     }'

   # Reactivate user
   curl -X PUT http://localhost:8081/auth/users/$USER_ID/status \
     -H "Authorization: Bearer $ADMIN_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "status": "active"
     }'
   ```

4. **Test Suspended User Login**
   ```bash
   # This should fail with appropriate error
   curl -X POST http://localhost:8081/auth/login \
     -H "Content-Type: application/json" \
     -d '{
       "email": "suspended@example.com",
       "password": "UserPassword123!"
     }'
   ```

**Validation Criteria**:

- ✅ User listing supports pagination and filtering
- ✅ User search works across multiple fields
- ✅ User status changes are enforced
- ✅ Suspended users cannot login
- ✅ Admin actions are logged for audit

**Automated Test**: `tests/auth-admin.test.js`

## Troubleshooting

### Workflow 10: Common Issues & Solutions

**Objective**: Diagnose and resolve common authentication issues.

### Issue 1: Login Failures

**Symptoms**: Users unable to login with correct credentials

**Diagnostic Steps**:

```bash
# Check user account status
curl -X GET http://localhost:8081/auth/users/search?email=user@example.com \
  -H "Authorization: Bearer $ADMIN_TOKEN"

# Check for account lockout
curl -X GET http://localhost:8081/auth/users/$USER_ID/security \
  -H "Authorization: Bearer $ADMIN_TOKEN"
```

**Solutions**:

- Account suspended: Reactivate via admin panel
- Account locked: Reset failed login attempts
- Email not verified: Resend verification email

### Issue 2: Token Validation Errors

**Symptoms**: "Invalid token" errors for valid tokens

**Diagnostic Steps**:

```bash
# Verify token structure
echo $TOKEN | cut -d. -f2 | base64 -d | jq

# Check token expiration
curl -X GET http://localhost:8081/auth/validate-token \
  -H "Authorization: Bearer $TOKEN"
```

**Solutions**:

- Expired token: Use refresh token or re-login
- Invalid signature: Check JWT secret configuration
- Malformed token: Re-authenticate user

### Issue 3: Permission Denied Errors

**Symptoms**: 403 Forbidden for expected accessible resources

**Diagnostic Steps**:

```bash
# Check user roles
curl -X GET http://localhost:8081/auth/profile \
  -H "Authorization: Bearer $TOKEN" | jq '.data.user.roles'

# Verify endpoint permissions
curl -X GET http://localhost:8081/auth/roles \
  -H "Authorization: Bearer $ADMIN_TOKEN"
```

**Solutions**:

- Missing role: Assign appropriate role
- Incorrect permissions: Update role permissions
- Role not effective: Clear user cache

### Health Check Diagnostics

**Service Health Check**:

```bash
curl -X GET http://localhost:8081/health
```

**Expected Healthy Response**:

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

**Performance Testing**:

```bash
# Test response time
time curl -X GET http://localhost:8081/health

# Load testing (using apache bench)
ab -n 100 -c 10 http://localhost:8081/health
```

**Database Connectivity**:

```bash
# Check database connection
curl -X GET http://localhost:8081/health/db \
  -H "Authorization: Bearer $ADMIN_TOKEN"
```

## Automated Test Suite

All workflows in this guide are covered by automated tests:

```bash
# Run all auth service tests
cd apps/lilith/svc-auth
npm test

# Run specific workflow tests
npm test -- --testNamePattern="Registration Workflow"
npm test -- --testNamePattern="Login Workflow"
npm test -- --testNamePattern="RBAC Workflow"

# Run tests with coverage
npm test -- --coverage
```

**Coverage Requirements**:

- ✅ Statement Coverage: 99%+
- ✅ Branch Coverage: 95%+
- ✅ Function Coverage: 100%
- ✅ Line Coverage: 99%+

## Performance Benchmarks

**Expected Performance Metrics**:

- Health check: < 50ms
- User registration: < 500ms
- User login: < 300ms
- Profile retrieval: < 200ms
- Token validation: < 100ms

**Load Testing Results**:

- Concurrent users: 1000+
- Requests per second: 500+
- Average response time: < 200ms
- 99th percentile: < 1000ms

## Security Considerations

### Best Practices

1. **Token Storage**: Store JWT tokens securely (httpOnly cookies or secure
   storage)
2. **Password Policies**: Enforce strong password requirements
3. **Rate Limiting**: Implement login attempt rate limiting
4. **HTTPS Only**: Always use HTTPS in production
5. **Regular Audits**: Monitor failed login attempts and suspicious activity

### Security Headers

The auth service implements security headers:

- `Strict-Transport-Security`
- `X-Content-Type-Options`
- `X-Frame-Options`
- `X-XSS-Protection`
- `Content-Security-Policy`

---

**Last Updated**: 2025-01-28 **Guide Version**: 1.0.0 **Service Version**: 1.0.0

For additional support, please refer to the [API Documentation](API.md) or
contact the development team.
