# MbetterClient API Authentication Documentation

## Overview

The MbetterClient web dashboard implements a comprehensive authentication system that supports multiple authentication methods and role-based access control. This document outlines how authentication works and which endpoints require authentication.

## Authentication Methods

### 1. Bearer Token Authentication
- **JWT Tokens**: Short-lived tokens (24 hours default) obtained via `/auth/token` endpoint
- **API Tokens**: Long-lived tokens (1 year default) created via `/api/tokens` endpoint
- **Header**: `Authorization: Bearer <token>`

### 2. Web Session Authentication
- Flask-Login based session authentication for web interface
- Automatic fallback when no Bearer token is provided
- Requires active login session

### 3. Localhost Auto-Authentication
- Requests from `127.0.0.1` or `localhost` are automatically authenticated as admin
- No token or session required for local development/testing

## User Roles

### Admin User
- Full system access
- Can manage users, configuration, and all system functions
- `role = 'admin'` or `is_admin = True`

### Cashier User
- Limited access for betting operations
- Can create/view bets, verify bets, manage cashier-specific functions
- `role = 'cashier'`

### Normal User
- Basic access to betting and viewing functions
- Cannot access administrative functions
- `role = 'normal'` (default)

## Authentication Decorators

### `@get_api_auth_decorator()`
- Requires authentication (any authenticated user)
- Accepts both Bearer tokens and web sessions
- Localhost requests auto-authenticated as admin

### `@get_api_auth_decorator(require_admin=True)`
- Requires admin-level authentication
- Only admin users can access these endpoints
- Accepts both Bearer tokens and web sessions

## API Endpoints by Authentication Level

### Public Endpoints (No Authentication Required)
These endpoints are accessible without any authentication and are intended for public access:

- `GET /api/status` - System status
- `GET /api/debug/match-status` - Debug match status (admin only)
- `GET /api/verify-bet/<uuid:bet_id>` - Bet verification (public for bet checking)
- `GET /api/verify-barcode` - Barcode verification (public for bet checking)
- `GET /api/barcode/<uuid:bet_id>` - Generate bet barcode (public for bet checking)
- `GET /api/barcode-data/<uuid:bet_id>` - Get barcode data (public for bet checking)
- `GET /api/templates/<template_name>` - Template preview (public for display)

### Authenticated Endpoints (Any Logged-in User)
These endpoints require authentication but accept any user role:

- `GET /api/video/status` - Video player status
- `POST /api/video/control` - Video player control
- `POST /api/overlay` - Update video overlay
- `GET /api/templates` - Get available templates
- `GET /api/config` - Get configuration
- `GET /api/config/<section>` - Get config section
- `POST /api/config/<section>` - Update config section (admin only)
- `POST /api/config` - Update configuration (admin only)
- `GET /api/config/match-interval` - Get match interval
- `POST /api/config/match-interval` - Set match interval
- `GET /api/config/license-text` - Get license text
- `POST /api/config/license-text` - Set license text
- `POST /api/config/test-connection` - Test API connection (admin only)
- `GET /api/tokens` - Get user API tokens
- `POST /api/tokens` - Create API token
- `DELETE /api/tokens/<token_id>` - Revoke API token
- `GET /api/logs` - Get application logs (admin only)
- `POST /api/test-message` - Send test message (admin only)
- `POST /api/video/upload` - Upload video file
- `POST /api/video/delete` - Delete video file
- `POST /api/templates/upload` - Upload template (admin only)
- `DELETE /api/templates/<template_name>` - Delete template (admin only)
- `GET /api/outcome-assignments` - Get outcome assignments
- `POST /api/extraction/result-options/add` - Add result option
- `POST /api/extraction/result-options/delete` - Delete result option
- `GET /api/extraction/redistribution-cap` - Get redistribution cap (admin only)
- `POST /api/extraction/redistribution-cap` - Set redistribution cap (admin only)
- `GET /api/currency-settings` - Get currency settings
- `POST /api/currency-settings` - Set currency settings (admin only)
- `GET /api/match-timer/state` - Get match timer state
- `POST /api/match-timer/control` - Control match timer (admin only)
- `GET /api/cashier/bets` - Get cashier bets
- `POST /api/cashier/bets` - Create cashier bet
- `GET /api/cashier/bets/<bet_id>` - Get cashier bet details
- `DELETE /api/cashier/bets/<bet_id>` - Cancel cashier bet
- `GET /api/cashier/available-matches` - Get available matches for betting
- `DELETE /api/cashier/bet-details/<detail_id>` - Delete bet detail
- `DELETE /api/bets/<bet_id>` - Delete admin bet (admin only)
- `POST /api/cashier/bets/<bet_id>/mark-paid` - Mark cashier bet as paid
- `POST /api/bets/<bet_id>/mark-paid` - Mark admin bet as paid
- `GET /api/barcode-settings` - Get barcode settings
- `POST /api/barcode-settings` - Set barcode settings (admin only)
- `GET /api/qrcode-settings` - Get QR code settings
- `POST /api/qrcode-settings` - Set QR code settings (admin only)
- `GET /api/statistics` - Get extraction statistics
- `GET /api/statistics/<stats_id>` - Get statistics details
- `POST /api/system/shutdown` - Shutdown application (admin only)
- `POST /api/upload-intro-video` - Upload intro video (admin only)

### Admin-Only Endpoints
These endpoints require admin role authentication:

- `GET /api/debug/match-status` - Debug match status
- `POST /api/config/<section>` - Update config section
- `POST /api/config` - Update configuration
- `POST /api/config/test-connection` - Test API connection
- `GET /api/logs` - Get application logs
- `POST /api/test-message` - Send test message
- `POST /api/templates/upload` - Upload template
- `DELETE /api/templates/<template_name>` - Delete template
- `GET /api/extraction/redistribution-cap` - Get redistribution cap
- `POST /api/extraction/redistribution-cap` - Set redistribution cap
- `POST /api/currency-settings` - Set currency settings
- `POST /api/match-timer/control` - Control match timer
- `DELETE /api/bets/<bet_id>` - Delete admin bet
- `POST /api/barcode-settings` - Set barcode settings
- `POST /api/qrcode-settings` - Set QR code settings
- `POST /api/system/shutdown` - Shutdown application
- `POST /api/upload-intro-video` - Upload intro video

## Authentication Flow

### For API Requests:
1. Check if request is from localhost (127.0.0.1/localhost) → Auto-authenticate as admin
2. Check for `Authorization: Bearer <token>` header
3. If Bearer token present:
   - Try to verify as JWT token
   - If JWT fails, try to verify as API token
4. If no Bearer token:
   - Check for active Flask-Login web session
   - If session exists, use session user
5. If no authentication found → Return 401 Unauthorized

### For Admin-Required Endpoints:
1. Perform standard authentication (above)
2. Check if authenticated user has admin role (`role == 'admin'` or `is_admin == True`)
3. If not admin → Return 403 Forbidden

## Token Management

### JWT Tokens
- Created via `POST /auth/token` with username/password
- Short-lived (24 hours default)
- Stored in database for revocation tracking
- Include user info and expiration

### API Tokens
- Created via `POST /api/tokens` (authenticated users only)
- Long-lived (1 year default)
- Can be revoked individually
- User-specific

## Error Responses

### 401 Unauthorized
```json
{
  "error": "Authentication required"
}
```

### 403 Forbidden
```json
{
  "error": "Admin access required"
}
```

## Testing Authentication

### Local Development
- Requests from `127.0.0.1` or `localhost` are auto-authenticated as admin
- No tokens or sessions required for local testing

### Production Testing
1. **Get JWT Token:**
   ```bash
   curl -X POST http://your-server/auth/token \
     -H "Content-Type: application/json" \
     -d '{"username": "admin", "password": "password"}'
   ```

2. **Use JWT Token:**
   ```bash
   curl -H "Authorization: Bearer <token>" \
     http://your-server/api/status
   ```

3. **Create API Token:**
   ```bash
   curl -X POST -H "Authorization: Bearer <jwt_token>" \
     http://your-server/api/tokens \
     -H "Content-Type: application/json" \
     -d '{"name": "Test Token", "expires_hours": 8760}'
   ```

## Security Considerations

1. **Token Storage**: Never store tokens in client-side localStorage for production
2. **HTTPS**: Always use HTTPS in production to protect token transmission
3. **Token Expiration**: Implement proper token refresh logic for long-running applications
4. **Rate Limiting**: Consider implementing rate limiting for authentication endpoints
5. **Audit Logging**: All authentication attempts are logged for security monitoring

## Implementation Notes

- The authentication system uses lazy initialization to avoid circular dependencies
- Localhost auto-authentication is intended for development only
- Role-based access control is enforced at the decorator level
- All authentication failures return appropriate HTTP status codes
- The system supports both programmatic API access and web interface access