Api doc

parent b42f9dcd
# API Authentication Documentation
# MbetterClient API Authentication Documentation
## Overview
This document describes the authentication system implemented for the MbetterClient API endpoints to ensure that logged-in users (admin/cashier) can access the API endpoints securely.
This document provides comprehensive documentation of the authentication system for the MbetterClient API endpoints, ensuring that logged-in users (admin/cashier) can access the API endpoints securely.
## Authentication System
## Authentication System Architecture
The system uses a multi-layered authentication approach:
The MbetterClient application uses a dual authentication system:
### 1. JWT (JSON Web Tokens)
- Short-lived access tokens for web interface authentication
- Generated via `/auth/token` endpoint with username/password
- Used for API requests with `Authorization: Bearer <token>` header
1. **Web-based Authentication**: Uses Flask-Login with user sessions for web interface access
2. **API Authentication**: Uses JWT (JSON Web Tokens) and API tokens for programmatic API access
### 2. API Tokens
- Long-lived tokens for programmatic access
- Created and managed via the web dashboard
- Used for API requests with `Authorization: Bearer <api_token>` header
## Authentication Components
### 1. AuthManager (`mbetterclient/web_dashboard/auth.py`)
The `AuthManager` class handles all authentication-related functionality:
- **User Authentication**: `authenticate_user(username, password)`
- **JWT Token Management**: `create_jwt_token(user_id)`, `verify_jwt_token(token)`
- **API Token Management**: `create_api_token(user_id, name, expires_hours)`, `verify_api_token(token)`
- **Authentication Decorators**: `require_auth()`, `require_admin()`, `require_role(role)`
### 2. Authentication Decorators
The system provides several authentication decorators for protecting API endpoints:
#### `@get_api_auth_decorator()`
- Basic API authentication decorator
- Validates JWT tokens in the Authorization header
- Falls back to web session authentication if no auth manager is available
#### `@get_api_auth_decorator(require_admin=True)`
- Admin-only API authentication decorator
- Requires both authentication and admin privileges
- Returns 403 Forbidden if user is not an admin
#### `@login_required`
- Web session authentication decorator
- Used for web interface routes
- Requires active Flask-Login session
### 3. Role-Based Access Control
- **Admin**: Full access to all endpoints
- **Cashier**: Access to cashier-specific endpoints
- **Normal User**: Limited access to user-specific endpoints
### 4. Localhost Access
- Requests from `127.0.0.1` or `localhost` are automatically authenticated as admin
- Useful for development and testing
## Authentication Decorators
The system provides several authentication decorators:
### `@get_api_auth_decorator()`
- Basic authentication decorator
- Requires valid JWT or API token
- Used for most authenticated endpoints
### `@get_api_auth_decorator(require_admin=True)`
- Admin-only authentication decorator
- Requires valid authentication AND admin role
- Used for sensitive administrative endpoints
### `@require_role(allowed_roles)`
- Role-based access control decorator
- Requires specific roles for access
- Used for role-specific endpoints
## API Endpoints Authentication Requirements
### Public Endpoints (No Authentication)
These endpoints are accessible without authentication:
- `/auth/login` - Login page
- `/auth/token` - JWT token generation
- `/auth/logout` - Logout
- `/` - Dashboard home (redirects based on role)
### Authenticated Endpoints
These endpoints require valid authentication (JWT or API token):
#### System & Configuration
- `/api/status` - System status
- `/api/server-time` - Current server time
- `/api/config` - Configuration management
- `/api/config/<section>` - Section-specific configuration
- `/api/config/license-text` - License text configuration
- `/api/config/match-interval` - Match interval configuration
- `/api/currency-settings` - Currency settings
- `/api/barcode-settings` - Barcode settings
- `/api/qrcode-settings` - QR code settings
#### User Management
- `/api/users` - User management (admin only)
- `/api/users/<int:user_id>` - User operations (admin only)
- `/api/tokens` - API token management
#### Video & Overlay Control
- `/api/video/status` - Video player status
- `/api/video/control` - Video player control
- `/api/overlay` - Overlay updates
- `/api/templates` - Template management
#### Betting & Fixtures
- `/api/fixtures` - Get all fixtures
- `/api/fixtures/<fixture_id>` - Get fixture details
- `/api/cashier/pending-matches` - Get pending matches for cashier
- `/api/cashier/available-matches` - Get available matches for betting
- `/api/cashier/bets` - Cashier bet management
- `/api/cashier/bets/<uuid:bet_id>` - Cashier bet details
- `/api/bets/<uuid:bet_id>` - Bet management (admin/user)
#### Verification & Barcode
- `/api/verify-bet/<uuid:bet_id>` - Bet verification
- `/api/verify-barcode` - Barcode verification
- `/api/barcode/<uuid:bet_id>` - Barcode generation
- `/api/barcode-data/<uuid:bet_id>` - Barcode data retrieval
#### Extraction & Statistics
- `/api/extraction/outcomes` - Extraction outcomes
- `/api/extraction/associations` - Extraction associations
- `/api/extraction/config` - Extraction configuration
- `/api/statistics` - Statistics and reporting
### Admin-Only Endpoints
These endpoints require admin authentication:
- `/api/debug/match-status` - Debug match statuses
- `/api/cashier/bets/test-simple` - Test bet creation
- `/api/fixtures/reset` - Reset fixtures data
- `/api/api-client/trigger` - Trigger API requests
- `/api/system/shutdown` - System shutdown
- `/api/templates/upload` - Template upload
- `/api/templates/<template_name>` - Template deletion
- `/api/outcome-assignments` - Outcome assignments (POST)
- `/api/intro-templates` - Intro templates (POST)
- `/api/betting-mode` - Betting mode (POST)
- `/api/extraction/redistribution-cap` - Redistribution cap
- `/api/upload-intro-video` - Upload intro video
### Cashier-Specific Endpoints
These endpoints are accessible to cashiers:
- `/api/cashier/pending-matches` - Get pending matches
- `/api/cashier/available-matches` - Get available matches for betting
- `/api/cashier/bets` - Bet management
- `/api/cashier/bets/<uuid:bet_id>` - Bet details
- `/api/cashier/bets/<uuid:bet_id>/mark-paid` - Mark bet as paid
- `/api/cashier/bet-details/<int:detail_id>` - Delete bet detail
The system supports three user roles:
- **Admin**: Full access to all endpoints and administrative functions
- **Cashier**: Access to cashier-specific endpoints and betting operations
- **Normal User**: Limited access to basic functionality
## API Endpoint Protection Analysis
### Protected API Endpoints
The following API endpoints are properly protected with authentication decorators:
#### System and Configuration Endpoints
- `/api/status` - `@get_api_auth_decorator()`
- `/api/debug/match-status` - `@get_api_auth_decorator(require_admin=True)`
- `/api/video/status` - `@get_api_auth_decorator()`
- `/api/video/control` - `@get_api_auth_decorator()`
- `/api/overlay` - `@get_api_auth_decorator()`
- `/api/templates` - `@get_api_auth_decorator()`
- `/api/config` - `@get_api_auth_decorator()`
- `/api/config/<section>` - `@get_api_auth_decorator()`
- `/api/config/<section>` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/config` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/config/match-interval` - `@get_api_auth_decorator()`
- `/api/config/match-interval` (POST) - `@get_api_auth_decorator()`
- `/api/config/license-text` - `@get_api_auth_decorator()`
- `/api/config/license-text` (POST) - `@get_api_auth_decorator()`
- `/api/config/test-connection` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
#### User Management Endpoints
- `/api/users` - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/users` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/users/<user_id>` (PUT) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/users/<user_id>` (DELETE) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
#### Token Management Endpoints
- `/api/tokens` - `@get_api_auth_decorator()`
- `/api/tokens` (POST) - `@get_api_auth_decorator()`
- `/api/tokens/<token_id>` (DELETE) - `@get_api_auth_decorator()`
#### Logs and Testing Endpoints
- `/api/logs` - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/test-message` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
#### Video Management Endpoints
- `/api/video/upload` - `@get_api_auth_decorator()`
- `/api/video/delete` - `@get_api_auth_decorator()`
#### Cashier Betting Endpoints
- `/api/cashier/bets` - `@get_api_auth_decorator()`
- `/api/cashier/bets` (POST) - `@get_api_auth_decorator()`
- `/api/cashier/bets/<bet_id>` - `@get_api_auth_decorator()`
- `/api/cashier/bets/<bet_id>` (DELETE) - `@get_api_auth_decorator()`
- `/api/cashier/bet-details/<detail_id>` (DELETE) - `@get_api_auth_decorator()`
- `/api/cashier/available-matches` - `@get_api_auth_decorator()`
#### Bet Verification Endpoints
- `/api/verify-bet/<bet_id>` - `@get_api_auth_decorator()`
- `/api/verify-barcode` - `@get_api_auth_decorator()`
#### Payment Management Endpoints
- `/api/cashier/bets/<bet_id>/mark-paid` - `@get_api_auth_decorator()`
- `/api/bets/<bet_id>/mark-paid` - `@get_api_auth_decorator()`
#### Barcode and QR Code Endpoints
- `/api/barcode-settings` - `@get_api_auth_decorator()`
- `/api/barcode-settings` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/qrcode-settings` - `@get_api_auth_decorator()`
- `/api/qrcode-settings` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/barcode/<bet_id>` - `@get_api_auth_decorator()`
- `/api/barcode-data/<bet_id>` - `@get_api_auth_decorator()`
#### Statistics Endpoints
- `/api/statistics` - `@get_api_auth_decorator()`
- `/api/statistics/<stats_id>` - `@get_api_auth_decorator()`
#### Match Timer Endpoints
- `/api/match-timer/state` - `@get_api_auth_decorator()`
- `/api/match-timer/control` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
#### Currency Settings Endpoints
- `/api/currency-settings` - `@get_api_auth_decorator()`
- `/api/currency-settings` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
#### Template Management Endpoints
- `/api/templates/upload` - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/templates/<template_name>` (GET) - `@get_api_auth_decorator()`
- `/api/templates/<template_name>` (DELETE) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
#### Extraction and Game Configuration Endpoints
- `/api/outcome-assignments` - `@get_api_auth_decorator()`
- `/api/outcome-assignments` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/extraction/available-bets` - `@get_api_auth_decorator()`
- `/api/extraction/available-bets/add` - `@get_api_auth_decorator()`
- `/api/extraction/available-bets/delete` - `@get_api_auth_decorator()`
- `/api/extraction/result-options` - `@get_api_auth_decorator()`
- `/api/extraction/result-options/add` - `@get_api_auth_decorator()`
- `/api/extraction/result-options/delete` - `@get_api_auth_decorator()`
- `/api/extraction/redistribution-cap` - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/extraction/redistribution-cap` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/extraction/results-config` - `@get_api_auth_decorator()`
- `/api/extraction/results-config` (POST) - `@get_api_auth_decorator()`
#### Custom Message Endpoints
- `/api/send-custom-message` - `@get_api_auth_decorator()`
#### Intro Templates Endpoints
- `/api/intro-templates` - `@get_api_auth_decorator()`
- `/api/intro-templates` (POST) - `@get_api_auth_decorator()`
#### System Management Endpoints
- `/api/system/shutdown` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/upload-intro-video` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
### Public API Endpoints (No Authentication Required)
The following endpoints are intentionally public for bet verification and mobile access:
- `/api/verify-bet/<bet_id>` - Public bet verification
- `/api/verify-barcode` - Public barcode verification
- `/api/barcode/<bet_id>` - Public barcode generation
- `/api/barcode-data/<bet_id>` - Public barcode data retrieval
- `/api/templates/<template_name>` - Public template preview
### Test Endpoints
- `/api/cashier/bets/test-simple` (POST) - Test endpoint with admin authentication
## Authentication Flow
### 1. User Login
1. User navigates to `/auth/login`
2. Enters username and password
3. System authenticates via `AuthManager.authenticate_user()`
4. User session is created with Flask-Login
### 2. API Token Generation
1. User logs in via web interface
2. Navigates to API tokens page
3. Creates new API token via `/api/tokens` endpoint
4. Token is stored securely in database
### 3. API Request Authentication
1. Client includes `Authorization: Bearer <token>` header
2. `require_auth()` decorator validates the token
3. If valid, `request.current_user` is set with user data
4. Request proceeds to endpoint handler
### 4. Role-Based Access Control
1. Endpoint with `@get_api_auth_decorator(require_admin=True)` checks admin status
2. `require_role()` decorator checks specific roles
3. If user lacks required role, returns 403 Forbidden
### 1. Web Authentication Flow
1. User navigates to `/login` page
2. User submits username and password
3. `AuthManager.authenticate_user()` validates credentials
4. If valid, user is logged in with Flask-Login's `login_user()`
5. User is redirected to appropriate dashboard based on role
### 2. API Authentication Flow
1. Client sends request with `Authorization: Bearer <JWT_TOKEN>` header
2. `@get_api_auth_decorator()` intercepts the request
3. `AuthManager.verify_jwt_token()` validates the JWT token
4. If valid, request proceeds to the endpoint handler
5. If invalid, returns 401 Unauthorized
### 3. Admin Authentication Flow
1. Client sends request with `Authorization: Bearer <JWT_TOKEN>` header
2. `@get_api_auth_decorator(require_admin=True)` intercepts the request
3. `AuthManager.verify_jwt_token()` validates the JWT token
4. Additional check verifies `is_admin` flag or `role == 'admin'`
5. If valid admin, request proceeds to the endpoint handler
6. If not admin, returns 403 Forbidden
## JWT Token Management
### Token Creation
```python
# Create JWT token for authenticated user
token = auth_manager.create_jwt_token(user_id)
```
### Token Verification
The `@get_api_auth_decorator()` handles token verification automatically:
1. Extracts `Authorization: Bearer <token>` header
2. Validates token signature and expiration
3. Sets `request.current_user` with user information
4. Allows request to proceed if valid
### Token Response Format
```json
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer",
"user": {
"id": 1,
"username": "admin",
"email": "admin@example.com",
"is_admin": true,
"role": "admin"
}
}
```
## API Token Management
### API Token Creation
```python
# Create API token for programmatic access
result = api.create_api_token(user_id, "Mobile App Token", 8760) # 1 year expiry
```
### API Token Usage
API tokens can be used in place of JWT tokens:
```http
Authorization: Bearer <API_TOKEN>
```
## Role-Based Access Control Implementation
### Admin Access
Endpoints requiring admin access use:
```python
@get_api_auth_decorator(require_admin=True)
def admin_endpoint():
# Admin-only functionality
pass
```
### Cashier Access
Cashier-specific endpoints use standard authentication but include role checks:
```python
@get_api_auth_decorator()
def cashier_endpoint():
# Check if user has cashier role
if request.current_user.get('role') != 'cashier':
return jsonify({"error": "Cashier access required"}), 403
# Cashier functionality
pass
```
### Normal User Access
Most endpoints use standard authentication:
```python
@get_api_auth_decorator()
def user_endpoint():
# Standard user functionality
pass
```
## Error Handling
### Authentication Errors
- **401 Unauthorized**: Missing or invalid authentication token
- **403 Forbidden**: Authenticated but lacks required permissions
- **404 Not Found**: Endpoint not found
- **500 Internal Server Error**: Server-side authentication failure
### Unauthorized Access (401)
```json
{
"error": "Authentication required"
}
```
### Forbidden Access (403)
### Error Responses
```json
{
"error": "Authentication required",
"status": 401
"error": "Admin access required"
}
```
### Invalid Token
```json
{
"error": "Admin access required",
"status": 403
"error": "Invalid or expired token"
}
```
## Localhost Request Handling
The system includes special handling for localhost requests:
- Localhost requests may bypass some authentication checks for development
- Production environments should disable localhost bypass
## Best Practices for API Consumers
### Authentication Headers
Always include the Authorization header:
```http
GET /api/status
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
```
### Token Storage
- Store tokens securely (e.g., secure storage, keychain)
- Never hardcode tokens in client applications
- Use short-lived tokens where possible
### Token Refresh
- Implement token refresh mechanism for long-running applications
- Handle token expiration gracefully with re-authentication
### Role-Based UI
- Hide admin-only features from non-admin users in the UI
- Display appropriate features based on user role
## Security Recommendations
1. **Use HTTPS**: Always use HTTPS for API communication
2. **Token Expiry**: Use reasonable token expiry times (default: 1 hour for JWT)
3. **Token Revocation**: Implement token revocation for compromised tokens
4. **Rate Limiting**: Implement rate limiting on authentication endpoints
5. **Input Validation**: Validate all API inputs to prevent injection attacks
6. **Logging**: Log authentication attempts for security auditing
## Testing Authentication
### Test Cases
1. **Unauthenticated Access**: Verify 401 responses for protected endpoints
2. **Invalid Token**: Verify 401 responses for invalid tokens
3. **Expired Token**: Verify 401 responses for expired tokens
4. **Role-Based Access**: Verify 403 responses for insufficient permissions
5. **Localhost Access**: Verify automatic admin authentication for localhost
### Test Script
```bash
# Run the test script
python test_api_authentication.py
# Test specific endpoints
curl -X GET http://localhost:5000/api/status
curl -X GET http://localhost:5000/api/status -H "Authorization: Bearer invalid_token"
curl -X GET http://localhost:5000/api/debug/match-status -H "Authorization: Bearer valid_token"
1. **Valid Admin Token**: Should access all endpoints
2. **Valid Cashier Token**: Should access cashier endpoints only
3. **Valid User Token**: Should access standard endpoints only
4. **Invalid Token**: Should return 401 Unauthorized
5. **Expired Token**: Should return 401 Unauthorized
6. **No Token**: Should return 401 Unauthorized
7. **User Accessing Admin Endpoint**: Should return 403 Forbidden
8. **Cashier Accessing Admin Endpoint**: Should return 403 Forbidden
### Test Endpoints
- `/auth/token` - Create JWT token for testing
- `/api/status` - Test basic authentication
- `/api/debug/match-status` - Test admin authentication
## Troubleshooting
### Common Issues
1. **401 Unauthorized**: Invalid or missing token
- Verify token is included in Authorization header
- Check token expiration
- Verify token signature
2. **403 Forbidden**: Insufficient permissions
- Verify user role matches endpoint requirements
- Check if endpoint requires admin access
3. **Token Creation Failure**: Authentication issues
- Verify username and password are correct
- Check user account status
### Debugging
Enable debug logging for authentication:
```python
logger.setLevel(logging.DEBUG)
```
## Security Best Practices
### Token Management
- Store tokens securely (not in client-side code)
- Use short expiration times for JWT tokens
- Rotate API tokens regularly
- Revoke compromised tokens immediately
### Request Security
- Always use HTTPS in production
- Validate all input data
- Implement rate limiting
- Log authentication attempts
### Role Management
- Follow principle of least privilege
- Regularly audit user roles
- Remove unnecessary admin access
- Document role requirements
## Implementation Summary
### Changes Made
1. **Added authentication decorators** to all previously unprotected API endpoints
2. **Implemented role-based access control** for sensitive endpoints
3. **Enhanced security** for admin-only endpoints
4. **Maintained localhost access** for development convenience
5. **Documented authentication requirements** for all endpoints
### Endpoints Updated
- `/api/status` - Added `@get_api_auth_decorator()`
- `/api/debug/match-status` - Added `@get_api_auth_decorator(require_admin=True)`
- `/api/fixtures` - Added `@get_api_auth_decorator()`
- `/api/cashier/pending-matches` - Added `@get_api_auth_decorator()`
- `/api/fixtures/<fixture_id>` - Added `@get_api_auth_decorator()`
- `/api/server-time` - Added `@get_api_auth_decorator()`
- `/api/cashier/bets/test-simple` - Added `@get_api_auth_decorator(require_admin=True)`
- `/api/verify-bet/<uuid:bet_id>` - Added `@get_api_auth_decorator()`
- `/api/verify-barcode` - Added `@get_api_auth_decorator()`
- `/api/barcode/<uuid:bet_id>` - Added `@get_api_auth_decorator()`
- `/api/barcode-data/<uuid:bet_id>` - Added `@get_api_auth_decorator()`
- `/api/templates/<template_name>` - Added `@get_api_auth_decorator()`
## Conclusion
The API authentication system now ensures that:
- All API endpoints require proper authentication
- Role-based access control is implemented correctly
- Admin-only endpoints are properly protected
- Localhost access is maintained for development
- JWT and API token authentication works for all endpoints
- Comprehensive error handling is in place
The system provides a secure foundation for the MbetterClient application while maintaining flexibility for different user roles and access requirements.
\ No newline at end of file
Check authentication logs for detailed error information.
## API Authentication Summary
The MbetterClient API provides comprehensive authentication and authorization:
- **JWT Token Authentication**: Secure token-based authentication
- **Role-Based Access Control**: Admin, cashier, and normal user roles
- **API Token Support**: Long-lived tokens for programmatic access
- **Proper Error Handling**: Clear error responses for authentication failures
- **Extensive Coverage**: All sensitive endpoints are properly protected
- **Public Endpoints**: Limited public endpoints for bet verification
This authentication system ensures that logged-in users (admin/cashier) can securely access the API endpoints while maintaining proper access control and security.
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment