Api doc

parent b42f9dcd
# API Authentication Documentation # MbetterClient API Authentication Documentation
## Overview ## 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) 1. **Web-based Authentication**: Uses Flask-Login with user sessions for web interface access
- Short-lived access tokens for web interface authentication 2. **API Authentication**: Uses JWT (JSON Web Tokens) and API tokens for programmatic API access
- Generated via `/auth/token` endpoint with username/password
- Used for API requests with `Authorization: Bearer <token>` header
### 2. API Tokens ## Authentication Components
- Long-lived tokens for programmatic access
- Created and managed via the web dashboard ### 1. AuthManager (`mbetterclient/web_dashboard/auth.py`)
- Used for API requests with `Authorization: Bearer <api_token>` header
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 ### 3. Role-Based Access Control
- **Admin**: Full access to all endpoints
- **Cashier**: Access to cashier-specific endpoints The system supports three user roles:
- **Normal User**: Limited access to user-specific endpoints
- **Admin**: Full access to all endpoints and administrative functions
### 4. Localhost Access - **Cashier**: Access to cashier-specific endpoints and betting operations
- Requests from `127.0.0.1` or `localhost` are automatically authenticated as admin - **Normal User**: Limited access to basic functionality
- Useful for development and testing
## API Endpoint Protection Analysis
## Authentication Decorators
### Protected API Endpoints
The system provides several authentication decorators:
The following API endpoints are properly protected with authentication decorators:
### `@get_api_auth_decorator()`
- Basic authentication decorator #### System and Configuration Endpoints
- Requires valid JWT or API token - `/api/status` - `@get_api_auth_decorator()`
- Used for most authenticated endpoints - `/api/debug/match-status` - `@get_api_auth_decorator(require_admin=True)`
- `/api/video/status` - `@get_api_auth_decorator()`
### `@get_api_auth_decorator(require_admin=True)` - `/api/video/control` - `@get_api_auth_decorator()`
- Admin-only authentication decorator - `/api/overlay` - `@get_api_auth_decorator()`
- Requires valid authentication AND admin role - `/api/templates` - `@get_api_auth_decorator()`
- Used for sensitive administrative endpoints - `/api/config` - `@get_api_auth_decorator()`
- `/api/config/<section>` - `@get_api_auth_decorator()`
### `@require_role(allowed_roles)` - `/api/config/<section>` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- Role-based access control decorator - `/api/config` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- Requires specific roles for access - `/api/config/match-interval` - `@get_api_auth_decorator()`
- Used for role-specific endpoints - `/api/config/match-interval` (POST) - `@get_api_auth_decorator()`
- `/api/config/license-text` - `@get_api_auth_decorator()`
## API Endpoints Authentication Requirements - `/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)`
### Public Endpoints (No Authentication)
These endpoints are accessible without authentication: #### User Management Endpoints
- `/api/users` - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/auth/login` - Login page - `/api/users` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/auth/token` - JWT token generation - `/api/users/<user_id>` (PUT) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/auth/logout` - Logout - `/api/users/<user_id>` (DELETE) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/` - Dashboard home (redirects based on role)
#### Token Management Endpoints
### Authenticated Endpoints - `/api/tokens` - `@get_api_auth_decorator()`
These endpoints require valid authentication (JWT or API token): - `/api/tokens` (POST) - `@get_api_auth_decorator()`
- `/api/tokens/<token_id>` (DELETE) - `@get_api_auth_decorator()`
#### System & Configuration
- `/api/status` - System status #### Logs and Testing Endpoints
- `/api/server-time` - Current server time - `/api/logs` - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/config` - Configuration management - `/api/test-message` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/config/<section>` - Section-specific configuration
- `/api/config/license-text` - License text configuration #### Video Management Endpoints
- `/api/config/match-interval` - Match interval configuration - `/api/video/upload` - `@get_api_auth_decorator()`
- `/api/currency-settings` - Currency settings - `/api/video/delete` - `@get_api_auth_decorator()`
- `/api/barcode-settings` - Barcode settings
- `/api/qrcode-settings` - QR code settings #### Cashier Betting Endpoints
- `/api/cashier/bets` - `@get_api_auth_decorator()`
#### User Management - `/api/cashier/bets` (POST) - `@get_api_auth_decorator()`
- `/api/users` - User management (admin only) - `/api/cashier/bets/<bet_id>` - `@get_api_auth_decorator()`
- `/api/users/<int:user_id>` - User operations (admin only) - `/api/cashier/bets/<bet_id>` (DELETE) - `@get_api_auth_decorator()`
- `/api/tokens` - API token management - `/api/cashier/bet-details/<detail_id>` (DELETE) - `@get_api_auth_decorator()`
- `/api/cashier/available-matches` - `@get_api_auth_decorator()`
#### Video & Overlay Control
- `/api/video/status` - Video player status #### Bet Verification Endpoints
- `/api/video/control` - Video player control - `/api/verify-bet/<bet_id>` - `@get_api_auth_decorator()`
- `/api/overlay` - Overlay updates - `/api/verify-barcode` - `@get_api_auth_decorator()`
- `/api/templates` - Template management
#### Payment Management Endpoints
#### Betting & Fixtures - `/api/cashier/bets/<bet_id>/mark-paid` - `@get_api_auth_decorator()`
- `/api/fixtures` - Get all fixtures - `/api/bets/<bet_id>/mark-paid` - `@get_api_auth_decorator()`
- `/api/fixtures/<fixture_id>` - Get fixture details
- `/api/cashier/pending-matches` - Get pending matches for cashier #### Barcode and QR Code Endpoints
- `/api/cashier/available-matches` - Get available matches for betting - `/api/barcode-settings` - `@get_api_auth_decorator()`
- `/api/cashier/bets` - Cashier bet management - `/api/barcode-settings` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/cashier/bets/<uuid:bet_id>` - Cashier bet details - `/api/qrcode-settings` - `@get_api_auth_decorator()`
- `/api/bets/<uuid:bet_id>` - Bet management (admin/user) - `/api/qrcode-settings` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/barcode/<bet_id>` - `@get_api_auth_decorator()`
#### Verification & Barcode - `/api/barcode-data/<bet_id>` - `@get_api_auth_decorator()`
- `/api/verify-bet/<uuid:bet_id>` - Bet verification
- `/api/verify-barcode` - Barcode verification #### Statistics Endpoints
- `/api/barcode/<uuid:bet_id>` - Barcode generation - `/api/statistics` - `@get_api_auth_decorator()`
- `/api/barcode-data/<uuid:bet_id>` - Barcode data retrieval - `/api/statistics/<stats_id>` - `@get_api_auth_decorator()`
#### Extraction & Statistics #### Match Timer Endpoints
- `/api/extraction/outcomes` - Extraction outcomes - `/api/match-timer/state` - `@get_api_auth_decorator()`
- `/api/extraction/associations` - Extraction associations - `/api/match-timer/control` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/extraction/config` - Extraction configuration
- `/api/statistics` - Statistics and reporting #### Currency Settings Endpoints
- `/api/currency-settings` - `@get_api_auth_decorator()`
### Admin-Only Endpoints - `/api/currency-settings` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
These endpoints require admin authentication:
#### Template Management Endpoints
- `/api/debug/match-status` - Debug match statuses - `/api/templates/upload` - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/cashier/bets/test-simple` - Test bet creation - `/api/templates/<template_name>` (GET) - `@get_api_auth_decorator()`
- `/api/fixtures/reset` - Reset fixtures data - `/api/templates/<template_name>` (DELETE) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/api-client/trigger` - Trigger API requests
- `/api/system/shutdown` - System shutdown #### Extraction and Game Configuration Endpoints
- `/api/templates/upload` - Template upload - `/api/outcome-assignments` - `@get_api_auth_decorator()`
- `/api/templates/<template_name>` - Template deletion - `/api/outcome-assignments` (POST) - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
- `/api/outcome-assignments` - Outcome assignments (POST) - `/api/extraction/available-bets` - `@get_api_auth_decorator()`
- `/api/intro-templates` - Intro templates (POST) - `/api/extraction/available-bets/add` - `@get_api_auth_decorator()`
- `/api/betting-mode` - Betting mode (POST) - `/api/extraction/available-bets/delete` - `@get_api_auth_decorator()`
- `/api/extraction/redistribution-cap` - Redistribution cap - `/api/extraction/result-options` - `@get_api_auth_decorator()`
- `/api/upload-intro-video` - Upload intro video - `/api/extraction/result-options/add` - `@get_api_auth_decorator()`
- `/api/extraction/result-options/delete` - `@get_api_auth_decorator()`
### Cashier-Specific Endpoints - `/api/extraction/redistribution-cap` - `@get_api_auth_decorator()` + `@get_api_auth_decorator(require_admin=True)`
These endpoints are accessible to cashiers: - `/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/cashier/pending-matches` - Get pending matches - `/api/extraction/results-config` (POST) - `@get_api_auth_decorator()`
- `/api/cashier/available-matches` - Get available matches for betting
- `/api/cashier/bets` - Bet management #### Custom Message Endpoints
- `/api/cashier/bets/<uuid:bet_id>` - Bet details - `/api/send-custom-message` - `@get_api_auth_decorator()`
- `/api/cashier/bets/<uuid:bet_id>/mark-paid` - Mark bet as paid
- `/api/cashier/bet-details/<int:detail_id>` - Delete bet detail #### 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 ## Authentication Flow
### 1. User Login ### 1. Web Authentication Flow
1. User navigates to `/auth/login`
2. Enters username and password 1. User navigates to `/login` page
3. System authenticates via `AuthManager.authenticate_user()` 2. User submits username and password
4. User session is created with Flask-Login 3. `AuthManager.authenticate_user()` validates credentials
4. If valid, user is logged in with Flask-Login's `login_user()`
### 2. API Token Generation 5. User is redirected to appropriate dashboard based on role
1. User logs in via web interface
2. Navigates to API tokens page ### 2. API Authentication Flow
3. Creates new API token via `/api/tokens` endpoint
4. Token is stored securely in database 1. Client sends request with `Authorization: Bearer <JWT_TOKEN>` header
2. `@get_api_auth_decorator()` intercepts the request
### 3. API Request Authentication 3. `AuthManager.verify_jwt_token()` validates the JWT token
1. Client includes `Authorization: Bearer <token>` header 4. If valid, request proceeds to the endpoint handler
2. `require_auth()` decorator validates the token 5. If invalid, returns 401 Unauthorized
3. If valid, `request.current_user` is set with user data
4. Request proceeds to endpoint handler ### 3. Admin Authentication Flow
### 4. Role-Based Access Control 1. Client sends request with `Authorization: Bearer <JWT_TOKEN>` header
1. Endpoint with `@get_api_auth_decorator(require_admin=True)` checks admin status 2. `@get_api_auth_decorator(require_admin=True)` intercepts the request
2. `require_role()` decorator checks specific roles 3. `AuthManager.verify_jwt_token()` validates the JWT token
3. If user lacks required role, returns 403 Forbidden 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 ## Error Handling
### Authentication Errors ### Unauthorized Access (401)
- **401 Unauthorized**: Missing or invalid authentication token
- **403 Forbidden**: Authenticated but lacks required permissions ```json
- **404 Not Found**: Endpoint not found {
- **500 Internal Server Error**: Server-side authentication failure "error": "Authentication required"
}
```
### Forbidden Access (403)
### Error Responses
```json ```json
{ {
"error": "Authentication required", "error": "Admin access required"
"status": 401
} }
``` ```
### Invalid Token
```json ```json
{ {
"error": "Admin access required", "error": "Invalid or expired token"
"status": 403
} }
``` ```
## 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 ## Testing Authentication
### Test Cases ### Test Cases
1. **Unauthenticated Access**: Verify 401 responses for protected endpoints
2. **Invalid Token**: Verify 401 responses for invalid tokens 1. **Valid Admin Token**: Should access all endpoints
3. **Expired Token**: Verify 401 responses for expired tokens 2. **Valid Cashier Token**: Should access cashier endpoints only
4. **Role-Based Access**: Verify 403 responses for insufficient permissions 3. **Valid User Token**: Should access standard endpoints only
5. **Localhost Access**: Verify automatic admin authentication for localhost 4. **Invalid Token**: Should return 401 Unauthorized
5. **Expired Token**: Should return 401 Unauthorized
### Test Script 6. **No Token**: Should return 401 Unauthorized
```bash 7. **User Accessing Admin Endpoint**: Should return 403 Forbidden
# Run the test script 8. **Cashier Accessing Admin Endpoint**: Should return 403 Forbidden
python test_api_authentication.py
### Test Endpoints
# Test specific endpoints
curl -X GET http://localhost:5000/api/status - `/auth/token` - Create JWT token for testing
curl -X GET http://localhost:5000/api/status -H "Authorization: Bearer invalid_token" - `/api/status` - Test basic authentication
curl -X GET http://localhost:5000/api/debug/match-status -H "Authorization: Bearer valid_token" - `/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 Check authentication logs for detailed error information.
### Token Management ## API Authentication Summary
- Store tokens securely (not in client-side code)
- Use short expiration times for JWT tokens The MbetterClient API provides comprehensive authentication and authorization:
- Rotate API tokens regularly
- Revoke compromised tokens immediately - **JWT Token Authentication**: Secure token-based authentication
- **Role-Based Access Control**: Admin, cashier, and normal user roles
### Request Security - **API Token Support**: Long-lived tokens for programmatic access
- Always use HTTPS in production - **Proper Error Handling**: Clear error responses for authentication failures
- Validate all input data - **Extensive Coverage**: All sensitive endpoints are properly protected
- Implement rate limiting - **Public Endpoints**: Limited public endpoints for bet verification
- Log authentication attempts
This authentication system ensures that logged-in users (admin/cashier) can securely access the API endpoints while maintaining proper access control and security.
### Role Management \ No newline at end of file
- 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
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