# 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.

## Authentication System

The system uses a multi-layered authentication approach:

### 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

### 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

### 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

## 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

## 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

### Error Responses
```json
{
    "error": "Authentication required",
    "status": 401
}
```

```json
{
    "error": "Admin access required",
    "status": 403
}
```

## 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"
```

## 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.