# Dynamic User Management - Secure OTP System

## Overview

This document describes the secure OTP (One-Time Password) system implemented for dynamic user management operations. The system replaces the legacy OTP mechanism that had security vulnerabilities with a cryptographically secure, rate-limited, and session-based approach.

## Security Improvements

### Before (Legacy System)
- ❌ OTP secret exposed in frontend JavaScript
- ❌ Predictable OTP generation using jsOTP library
- ❌ No rate limiting
- ❌ No CSRF protection
- ❌ Sensitive data in URLs
- ❌ No session validation

### After (Secure System)
- ✅ Server-side cryptographically secure OTP generation
- ✅ Session token management
- ✅ Rate limiting (3 requests per hour per phone)
- ✅ CSRF protection on all endpoints
- ✅ Sensitive data moved to POST requests
- ✅ Session validation and cleanup

## API Endpoints

### Session Management
- `POST /dynamic/user/session/generate` - Generate session token
- `POST /dynamic/user/session/cleanup` - Cleanup session token

### OTP Operations
- `POST /dynamic/user/otp/send` - Send secure OTP
- `POST /dynamic/user/otp/verify` - Verify secure OTP

### Secure Actions
- `POST /dynamic/user/create/secure` - Create user with OTP verification
- `POST /dynamic/user/edit/secure/{id}` - Edit user with OTP verification
- `POST /dynamic/user/delete/secure/{id}` - Delete user with OTP verification
- `POST /dynamic/user/lock/secure/{id}` - Lock/Unlock user with OTP verification
- `POST /dynamic/user/password/send-link/secure/{id}` - Send reset link with OTP verification

## Frontend Integration

### JavaScript Flow
1. **Generate Session**: Create session token for the action
2. **Send OTP**: Request OTP via SMS
3. **Verify OTP**: User enters OTP, verify on server
4. **Execute Action**: Perform the requested action
5. **Cleanup**: Clean up session token

### Example Usage
```javascript
// Generate session for delete action
$.ajax({
    url: '/dynamic/user/session/generate',
    method: 'POST',
    data: {
        action: 'delete',
        _token: csrfToken
    },
    success: function(response) {
        if (response.success) {
            // Send OTP
            sendOTP(response.session_token, 'delete');
        }
    }
});
```

## Backward Compatibility

The legacy OTP routes are still available but deprecated:
- `GET /dynamic/user/create/{otp}`
- `GET /dynamic/user/edit/{id}/{otp}`
- `GET /dynamic/user/delete/{id}/{otp}`
- `GET /dynamic/user/lock/{id}/{otp}`
- `GET /dynamic/user/password/send-link/{id}/{otp}`

## Security Features

### Rate Limiting
- Maximum 3 OTP requests per hour per phone number
- Rate limit window: 60 minutes
- Automatic cleanup of expired rate limit data

### Session Management
- Session tokens are 64-character random strings
- Sessions expire after 24 hours
- Automatic cleanup on page unload

### OTP Security
- 6-digit cryptographically secure random numbers
- 5-minute expiration
- Single-use (consumed after verification)

### CSRF Protection
- All endpoints require CSRF tokens
- Automatic token validation

## Error Handling

### Common Error Responses
```json
{
    "success": false,
    "message": "Rate limit exceeded. Please try again later."
}
```

```json
{
    "success": false,
    "message": "Invalid session token"
}
```

```json
{
    "success": false,
    "message": "Invalid OTP"
}
```

## Migration Guide

### For Developers
1. Replace legacy OTP calls with new secure endpoints
2. Update frontend JavaScript to use session-based flow
3. Remove jsOTP library dependency
4. Update error handling for new response format

### For Users
- No changes required for end users
- Same user experience with improved security
- Better error messages and retry mechanisms

## Configuration

### Rate Limiting
- Default: 3 attempts per hour
- Configurable in OTPService class

### OTP Expiration
- Default: 5 minutes
- Configurable in OTPService class

### Session Expiration
- Default: 24 hours
- Configurable in OTPService class

## Monitoring

### Logging
- All OTP operations are logged
- Rate limit violations are tracked
- Session creation and cleanup events

### Metrics
- OTP success/failure rates
- Rate limit hit counts
- Session usage patterns

## Troubleshooting

### Common Issues
1. **Rate limit exceeded**: Wait for rate limit window to expire
2. **Invalid session**: Generate new session token
3. **OTP expired**: Request new OTP
4. **CSRF token missing**: Ensure CSRF token is included in requests

### Debug Mode
Enable debug logging in OTPService for detailed troubleshooting information.
