update docs

This commit is contained in:
Fran Jurmanović
2025-07-29 20:50:57 +02:00
parent 647f4f7487
commit 90aa63fc99
34 changed files with 5697 additions and 5905 deletions

124
README.md
View File

@@ -1,135 +1,97 @@
# ACC Server Manager
A comprehensive web-based management system for Assetto Corsa Competizione (ACC) dedicated servers.
A web-based management system for Assetto Corsa Competizione (ACC) dedicated servers on Windows.
## 🚀 Quick Start
## Quick Start
### Prerequisites
- Windows 10/11 or Windows Server 2016+
- Go 1.23.0+
- Administrative privileges
- [SteamCMD](https://developer.valvesoftware.com/wiki/SteamCMD#Downloading_SteamCMD)
- [NSSM](https://nssm.cc/download) (for Windows service management)
### Installation
1. **Clone and Build**
1. **Clone and build**
```bash
git clone <repository-url>
cd acc-server-manager
go mod download
go build -o api.exe cmd/api/main.go
```
2. **Set Environment Variables**
```powershell
# Set tool paths (optional - defaults will be used if not set)
$env:STEAMCMD_PATH = "C:\steamcmd\steamcmd.exe"
$env:NSSM_PATH = ".\nssm.exe"
```
3. **Generate Configuration**
2. **Generate configuration**
```powershell
# Windows PowerShell
.\scripts\generate-secrets.ps1
# Or manually copy and edit
copy .env.example .env
```
4. **Run Application**
3. **Run**
```bash
./api.exe
```
Access at: http://localhost:3000
Access the web interface at: http://localhost:3000
## ✨ Key Features
## Features
- **Multi-Server Management** - Manage multiple ACC servers from one interface
- **Steam Integration** - Automated server installation and updates
- **Real-time Monitoring** - Live server status and performance metrics
- **Advanced Security** - JWT authentication, role-based access, rate limiting
- **Configuration Management** - Web-based configuration editor
- **Service Integration** - Windows Service management
- **Web Configuration** - Edit server settings through the browser
- **Windows Services** - Run servers as Windows services
- **Security** - JWT authentication and encrypted credential storage
- **Interactive API** - Swagger UI for API testing and documentation
## 🔧 Configuration
## Configuration
### Environment Variables
The application uses environment variables for tool configuration:
The application uses these environment variables:
| Variable | Description | Default |
|----------|-------------|---------|
| `STEAMCMD_PATH` | Path to SteamCMD executable | `c:\steamcmd\steamcmd.exe` |
| `NSSM_PATH` | Path to NSSM executable | `.\nssm.exe` |
| `STEAMCMD_PATH` | Path to SteamCMD | `c:\steamcmd\steamcmd.exe` |
| `NSSM_PATH` | Path to NSSM | `.\nssm.exe` |
| `PORT` | Web server port | `3000` |
For detailed configuration information, see [Environment Variables Documentation](documentation/ENVIRONMENT_VARIABLES.md).
Security keys are automatically generated by the setup script.
## 🏗️ Architecture
## API Documentation
- **Backend**: Go + Fiber web framework
- **Database**: SQLite with GORM
- **Authentication**: JWT with bcrypt
- **API**: RESTful with Swagger documentation
### Interactive Swagger UI
## 📚 Documentation
Access the comprehensive API documentation with testing capabilities at:
- **Swagger UI**: http://localhost:3000/swagger/
- **OpenAPI Spec**: http://localhost:3000/swagger/doc.json
Comprehensive documentation is available in the [`documentation/`](documentation/) folder:
The Swagger interface allows you to:
- Test API endpoints directly from your browser
- View request/response examples
- Authenticate and test protected endpoints
- Generate client libraries from the OpenAPI spec
- **[Detailed README](documentation/DETAILED_README.md)** - Complete setup and usage guide
- **[Logging System](documentation/LOGGING_IMPLEMENTATION_SUMMARY.md)** - Enhanced error handling and logging
- **[Security Guide](documentation/SECURITY.md)** - Security features and best practices
- **[Configuration](documentation/CONFIGURATION.md)** - Advanced configuration options
- **[API Documentation](documentation/API.md)** - Complete API reference
- **[Deployment Guide](documentation/DEPLOYMENT.md)** - Production deployment instructions
- **[Migration Guides](documentation/)** - Database and feature migration instructions
For detailed API usage, see [API Reference](docs/API.md) and [Swagger Guide](docs/SWAGGER.md).
## 🔒 Security Features
- JWT token authentication
- Role-based access control
- AES-256 encryption for sensitive data
- Comprehensive input validation
- Rate limiting and DoS protection
- Security headers and CORS protection
## 🛠️ Development
## Development
```bash
# Development with hot reload
# Install hot-reload tool
go install github.com/cosmtrek/air@latest
# Run with hot reload
air
# Run tests
go test ./...
# API Documentation
# Visit: http://localhost:3000/swagger/
```
## 📝 Environment Variables
## Documentation
Required variables (auto-generated by scripts):
- `JWT_SECRET` - JWT signing secret
- `APP_SECRET` - Application secret key
- `ENCRYPTION_KEY` - AES encryption key
- [Setup Guide](docs/SETUP.md) - Detailed installation instructions
- [Configuration](docs/CONFIG.md) - Advanced configuration options
- [API Reference](docs/API.md) - API endpoints and authentication
- [Swagger Guide](docs/SWAGGER.md) - Interactive API documentation
- [Troubleshooting](docs/TROUBLESHOOTING.md) - Common issues and solutions
Optional:
- `PORT` - HTTP port (default: 3000)
- `DB_NAME` - Database file (default: acc.db)
- `CORS_ALLOWED_ORIGIN` - CORS origins
## License
## 🤝 Contributing
1. Fork the repository
2. Create feature branch: `git checkout -b feature/name`
3. Make changes and add tests
4. Submit pull request
## 📄 License
MIT License - see [LICENSE](LICENSE) file for details.
---
For detailed documentation, troubleshooting, and advanced configuration, see the [`documentation/`](documentation/) folder.
**Happy Racing! 🏁**
MIT License - see [LICENSE](LICENSE) file for details.

197
docs/API.md Normal file
View File

@@ -0,0 +1,197 @@
# API Reference
ACC Server Manager provides a RESTful API for managing ACC dedicated servers.
## Interactive Documentation
**Swagger UI is available at: http://localhost:3000/swagger/**
The Swagger UI provides:
- Interactive API testing
- Request/response examples
- Schema definitions
- Authentication testing
For detailed Swagger usage, see [SWAGGER.md](SWAGGER.md).
## Base URL
```
http://localhost:3000/api/v1
```
## Authentication
The API uses JWT (JSON Web Token) authentication. Include the token in the Authorization header:
```
Authorization: Bearer <your-jwt-token>
```
### Getting a Token
```http
POST /auth/login
Content-Type: application/json
{
"username": "admin",
"password": "your-password"
}
```
Response:
```json
{
"token": "eyJhbGciOiJIUzI1NiIs...",
"user": {
"id": "uuid",
"username": "admin",
"role": "admin"
}
}
```
## Core Endpoints
### Authentication
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/auth/login` | Login |
| POST | `/auth/register` | Register new user |
| GET | `/auth/me` | Get current user |
| POST | `/auth/refresh` | Refresh token |
### Server Management
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/servers` | List all servers |
| POST | `/servers` | Create new server |
| GET | `/servers/{id}` | Get server details |
| PUT | `/servers/{id}` | Update server |
| DELETE | `/servers/{id}` | Delete server |
### Server Operations
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/servers/{id}/service/start` | Start server |
| POST | `/servers/{id}/service/stop` | Stop server |
| POST | `/servers/{id}/service/restart` | Restart server |
| GET | `/servers/{id}/service/status` | Get server status |
### Configuration
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/servers/{id}/config/{file}` | Get config file |
| PUT | `/servers/{id}/config/{file}` | Update config file |
Available config files:
- `configuration.json`
- `settings.json`
- `event.json`
- `eventRules.json`
- `assistRules.json`
### System
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/system/health` | Health check
## Request Examples
### Create Server
```http
POST /api/v1/servers
Content-Type: application/json
Authorization: Bearer <token>
{
"name": "My ACC Server",
"track": "monza",
"maxClients": 30
}
```
### Update Configuration
```http
PUT /api/v1/servers/123/config/settings.json
Content-Type: application/json
Authorization: Bearer <token>
{
"serverName": "My Updated Server",
"adminPassword": "secret",
"trackMedalsRequirement": 0,
"safetyRatingRequirement": -1
}
```
### Start Server
```http
POST /api/v1/servers/123/start
Authorization: Bearer <token>
```
## Response Formats
### Success Response
```json
{
"success": true,
"data": { ... }
}
```
### Error Response
```json
{
"success": false,
"error": "Error message",
"code": "ERROR_CODE"
}
```
## Status Codes
- `200` - Success
- `201` - Created
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not Found
- `500` - Internal Server Error
## Rate Limiting
- 100 requests per minute per IP
- 1000 requests per hour per user
## Additional Resources
### Swagger Documentation
For comprehensive interactive API documentation:
- **Swagger UI**: http://localhost:3000/swagger/
- **OpenAPI Spec**: http://localhost:3000/swagger/doc.json
- **Usage Guide**: [SWAGGER.md](SWAGGER.md)
### Client Libraries
Generate client libraries using the OpenAPI spec:
```bash
# Download spec
curl http://localhost:3000/swagger/doc.json -o swagger.json
# Generate client (example for JavaScript)
openapi-generator generate -i swagger.json -g javascript -o ./client
```

140
docs/CONFIG.md Normal file
View File

@@ -0,0 +1,140 @@
# Configuration Guide
This guide covers the configuration options for ACC Server Manager.
## Environment Variables
### Required Variables (Auto-generated)
These are automatically created by the setup script:
- `JWT_SECRET` - Authentication token secret
- `APP_SECRET` - Application encryption key
- `ENCRYPTION_KEY` - Database encryption key
### Optional Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `PORT` | Web server port | `3000` |
| `DB_NAME` | Database filename | `acc.db` |
| `STEAMCMD_PATH` | Path to SteamCMD | `c:\steamcmd\steamcmd.exe` |
| `NSSM_PATH` | Path to NSSM | `.\nssm.exe` |
| `CORS_ALLOWED_ORIGIN` | Allowed CORS origins | `http://localhost:5173` |
## Setting Environment Variables
### Temporary (Current Session)
```powershell
# PowerShell
$env:PORT = "8080"
$env:STEAMCMD_PATH = "D:\tools\steamcmd\steamcmd.exe"
```
### Permanent (System-wide)
1. Open System Properties → Advanced → Environment Variables
2. Add new system variables with desired values
3. Restart the application
## Server Configuration
### ACC Server Settings
Each ACC server instance has its own configuration managed through the web interface:
- **Server Name** - Display name in the manager
- **Port Settings** - TCP/UDP ports (auto-assigned or manual)
- **Configuration Files** - Edit `configuration.json`, `settings.json`, etc.
### Firewall Rules
The application automatically manages Windows Firewall rules for ACC servers:
- Creates inbound rules for TCP and UDP ports
- Names rules as "ACC Server - [ServerName]"
- Removes rules when server is deleted
## Security Configuration
### Password Requirements
- Minimum 8 characters
- Mix of uppercase, lowercase, numbers
- Special characters recommended
### Session Management
- JWT tokens expire after 24 hours
- Refresh tokens available for extended sessions
- Configurable timeout in future releases
## Database
### SQLite Configuration
- Database file: `acc.db` (configurable via `DB_NAME`)
- Automatic backups: Not yet implemented
- Location: Application root directory
### Data Encryption
Sensitive data is encrypted using AES-256:
- Steam credentials
- User passwords (bcrypt)
- API keys
## Logging
### Log Files
Located in `logs/` directory:
- `app.log` - General application logs
- `error.log` - Error messages
- `access.log` - HTTP access logs
### Log Rotation
Currently manual - delete old logs periodically.
## Performance Tuning
### Database Optimization
- Use SSD for database location
- Regular VACUUM operations recommended
- Keep database size under 1GB
### Memory Usage
- Base usage: ~50MB
- Per server instance: ~10MB
- Caching: ~100MB
## Advanced Configuration
### Custom Ports
To use custom port ranges for ACC servers:
1. Log into web interface
2. Go to Settings → Server Defaults
3. Set port range (e.g., 9600-9700)
### Multiple IPs
If your server has multiple network interfaces:
1. ACC servers will bind to all interfaces by default
2. Configure specific IPs in ACC server settings files
## Configuration Best Practices
1. **Backup your `.env` file** - Contains encryption keys
2. **Use strong passwords** - Especially for admin account
3. **Regular updates** - Keep ACC Server Manager updated
4. **Monitor logs** - Check for errors or warnings
5. **Test changes** - Verify configuration changes work as expected

178
docs/DEPLOYMENT.md Normal file
View File

@@ -0,0 +1,178 @@
# Deployment Guide
This guide covers deploying ACC Server Manager to a production Windows server.
## Production Requirements
- Windows Server 2016+ or Windows 10/11
- 4GB+ RAM
- 20GB+ free disk space
- Administrator access
- SteamCMD and NSSM installed
## Deployment Steps
### 1. Prepare the Server
Install required tools:
```powershell
# Create directories
New-Item -ItemType Directory -Path "C:\ACCServerManager"
New-Item -ItemType Directory -Path "C:\steamcmd"
New-Item -ItemType Directory -Path "C:\tools\nssm"
# Download and extract SteamCMD
# Download and extract NSSM
```
### 2. Build for Production
On your development machine:
```bash
# Build optimized binary
go build -ldflags="-w -s" -o acc-server-manager.exe cmd/api/main.go
```
### 3. Deploy Files
Copy to server:
- `acc-server-manager.exe`
- `.env` file (with production secrets)
- `nssm.exe` (if not in PATH)
### 4. Configure Production Environment
Generate production secrets:
```powershell
# On the server
.\scripts\generate-secrets.ps1
```
Edit `.env` for production:
```env
PORT=80
CORS_ALLOWED_ORIGIN=https://yourdomain.com
```
### 5. Install as Windows Service
```powershell
# Using NSSM
nssm install "ACC Server Manager" "C:\ACCServerManager\acc-server-manager.exe"
nssm set "ACC Server Manager" DisplayName "ACC Server Manager"
nssm set "ACC Server Manager" Description "Web management for ACC servers"
nssm set "ACC Server Manager" Start SERVICE_AUTO_START
nssm set "ACC Server Manager" AppDirectory "C:\ACCServerManager"
# Start the service
nssm start "ACC Server Manager"
```
### 6. Configure Firewall
```powershell
# Allow HTTP traffic
New-NetFirewallRule -DisplayName "ACC Server Manager" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
```
### 7. Set Up Reverse Proxy (Optional)
If using IIS as reverse proxy:
1. Install URL Rewrite and ARR modules
2. Configure reverse proxy to localhost:3000
3. Enable HTTPS with valid certificate
## Security Checklist
- [ ] Generated unique production secrets
- [ ] Changed default admin password
- [ ] Configured HTTPS (via reverse proxy)
- [ ] Restricted database file permissions
- [ ] Enabled Windows Firewall
- [ ] Disabled unnecessary ports
- [ ] Set up backup schedule
## Monitoring
### Service Health
```powershell
# Check service status
Get-Service "ACC Server Manager"
# View recent logs
Get-EventLog -LogName Application -Source "ACC Server Manager" -Newest 20
```
### Application Logs
- Check `logs/app.log` for application events
- Check `logs/error.log` for errors
- Monitor disk space for log growth
## Backup Strategy
### Automated Backups
Create scheduled task for daily backups:
```powershell
# Backup script (save as backup.ps1)
$date = Get-Date -Format "yyyy-MM-dd"
$backupDir = "C:\Backups\ACCServerManager"
New-Item -ItemType Directory -Force -Path $backupDir
# Backup database and config
Copy-Item "C:\ACCServerManager\acc.db" "$backupDir\acc_$date.db"
Copy-Item "C:\ACCServerManager\.env" "$backupDir\env_$date"
# Keep only last 7 days
Get-ChildItem $backupDir -File | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-7)} | Remove-Item
```
## Updates
### Update Process
1. **Backup current deployment**
2. **Build new version**
3. **Stop service**: `nssm stop "ACC Server Manager"`
4. **Replace binary**
5. **Start service**: `nssm start "ACC Server Manager"`
6. **Verify**: Check logs and web interface
### Rollback
If update fails:
1. Stop service
2. Restore previous binary
3. Restore database if needed
4. Start service
## Troubleshooting Deployment
### Service Won't Start
- Check Event Viewer for errors
- Verify .env file exists and is valid
- Run manually to see console output
### Can't Access Web Interface
- Check firewall rules
- Verify service is running
- Check port binding in .env
### Permission Errors
- Run service as Administrator (not recommended)
- Or grant specific permissions to service account
## Performance Tuning
### For Large Deployments
- Use SSD for database storage
- Increase Windows TCP connection limits
- Consider load balancing for 50+ servers
- Monitor memory usage and adjust if needed
### Database Maintenance
```sql
-- Run monthly via SQLite
VACUUM;
ANALYZE;
```

125
docs/MIGRATION.md Normal file
View File

@@ -0,0 +1,125 @@
# Migration Guide
This guide covers database migrations and version upgrades for ACC Server Manager.
## Database Migrations
The application handles database migrations automatically on startup. No manual intervention is required for most upgrades.
### Automatic Migrations
When you start the application:
1. It checks the current database schema
2. Applies any pending migrations
3. Updates the schema version
### Manual Migration (if needed)
If automatic migration fails:
```bash
# Backup your database first
copy acc.db acc_backup.db
# Delete the database and let it recreate
del acc.db
# Start the application - it will create a fresh database
./api.exe
```
## Upgrading ACC Server Manager
### From v1.x to v2.x
1. **Backup your data**
```bash
copy acc.db acc_backup.db
copy .env .env.backup
```
2. **Stop the application**
```bash
# If running as service
nssm stop "ACC Server Manager"
```
3. **Update the code**
```bash
git pull
go build -o api.exe cmd/api/main.go
```
4. **Update configuration**
- Check `.env.example` for new required variables
- Run `.\scripts\generate-secrets.ps1` if needed
5. **Start the application**
```bash
./api.exe
# Or restart service
nssm start "ACC Server Manager"
```
## Breaking Changes
### v2.0
- Changed from system_configs table to environment variables
- Now use `STEAMCMD_PATH` and `NSSM_PATH` environment variables
- UUID fields added to all tables (automatic migration)
### v1.5
- Authentication system overhaul
- New permission system
- Password requirements enforced
## Data Backup
### Regular Backups
Create a scheduled task to backup your database:
```powershell
# PowerShell backup script
$date = Get-Date -Format "yyyy-MM-dd"
Copy-Item "acc.db" "backups\acc_$date.db"
```
### What to Backup
- `acc.db` - Main database
- `.env` - Configuration and secrets
- `logs/` - Application logs (optional)
- Server configuration files in each server directory
## Rollback Procedure
If an upgrade fails:
1. Stop the application
2. Restore the database: `copy acc_backup.db acc.db`
3. Restore the configuration: `copy .env.backup .env`
4. Use the previous binary version
5. Start the application
## Common Migration Issues
### "Database locked"
- Stop all instances of the application
- Check for stuck processes
### "Schema version mismatch"
- Let automatic migration complete
- Don't interrupt during migration
### "Missing columns"
- Database migration was interrupted
- Restore from backup and retry
## Best Practices
1. **Always backup before upgrading**
2. **Test upgrades in a non-production environment first**
3. **Read release notes for breaking changes**
4. **Keep the last working version's binary**
5. **Monitor logs during first startup after upgrade**

121
docs/SETUP.md Normal file
View File

@@ -0,0 +1,121 @@
# Setup Guide
This guide covers the complete setup process for ACC Server Manager.
## Prerequisites
### Required Software
1. **Windows OS**: Windows 10/11 or Windows Server 2016+
2. **Go**: Version 1.23.0+ ([Download](https://golang.org/dl/))
3. **SteamCMD**: For ACC server installation ([Download](https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip))
4. **NSSM**: For Windows service management ([Download](https://nssm.cc/release/nssm-2.24.zip))
### System Requirements
- Administrator privileges (for service and firewall management)
- At least 4GB RAM
- 10GB+ free disk space for ACC servers
## Installation Steps
### 1. Install SteamCMD
1. Download SteamCMD from the link above
2. Extract to `C:\steamcmd\`
3. Run `steamcmd.exe` once to complete setup
### 2. Install NSSM
1. Download NSSM from the link above
2. Extract the appropriate version (32-bit or 64-bit)
3. Copy `nssm.exe` to the ACC Server Manager directory or add to PATH
### 3. Build ACC Server Manager
```bash
# Clone the repository
git clone <repository-url>
cd acc-server-manager
# Build the application
go build -o api.exe cmd/api/main.go
```
### 4. Configure Environment
Run the setup script to generate secure configuration:
```powershell
# PowerShell
.\scripts\generate-secrets.ps1
```
This creates a `.env` file with secure random keys.
### 5. Set Tool Paths (Optional)
If your tools are not in the default locations:
```powershell
# PowerShell
$env:STEAMCMD_PATH = "D:\tools\steamcmd\steamcmd.exe"
$env:NSSM_PATH = "D:\tools\nssm\nssm.exe"
```
### 6. First Run
```bash
# Start the server
./api.exe
```
The server will start on http://localhost:3000
### 7. Initial Login
1. Open http://localhost:3000 in your browser
2. Default credentials:
- Username: `admin`
- Password: Set in `.env` file or use default (change immediately)
## Post-Installation
### Configure Steam Credentials
1. Log into the web interface
2. Go to Settings → Steam Configuration
3. Enter your Steam credentials (encrypted storage)
### Create Your First Server
1. Click "Add Server"
2. Enter server details
3. Click "Install" to download ACC server files via Steam
4. Configure and start your server
## Running as a Service
To run ACC Server Manager as a Windows service:
```bash
# Install service
nssm install "ACC Server Manager" "C:\path\to\api.exe"
# Start service
nssm start "ACC Server Manager"
```
## Verify Installation
Check that everything is working:
1. Access http://localhost:3000
2. Check logs in `logs/` directory
3. Try creating a test server
## Next Steps
- [Configure your servers](CONFIG.md)
- [Review API documentation](API.md)
- [Troubleshooting guide](TROUBLESHOOTING.md)

161
docs/SWAGGER.md Normal file
View File

@@ -0,0 +1,161 @@
# Swagger API Documentation
This guide explains how to use the interactive API documentation for ACC Server Manager.
## Accessing Swagger UI
The Swagger UI is available at:
```
http://localhost:3000/swagger/
```
## Authentication
Most API endpoints require JWT authentication. To use authenticated endpoints:
1. **Get a token**: Use the `/auth/login` endpoint with valid credentials
2. **Authorize**: Click the "Authorize" button in Swagger UI
3. **Enter token**: Type `Bearer <your-token>` (include the word "Bearer")
4. **Test endpoints**: Now you can test protected endpoints
## API Overview
### Authentication Endpoints
- `POST /auth/login` - Login and get JWT token
- `GET /auth/me` - Get current user information
### Server Management
- `GET /v1/server` - List all servers
- `POST /v1/server` - Create new server
- `GET /v1/server/{id}` - Get server details
- `PUT /v1/server/{id}` - Update server
- `DELETE /v1/server/{id}` - Delete server
### Server Configuration
- `GET /v1/server/{id}/config` - List config files
- `GET /v1/server/{id}/config/{file}` - Get config file
- `PUT /v1/server/{id}/config/{file}` - Update config file
### Service Control
- `GET /v1/service-control/{service}` - Get service status
- `POST /v1/service-control/start` - Start service
- `POST /v1/service-control/stop` - Stop service
- `POST /v1/service-control/restart` - Restart service
### Lookups
- `GET /v1/lookup/tracks` - Available tracks
- `GET /v1/lookup/car-models` - Available cars
- `GET /v1/lookup/driver-categories` - Driver categories
- `GET /v1/lookup/cup-categories` - Cup categories
- `GET /v1/lookup/session-types` - Session types
### User Management
- `GET /v1/membership` - List users
- `POST /v1/membership` - Create user
- `GET /v1/membership/{id}` - Get user details
- `PUT /v1/membership/{id}` - Update user
- `DELETE /v1/membership/{id}` - Delete user
## Common Operations
### Login Example
```json
POST /auth/login
{
"username": "admin",
"password": "your-password"
}
Response:
{
"token": "eyJhbGciOiJIUzI1NiIs..."
}
```
### Create Server Example
```json
POST /v1/server
Authorization: Bearer <token>
{
"name": "My ACC Server",
"track": "monza",
"maxClients": 30,
"tcpPort": 9201,
"udpPort": 9201
}
```
### Update Configuration Example
```json
PUT /v1/server/{id}/config/settings.json
Authorization: Bearer <token>
{
"serverName": "My Updated Server",
"adminPassword": "secret",
"trackMedalsRequirement": 0,
"safetyRatingRequirement": -1
}
```
## Response Codes
- `200` - Success
- `201` - Created
- `400` - Bad Request (invalid input)
- `401` - Unauthorized (missing/invalid token)
- `403` - Forbidden (insufficient permissions)
- `404` - Not Found
- `409` - Conflict (duplicate resource)
- `500` - Internal Server Error
## Testing Tips
1. **Start with login** - Get your token first
2. **Use "Try it out"** - Click this button to test endpoints
3. **Check examples** - Swagger shows request/response examples
4. **View schemas** - Click "Schema" to see data structures
5. **Download spec** - Get the OpenAPI spec at `/swagger/doc.json`
## Troubleshooting
### "Unauthorized" errors
- Ensure you've logged in and added the token
- Check token hasn't expired (24 hour expiry)
- Include "Bearer " prefix with token
### "Invalid JSON" errors
- Use the schema examples provided
- Validate JSON syntax
- Check required fields
### Can't see Swagger UI
- Ensure server is running
- Check correct URL and port
- Verify no firewall blocking
## Generating API Clients
You can generate client libraries from the OpenAPI spec:
1. Download spec from `/swagger/doc.json`
2. Use [OpenAPI Generator](https://openapi-generator.tech/)
3. Generate clients for your language:
```bash
openapi-generator generate -i swagger.json -g javascript -o ./client
```
## API Rate Limits
- 100 requests per minute per IP
- 1000 requests per hour per user
- Rate limit headers included in responses
## For Developers
To update Swagger documentation:
1. Edit controller annotations
2. Run: `swag init -g cmd/api/swagger.go -o docs/`
3. Restart the server
See controller files for annotation examples.

173
docs/TROUBLESHOOTING.md Normal file
View File

@@ -0,0 +1,173 @@
# Troubleshooting Guide
Common issues and solutions for ACC Server Manager.
## Installation Issues
### "go: command not found"
**Solution**: Install Go from https://golang.org/dl/ and add to PATH.
### "steamcmd.exe not found"
**Solution**:
1. Download SteamCMD from https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip
2. Extract to `C:\steamcmd\`
3. Or set `STEAMCMD_PATH` environment variable to your location
### "nssm.exe not found"
**Solution**:
1. Download NSSM from https://nssm.cc/download
2. Place `nssm.exe` in application directory
3. Or set `NSSM_PATH` environment variable
## Startup Issues
### "JWT_SECRET environment variable is required"
**Solution**: Run the setup script:
```powershell
.\scripts\generate-secrets.ps1
```
### "Failed to connect database"
**Solution**:
1. Check write permissions in application directory
2. Delete `acc.db` if corrupted and restart
3. Ensure no other instance is running
### Port already in use
**Solution**:
1. Change port in `.env` file: `PORT=8080`
2. Or stop the application using port 3000
## Server Management Issues
### "Failed to create firewall rule"
**Solution**: Run ACC Server Manager as Administrator.
### ACC server won't start
**Solutions**:
1. Check ACC server logs in server directory
2. Verify ports are not in use
3. Ensure Steam credentials are correct
4. Check Windows Event Viewer
### "Steam authentication failed"
**Solutions**:
1. Verify Steam credentials in Settings
2. Check if Steam Guard is enabled
3. Try logging into Steam manually first
## Performance Issues
### High CPU usage
**Solutions**:
1. Reduce number of active servers
2. Check for runaway ACC server processes
3. Restart ACC Server Manager
### High memory usage
**Solutions**:
1. Check database size (should be < 1GB)
2. Restart application to clear caches
3. Reduce log retention
## Authentication Issues
### Can't login
**Solutions**:
1. Check username and password
2. Clear browser cookies
3. Check logs for specific errors
### "Token expired"
**Solution**: Login again to get a new token.
## Configuration Issues
### Changes not saving
**Solutions**:
1. Check file permissions
2. Ensure valid JSON format
3. Check logs for validation errors
### Can't edit server config
**Solutions**:
1. Stop the server first
2. Check user permissions
3. Verify file isn't locked
## Network Issues
### Can't connect to server
**Solutions**:
1. Check Windows Firewall rules
2. Verify port forwarding on router
3. Ensure server is actually running
### API requests failing
**Solutions**:
1. Check CORS settings if using custom frontend
2. Verify authentication token
3. Check API endpoint URL
## Logging & Debugging
### Enable debug logging
Add to `.env` file:
```
LOG_LEVEL=debug
```
### Log locations
- Application logs: `logs/app.log`
- Error logs: `logs/error.log`
- ACC server logs: In each server's directory
## Common Error Messages
### "Permission denied"
- Run as Administrator
- Check file/folder permissions
### "Invalid configuration"
- Validate JSON syntax
- Check required fields
### "Database locked"
- Close other instances
- Restart application
### "Service installation failed"
- Ensure NSSM is available
- Run as Administrator
- Check service name conflicts
## Getting Help
If these solutions don't work:
1. Check the logs in `logs/` directory
2. Search existing GitHub issues
3. Create a new issue with:
- Error message
- Steps to reproduce
- System information
- Relevant log entries

View File

@@ -1,407 +0,0 @@
// Package docs Code generated by swaggo/swag. DO NOT EDIT
package docs
import "github.com/swaggo/swag"
const docTemplate = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{escape .Description}}",
"title": "{{.Title}}",
"contact": {},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/v1/api": {
"get": {
"description": "Return API",
"tags": [
"api"
],
"summary": "Return API",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/api/restart": {
"post": {
"description": "Restarts service",
"tags": [
"api"
],
"summary": "Restart service",
"parameters": [
{
"description": "required",
"name": "name",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/api/start": {
"post": {
"description": "Starts service",
"tags": [
"api"
],
"summary": "Start service",
"parameters": [
{
"description": "required",
"name": "name",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/api/stop": {
"post": {
"description": "Stops service",
"tags": [
"api"
],
"summary": "Stop service",
"parameters": [
{
"description": "required",
"name": "name",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/api/{service}": {
"get": {
"description": "Returns service status",
"tags": [
"api"
],
"summary": "Return service status",
"parameters": [
{
"type": "string",
"description": "required",
"name": "service",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/car-models": {
"get": {
"description": "Return CarModels Lookup",
"tags": [
"Lookup"
],
"summary": "Return CarModels Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/cup-categories": {
"get": {
"description": "Return CupCategories Lookup",
"tags": [
"Lookup"
],
"summary": "Return CupCategories Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/driver-categories": {
"get": {
"description": "Return DriverCategories Lookup",
"tags": [
"Lookup"
],
"summary": "Return DriverCategories Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/session-types": {
"get": {
"description": "Return SessionTypes Lookup",
"tags": [
"Lookup"
],
"summary": "Return SessionTypes Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/tracks": {
"get": {
"description": "Return Tracks Lookup",
"tags": [
"Lookup"
],
"summary": "Return Tracks Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/server": {
"get": {
"description": "Return Servers",
"tags": [
"Server"
],
"summary": "Return Servers",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/server/{id}/config": {
"get": {
"description": "Return Config files",
"tags": [
"Config"
],
"summary": "Return Configs",
"parameters": [
{
"type": "number",
"description": "required",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/server/{id}/config/{file}": {
"get": {
"description": "Returns Config file",
"tags": [
"Config"
],
"summary": "Return Config file",
"parameters": [
{
"type": "number",
"description": "required",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "required",
"name": "file",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
},
"put": {
"description": "Updates config",
"tags": [
"Config"
],
"summary": "Update config",
"parameters": [
{
"type": "number",
"description": "required",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "required",
"name": "file",
"in": "path",
"required": true
},
{
"description": "required",
"name": "content",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
}
}`
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = &swag.Spec{
Version: "",
Host: "",
BasePath: "",
Schemes: []string{},
Title: "",
Description: "",
InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate,
LeftDelim: "{{",
RightDelim: "}}",
}
func init() {
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
}

View File

@@ -1,378 +0,0 @@
{
"swagger": "2.0",
"info": {
"contact": {}
},
"paths": {
"/v1/api": {
"get": {
"description": "Return API",
"tags": [
"api"
],
"summary": "Return API",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/api/restart": {
"post": {
"description": "Restarts service",
"tags": [
"api"
],
"summary": "Restart service",
"parameters": [
{
"description": "required",
"name": "name",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/api/start": {
"post": {
"description": "Starts service",
"tags": [
"api"
],
"summary": "Start service",
"parameters": [
{
"description": "required",
"name": "name",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/api/stop": {
"post": {
"description": "Stops service",
"tags": [
"api"
],
"summary": "Stop service",
"parameters": [
{
"description": "required",
"name": "name",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/api/{service}": {
"get": {
"description": "Returns service status",
"tags": [
"api"
],
"summary": "Return service status",
"parameters": [
{
"type": "string",
"description": "required",
"name": "service",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/car-models": {
"get": {
"description": "Return CarModels Lookup",
"tags": [
"Lookup"
],
"summary": "Return CarModels Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/cup-categories": {
"get": {
"description": "Return CupCategories Lookup",
"tags": [
"Lookup"
],
"summary": "Return CupCategories Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/driver-categories": {
"get": {
"description": "Return DriverCategories Lookup",
"tags": [
"Lookup"
],
"summary": "Return DriverCategories Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/session-types": {
"get": {
"description": "Return SessionTypes Lookup",
"tags": [
"Lookup"
],
"summary": "Return SessionTypes Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/lookup/tracks": {
"get": {
"description": "Return Tracks Lookup",
"tags": [
"Lookup"
],
"summary": "Return Tracks Lookup",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/server": {
"get": {
"description": "Return Servers",
"tags": [
"Server"
],
"summary": "Return Servers",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/server/{id}/config": {
"get": {
"description": "Return Config files",
"tags": [
"Config"
],
"summary": "Return Configs",
"parameters": [
{
"type": "number",
"description": "required",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
},
"/v1/server/{id}/config/{file}": {
"get": {
"description": "Returns Config file",
"tags": [
"Config"
],
"summary": "Return Config file",
"parameters": [
{
"type": "number",
"description": "required",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "required",
"name": "file",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
},
"put": {
"description": "Updates config",
"tags": [
"Config"
],
"summary": "Update config",
"parameters": [
{
"type": "number",
"description": "required",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "required",
"name": "file",
"in": "path",
"required": true
},
{
"description": "required",
"name": "content",
"in": "body",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
}
}

View File

@@ -1,246 +0,0 @@
info:
contact: {}
paths:
/v1/api:
get:
description: Return API
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return API
tags:
- api
/v1/api/{service}:
get:
description: Returns service status
parameters:
- description: required
in: path
name: service
required: true
type: string
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return service status
tags:
- api
/v1/api/restart:
post:
description: Restarts service
parameters:
- description: required
in: body
name: name
required: true
schema:
type: string
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Restart service
tags:
- api
/v1/api/start:
post:
description: Starts service
parameters:
- description: required
in: body
name: name
required: true
schema:
type: string
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Start service
tags:
- api
/v1/api/stop:
post:
description: Stops service
parameters:
- description: required
in: body
name: name
required: true
schema:
type: string
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Stop service
tags:
- api
/v1/lookup/car-models:
get:
description: Return CarModels Lookup
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return CarModels Lookup
tags:
- Lookup
/v1/lookup/cup-categories:
get:
description: Return CupCategories Lookup
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return CupCategories Lookup
tags:
- Lookup
/v1/lookup/driver-categories:
get:
description: Return DriverCategories Lookup
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return DriverCategories Lookup
tags:
- Lookup
/v1/lookup/session-types:
get:
description: Return SessionTypes Lookup
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return SessionTypes Lookup
tags:
- Lookup
/v1/lookup/tracks:
get:
description: Return Tracks Lookup
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return Tracks Lookup
tags:
- Lookup
/v1/server:
get:
description: Return Servers
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return Servers
tags:
- Server
/v1/server/{id}/config:
get:
description: Return Config files
parameters:
- description: required
in: path
name: id
required: true
type: number
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return Configs
tags:
- Config
/v1/server/{id}/config/{file}:
get:
description: Returns Config file
parameters:
- description: required
in: path
name: id
required: true
type: number
- description: required
in: path
name: file
required: true
type: string
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Return Config file
tags:
- Config
put:
description: Updates config
parameters:
- description: required
in: path
name: id
required: true
type: number
- description: required
in: path
name: file
required: true
type: string
- description: required
in: body
name: content
required: true
schema:
type: string
responses:
"200":
description: OK
schema:
items:
type: string
type: array
summary: Update config
tags:
- Config
swagger: "2.0"

View File

@@ -1,822 +0,0 @@
# API Documentation for ACC Server Manager
## Overview
The ACC Server Manager provides a comprehensive REST API for managing Assetto Corsa Competizione dedicated servers. This API enables full control over server instances, configurations, user management, and monitoring through HTTP endpoints.
## Base URL
```
http://localhost:3000/api/v1
```
## Authentication
All API endpoints (except public ones) require authentication via JWT tokens.
### Authentication Header
```http
Authorization: Bearer <your-jwt-token>
```
### Token Expiration
- Default token lifetime: 24 hours
- Tokens should be refreshed before expiration
- Failed authentication returns HTTP 401
## Rate Limiting
The API implements multiple layers of rate limiting:
- **Global**: 100 requests per minute per IP
- **Authentication**: 5 attempts per 15 minutes per IP
- **API Endpoints**: 60 requests per minute per IP
Rate limit exceeded responses return HTTP 429 with retry information.
## Response Format
All API responses follow a consistent JSON format:
### Success Response
```json
{
"success": true,
"data": {
// Response data
},
"message": "Operation completed successfully"
}
```
### Error Response
```json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human readable error message",
"details": {}
}
}
```
## HTTP Status Codes
| Status Code | Description |
|-------------|-------------|
| 200 | OK - Request successful |
| 201 | Created - Resource created successfully |
| 400 | Bad Request - Invalid request data |
| 401 | Unauthorized - Authentication required |
| 403 | Forbidden - Insufficient permissions |
| 404 | Not Found - Resource not found |
| 409 | Conflict - Resource already exists |
| 422 | Unprocessable Entity - Validation failed |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error - Server error |
## API Endpoints
### Authentication
#### Login
```http
POST /api/v1/auth/login
```
**Request Body:**
```json
{
"username": "string",
"password": "string"
}
```
**Response:**
```json
{
"success": true,
"data": {
"token": "jwt-token-string",
"user": {
"id": "uuid",
"username": "string",
"role": {
"id": "uuid",
"name": "string",
"permissions": []
}
}
}
}
```
#### Register User
```http
POST /api/v1/auth/register
```
*Requires: `user.create` permission*
**Request Body:**
```json
{
"username": "string",
"password": "string",
"roleId": "uuid"
}
```
#### Get Current User
```http
GET /api/v1/auth/me
```
*Requires: Authentication*
**Response:**
```json
{
"success": true,
"data": {
"id": "uuid",
"username": "string",
"role": {
"id": "uuid",
"name": "string",
"permissions": []
}
}
}
```
### Server Management
#### List Servers
```http
GET /api/v1/servers
```
*Requires: `server.read` permission*
**Query Parameters:**
- `page` (integer): Page number (default: 1)
- `limit` (integer): Items per page (default: 10)
- `search` (string): Search term
- `status` (string): Filter by status (running, stopped, error)
**Response:**
```json
{
"success": true,
"data": {
"servers": [
{
"id": 1,
"name": "string",
"ip": "string",
"port": 9600,
"path": "string",
"serviceName": "string",
"status": "string",
"dateCreated": "2024-01-01T00:00:00Z"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 50,
"pages": 5
}
}
}
```
#### Create Server
```http
POST /api/v1/servers
```
*Requires: `server.create` permission*
**Request Body:**
```json
{
"name": "string",
"ip": "string",
"port": 9600,
"path": "string"
}
```
**Response:**
```json
{
"success": true,
"data": {
"id": 1,
"name": "string",
"ip": "string",
"port": 9600,
"path": "string",
"serviceName": "string",
"status": "created",
"dateCreated": "2024-01-01T00:00:00Z"
}
}
```
#### Get Server Details
```http
GET /api/v1/servers/{id}
```
*Requires: `server.read` permission*
**Path Parameters:**
- `id` (integer): Server ID
**Response:**
```json
{
"success": true,
"data": {
"id": 1,
"name": "string",
"ip": "string",
"port": 9600,
"path": "string",
"serviceName": "string",
"status": "string",
"dateCreated": "2024-01-01T00:00:00Z",
"configs": [],
"statistics": {}
}
}
```
#### Update Server
```http
PUT /api/v1/servers/{id}
```
*Requires: `server.update` permission*
**Path Parameters:**
- `id` (integer): Server ID
**Request Body:**
```json
{
"name": "string",
"ip": "string",
"port": 9600,
"path": "string"
}
```
#### Delete Server
```http
DELETE /api/v1/servers/{id}
```
*Requires: `server.delete` permission*
**Path Parameters:**
- `id` (integer): Server ID
#### Start Server
```http
POST /api/v1/servers/{id}/start
```
*Requires: `server.control` permission*
#### Stop Server
```http
POST /api/v1/servers/{id}/stop
```
*Requires: `server.control` permission*
#### Restart Server
```http
POST /api/v1/servers/{id}/restart
```
*Requires: `server.control` permission*
### Configuration Management
#### Get Configuration File
```http
GET /api/v1/servers/{id}/config/{file}
```
*Requires: `config.read` permission*
**Path Parameters:**
- `id` (integer): Server ID
- `file` (string): Configuration file name (configuration, event, eventRules, settings)
**Response:**
```json
{
"success": true,
"data": {
"file": "configuration",
"content": {},
"lastModified": "2024-01-01T00:00:00Z"
}
}
```
#### Update Configuration File
```http
PUT /api/v1/servers/{id}/config/{file}
```
*Requires: `config.update` permission*
**Path Parameters:**
- `id` (integer): Server ID
- `file` (string): Configuration file name
**Query Parameters:**
- `restart` (boolean): Restart server after update (default: false)
- `override` (boolean): Override validation warnings (default: false)
**Request Body:**
```json
{
"tcpPort": 9600,
"udpPort": 9600,
"maxConnections": 30,
"registerToLobby": 1,
"serverName": "My ACC Server",
"password": "",
"adminPassword": "admin123",
"trackMedalsRequirement": 0,
"safetyRatingRequirement": -1,
"racecraftRatingRequirement": -1,
"configVersion": 1
}
```
#### Validate Configuration
```http
POST /api/v1/servers/{id}/config/{file}/validate
```
*Requires: `config.read` permission*
**Request Body:** Configuration object to validate
**Response:**
```json
{
"success": true,
"data": {
"valid": true,
"errors": [],
"warnings": []
}
}
```
### Steam Integration
#### Get Steam Credentials
```http
GET /api/v1/steam/credentials
```
*Requires: `steam.read` permission*
**Response:**
```json
{
"success": true,
"data": {
"id": 1,
"username": "steam_username",
"dateCreated": "2024-01-01T00:00:00Z",
"lastUpdated": "2024-01-01T00:00:00Z"
}
}
```
#### Update Steam Credentials
```http
PUT /api/v1/steam/credentials
```
*Requires: `steam.update` permission*
**Request Body:**
```json
{
"username": "steam_username",
"password": "steam_password"
}
```
#### Install/Update Server
```http
POST /api/v1/steam/install
```
*Requires: `steam.install` permission*
**Request Body:**
```json
{
"serverId": 1,
"validate": true,
"beta": false
}
```
### User Management
#### List Users
```http
GET /api/v1/users
```
*Requires: `user.read` permission*
**Query Parameters:**
- `page` (integer): Page number
- `limit` (integer): Items per page
- `search` (string): Search term
**Response:**
```json
{
"success": true,
"data": {
"users": [
{
"id": "uuid",
"username": "string",
"role": {
"id": "uuid",
"name": "string"
},
"createdAt": "2024-01-01T00:00:00Z"
}
],
"pagination": {}
}
}
```
#### Create User
```http
POST /api/v1/users
```
*Requires: `user.create` permission*
#### Update User
```http
PUT /api/v1/users/{id}
```
*Requires: `user.update` permission*
#### Delete User
```http
DELETE /api/v1/users/{id}
```
*Requires: `user.delete` permission*
### Role and Permission Management
#### List Roles
```http
GET /api/v1/roles
```
*Requires: `role.read` permission*
#### Create Role
```http
POST /api/v1/roles
```
*Requires: `role.create` permission*
**Request Body:**
```json
{
"name": "string",
"description": "string",
"permissions": ["permission1", "permission2"]
}
```
#### List Permissions
```http
GET /api/v1/permissions
```
*Requires: `permission.read` permission*
**Response:**
```json
{
"success": true,
"data": [
{
"name": "server.create",
"description": "Create new servers",
"category": "server"
}
]
}
```
### Monitoring and Analytics
#### Get Server Statistics
```http
GET /api/v1/servers/{id}/stats
```
*Requires: `stats.read` permission*
**Query Parameters:**
- `from` (string): Start date (ISO 8601)
- `to` (string): End date (ISO 8601)
- `granularity` (string): hour, day, week, month
**Response:**
```json
{
"success": true,
"data": {
"totalPlaytime": 3600,
"playerCount": [],
"sessionTypes": [],
"dailyActivity": [],
"recentSessions": []
}
}
```
#### Get System Health
```http
GET /api/v1/system/health
```
*Public endpoint*
**Response:**
```json
{
"success": true,
"data": {
"status": "healthy",
"version": "1.0.0",
"uptime": 3600,
"database": "connected",
"services": {
"steam": "available",
"nssm": "available"
}
}
}
```
### Lookup Data
#### Get Tracks
```http
GET /api/v1/lookup/tracks
```
*Public endpoint*
**Response:**
```json
{
"success": true,
"data": [
{
"name": "monza",
"uniquePitBoxes": 29,
"privateServerSlots": 60
}
]
}
```
#### Get Car Models
```http
GET /api/v1/lookup/cars
```
*Public endpoint*
#### Get Driver Categories
```http
GET /api/v1/lookup/driver-categories
```
*Public endpoint*
#### Get Cup Categories
```http
GET /api/v1/lookup/cup-categories
```
*Public endpoint*
#### Get Session Types
```http
GET /api/v1/lookup/session-types
```
*Public endpoint*
## Webhooks
The API supports webhook notifications for server events:
### Server Status Changes
```json
{
"event": "server.status.changed",
"serverId": 1,
"serverName": "My Server",
"oldStatus": "stopped",
"newStatus": "running",
"timestamp": "2024-01-01T00:00:00Z"
}
```
### Configuration Updates
```json
{
"event": "server.config.updated",
"serverId": 1,
"serverName": "My Server",
"configFile": "configuration",
"userId": "uuid",
"timestamp": "2024-01-01T00:00:00Z"
}
```
## Error Codes
| Code | Description |
|------|-------------|
| `AUTH_REQUIRED` | Authentication required |
| `AUTH_INVALID` | Invalid credentials |
| `AUTH_EXPIRED` | Token expired |
| `PERMISSION_DENIED` | Insufficient permissions |
| `VALIDATION_FAILED` | Request validation failed |
| `RESOURCE_NOT_FOUND` | Requested resource not found |
| `RESOURCE_EXISTS` | Resource already exists |
| `RATE_LIMIT_EXCEEDED` | Rate limit exceeded |
| `SERVER_ERROR` | Internal server error |
| `SERVICE_UNAVAILABLE` | External service unavailable |
## SDK Examples
### JavaScript/Node.js
```javascript
const axios = require('axios');
class ACCServerManagerAPI {
constructor(baseUrl, token) {
this.baseUrl = baseUrl;
this.token = token;
this.client = axios.create({
baseURL: baseUrl,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
}
async getServers() {
const response = await this.client.get('/servers');
return response.data;
}
async createServer(serverData) {
const response = await this.client.post('/servers', serverData);
return response.data;
}
async updateConfig(serverId, file, config, restart = false) {
const response = await this.client.put(
`/servers/${serverId}/config/${file}?restart=${restart}`,
config
);
return response.data;
}
}
// Usage
const api = new ACCServerManagerAPI('http://localhost:3000/api/v1', 'your-jwt-token');
const servers = await api.getServers();
```
### Python
```python
import requests
class ACCServerManagerAPI:
def __init__(self, base_url, token):
self.base_url = base_url
self.headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
def get_servers(self):
response = requests.get(f'{self.base_url}/servers', headers=self.headers)
return response.json()
def create_server(self, server_data):
response = requests.post(
f'{self.base_url}/servers',
json=server_data,
headers=self.headers
)
return response.json()
# Usage
api = ACCServerManagerAPI('http://localhost:3000/api/v1', 'your-jwt-token')
servers = api.get_servers()
```
### Go
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type ACCServerManagerAPI struct {
BaseURL string
Token string
Client *http.Client
}
func NewACCServerManagerAPI(baseURL, token string) *ACCServerManagerAPI {
return &ACCServerManagerAPI{
BaseURL: baseURL,
Token: token,
Client: &http.Client{},
}
}
func (api *ACCServerManagerAPI) request(method, endpoint string, body interface{}) (*http.Response, error) {
var reqBody bytes.Buffer
if body != nil {
json.NewEncoder(&reqBody).Encode(body)
}
req, err := http.NewRequest(method, api.BaseURL+endpoint, &reqBody)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+api.Token)
req.Header.Set("Content-Type", "application/json")
return api.Client.Do(req)
}
func (api *ACCServerManagerAPI) GetServers() (interface{}, error) {
resp, err := api.request("GET", "/servers", nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result interface{}
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
}
```
## Best Practices
### Authentication
1. Store JWT tokens securely (httpOnly cookies for web apps)
2. Implement token refresh mechanism
3. Handle authentication errors gracefully
4. Use HTTPS in production
### Rate Limiting
1. Implement exponential backoff for rate-limited requests
2. Cache responses when appropriate
3. Use batch operations when available
4. Monitor rate limit headers
### Error Handling
1. Always check response status codes
2. Handle network errors gracefully
3. Implement retry logic for transient errors
4. Log errors for debugging
### Performance
1. Use pagination for large datasets
2. Implement client-side caching
3. Use WebSockets for real-time updates
4. Compress request/response bodies
## Support
For API support:
- **Documentation**: Check this guide and interactive Swagger UI
- **Issues**: Report API bugs via GitHub Issues
- **Community**: Join community discussions for help
- **Professional Support**: Contact maintainers for enterprise support
---
**Note**: This API is versioned. Breaking changes will result in a new API version. Always specify the version in your requests.

View File

@@ -1,182 +0,0 @@
# Caching Implementation for Performance Optimization
This document describes the simple caching implementation added to improve authentication middleware performance in the ACC Server Manager.
## Problem Identified
The authentication middleware was experiencing performance issues due to database queries on every request:
- `HasPermission()` method was hitting the database for every permission check
- User authentication data was being retrieved from database repeatedly
- No caching mechanism for frequently accessed authentication data
## Solution Implemented
### Simple Permission Caching
Added lightweight caching to the authentication middleware using the existing cache infrastructure:
**Location**: `local/middleware/auth.go`
**Key Features**:
- **Permission Result Caching**: Cache permission check results for 10 minutes
- **Existing Cache Integration**: Uses the already available `InMemoryCache` system
- **Minimal Code Changes**: Simple addition to existing middleware without major refactoring
### Implementation Details
#### Cache Key Strategy
```go
cacheKey := fmt.Sprintf("permission:%s:%s", userID, permission)
```
#### Cache Flow
1. **Cache Check First**: Check if permission result exists in cache
2. **Database Fallback**: If cache miss, query database via membership service
3. **Cache Result**: Store result in cache with 10-minute TTL
4. **Return Result**: Return cached or fresh result
#### Core Method
```go
func (m *AuthMiddleware) hasPermissionCached(ctx context.Context, userID, permission string) (bool, error) {
cacheKey := fmt.Sprintf("permission:%s:%s", userID, permission)
// Try cache first
if cached, found := m.cache.Get(cacheKey); found {
if hasPermission, ok := cached.(bool); ok {
return hasPermission, nil
}
}
// Cache miss - check with service
has, err := m.membershipService.HasPermission(ctx, userID, permission)
if err != nil {
return false, err
}
// Cache result for 10 minutes
m.cache.Set(cacheKey, has, 10*time.Minute)
return has, nil
}
```
## Performance Benefits
### Expected Improvements
- **Reduced Database Load**: Permission checks avoid database queries after first access
- **Faster Response Times**: Cached permission lookups are significantly faster
- **Better Scalability**: System can handle more concurrent users with same database load
- **Minimal Memory Overhead**: Only boolean values cached with automatic expiration
### Cache Effectiveness
- **High Hit Ratio Expected**: Users typically access same resources repeatedly
- **10-Minute TTL**: Balances performance with data freshness
- **Per-User Per-Permission**: Granular caching for precise invalidation
## Configuration
### Cache TTL
```go
cacheTTL := 10 * time.Minute // Permission cache duration
```
### Cache Key Format
```go
"permission:{userID}:{permissionName}"
```
Examples:
- `permission:user123:ServerView`
- `permission:user456:ServerCreate`
- `permission:admin789:SystemManage`
## Integration
### Dependencies
- **Existing Cache System**: Uses `local/utl/cache/cache.go`
- **No New Dependencies**: Leverages already available infrastructure
- **Minimal Changes**: Only authentication middleware modified
### Backward Compatibility
- **Transparent Operation**: No changes required to existing controllers
- **Same API**: Permission checking interface remains unchanged
- **Graceful Degradation**: Falls back to database if cache fails
## Usage Examples
### Automatic Caching
```go
// In controller with HasPermission middleware
routeGroup.Get("/servers", auth.HasPermission(model.ServerView), controller.GetServers)
// First request: Database query + cache store
// Subsequent requests (within 10 minutes): Cache hit, no database query
```
### Manual Cache Invalidation
```go
// If needed (currently not implemented but can be added)
auth.InvalidateUserPermissions(userID)
```
## Monitoring
### Built-in Logging
- **Cache Hits**: Debug logs when permission found in cache
- **Cache Misses**: Debug logs when querying database
- **Cache Operations**: Debug logs for cache storage operations
### Log Examples
```
[DEBUG] [AUTH_CACHE] Permission user123:ServerView found in cache: true
[DEBUG] [AUTH_CACHE] Permission user456:ServerCreate cached: true
```
## Maintenance
### Cache Invalidation
- **Automatic Expiration**: 10-minute TTL handles most cases
- **User Changes**: Permission changes take effect after cache expiration
- **Role Changes**: New permissions available after cache expiration
### Memory Management
- **Automatic Cleanup**: Cache system handles expired entry removal
- **Low Memory Impact**: Boolean values have minimal memory footprint
- **Bounded Growth**: TTL prevents unlimited cache growth
## Future Enhancements
### Potential Improvements (if needed)
1. **User Data Caching**: Cache full user objects in addition to permissions
2. **Role-Based Invalidation**: Invalidate cache when user roles change
3. **Configurable TTL**: Make cache duration configurable
4. **Cache Statistics**: Add basic hit/miss ratio logging
### Implementation Considerations
- **Keep It Simple**: Current implementation prioritizes simplicity over features
- **Monitor Performance**: Measure actual performance impact before adding complexity
- **Business Requirements**: Add features only when business case is clear
## Testing
### Recommended Tests
1. **Permission Caching**: Verify permissions are cached correctly
2. **Cache Expiration**: Confirm permissions expire after TTL
3. **Database Fallback**: Ensure database queries work when cache fails
4. **Concurrent Access**: Test cache behavior under concurrent requests
### Performance Testing
- **Before/After Comparison**: Measure response times with and without caching
- **Load Testing**: Verify performance under realistic user loads
- **Database Load**: Monitor database query reduction
## Conclusion
This simple caching implementation provides significant performance benefits with minimal complexity:
- **Solves Core Problem**: Reduces database load for permission checks
- **Simple Implementation**: Uses existing infrastructure without major changes
- **Low Risk**: Minimal code changes reduce chance of introducing bugs
- **Easy Maintenance**: Simple cache strategy is easy to understand and maintain
- **Immediate Benefits**: Performance improvement available immediately
The implementation follows the principle of "simple solutions first" - addressing the performance bottleneck with the minimum viable solution that can be enhanced later if needed.

View File

@@ -1,395 +0,0 @@
# Configuration Guide for ACC Server Manager
## Overview
This guide provides comprehensive information about configuring the ACC Server Manager application, including environment variables, server settings, security configurations, and advanced options.
## 📁 Configuration Files
### Environment Configuration (.env)
The primary configuration is handled through environment variables. Create a `.env` file in the root directory:
```bash
# Copy the example file
cp .env.example .env
```
### Configuration File Hierarchy
1. **Environment Variables** (highest priority)
2. **`.env` file** (medium priority)
3. **Default values** (lowest priority)
## 🔐 Security Configuration
### Required Security Variables
These variables are **mandatory** and the application will not start without them:
```env
# JWT Secret - Used for signing authentication tokens
# Generate with: openssl rand -base64 64
JWT_SECRET=your-super-secure-jwt-secret-minimum-64-characters-long
# Application Secrets - Used for internal encryption and security
# Generate with: openssl rand -hex 32
APP_SECRET=your-32-character-hex-secret-here
APP_SECRET_CODE=your-32-character-hex-secret-code-here
# Encryption Key - Used for AES-256 encryption (MUST be exactly 32 bytes)
# Generate with: openssl rand -hex 32
ENCRYPTION_KEY=your-exactly-32-byte-encryption-key-here
```
## 🌐 Server Configuration
### Basic Server Settings
```env
# HTTP server port
PORT=3000
# CORS allowed origin (comma-separated for multiple origins)
CORS_ALLOWED_ORIGIN=http://localhost:5173
# Database file name (SQLite)
DB_NAME=acc.db
# Default admin password for initial setup (change after first login)
PASSWORD=change-this-default-admin-password
```
**Note**: Most other server configuration options (timeouts, request limits, etc.) are handled by application defaults and don't require environment variables.
## 🗄️ Database Configuration
The application uses SQLite with minimal configuration required:
```env
# Database file name (only setting available via environment)
DB_NAME=acc.db
```
**Note**: Other database settings like connection timeouts, migration settings, and SQL logging are handled internally by the application and don't require environment variables.
## 🎮 Steam Integration
Steam integration settings are managed through the web interface and stored in the database as system configuration. No environment variables are required for Steam integration.
**Configuration via Web Interface:**
- SteamCMD executable path
- NSSM executable path
- Steam credentials (encrypted in database)
- Update schedules and preferences
**Default Values:**
- SteamCMD Path: `c:\steamcmd\steamcmd.exe`
- NSSM Path: `.\nssm.exe`
## 🔥 Windows Service Configuration
Windows service and firewall configurations are handled internally by the application:
**Service Management:**
- NSSM path configured via web interface
- Default service name prefix: `ACC-Server`
- Automatic service creation and management
**Firewall Management:**
- Automatic firewall rule creation
- Default TCP port range: 9600+
- Default UDP port range: 9600+
- Rule cleanup on server deletion
**No environment variables required** - all settings are managed through the system configuration interface.
## 📊 Logging Configuration
Logging is handled internally by the application with sensible defaults:
**Default Logging Behavior:**
- Log level: `info` (adjustable via code)
- Log format: Structured text format
- Log files: Automatic rotation and cleanup
- Security events: Automatically logged
- Error tracking: Comprehensive error logging
**No environment variables required** - logging configuration is built into the application.
## 🚦 Rate Limiting Configuration
Rate limiting is built into the application with secure defaults:
**Built-in Rate Limits:**
- Global: 100 requests per minute per IP
- Authentication: 5 attempts per 15 minutes per IP
- API endpoints: 60 requests per minute per IP
- Configuration updates: Protected with additional limits
**No environment variables required** - rate limiting is automatically applied with appropriate limits for security and performance.
## 📈 Monitoring Configuration
Monitoring features are built into the application:
**Available Monitoring:**
- Health check endpoint: `/health` (always enabled)
- Performance tracking: Built-in performance monitoring
- Error tracking: Automatic error logging and tracking
- Security monitoring: Authentication and authorization events
**No environment variables required** - monitoring is automatically enabled with appropriate defaults.
## 🔄 Backup Configuration
Backup functionality is handled internally:
**Automatic Backups:**
- Database backup before migrations
- Configuration file versioning
- Error recovery mechanisms
**Manual Backups:**
- Database files can be copied manually
- Configuration export/import via web interface
**No environment variables required** - backup features are built into the application workflow.
## 🧪 Development Configuration
### Development Mode Settings
```env
# Enable development mode (NEVER use in production)
DEV_MODE=false
# Enable debug endpoints
DEBUG_ENDPOINTS=false
# Enable hot reload (requires air)
HOT_RELOAD=false
# Disable security features for testing (DANGEROUS)
DISABLE_SECURITY=false
```
### Testing Configuration
```env
# Test database name
TEST_DB_NAME=acc_test.db
# Enable test fixtures
ENABLE_TEST_FIXTURES=false
# Test timeout in seconds
TEST_TIMEOUT=300
```
## 🏭 Production Configuration
### Production Deployment Settings
```env
# Production mode
PRODUCTION=true
# Enable HTTPS enforcement
FORCE_HTTPS=true
# Security-first configuration
SECURITY_STRICT=true
# Disable debug information
DISABLE_DEBUG_INFO=true
# Enable comprehensive monitoring
ENABLE_MONITORING=true
```
### Performance Optimization
```env
# Enable response compression
ENABLE_COMPRESSION=true
# Compression level (1-9)
COMPRESSION_LEVEL=6
# Enable response caching
ENABLE_CACHING=true
# Cache TTL in seconds
CACHE_TTL=300
# Maximum cache size in MB
CACHE_MAX_SIZE=100
```
## 🛠️ Advanced Configuration
### Custom Port Ranges
```env
# Custom TCP port ranges (comma-separated)
CUSTOM_TCP_PORTS=9600-9610,9700-9710
# Custom UDP port ranges (comma-separated)
CUSTOM_UDP_PORTS=9600-9610,9700-9710
# Exclude specific ports (comma-separated)
EXCLUDED_PORTS=9605,9705
```
### Custom Paths
```env
# Custom ACC server installation path
ACC_SERVER_PATH=C:\ACC_Server
# Custom configuration templates path
CONFIG_TEMPLATES_PATH=./templates
# Custom scripts path
SCRIPTS_PATH=./scripts
```
### Integration Settings
```env
# External API endpoints
EXTERNAL_API_ENABLED=false
EXTERNAL_API_URL=https://api.example.com
EXTERNAL_API_KEY=your-api-key-here
# Webhook notifications
WEBHOOK_ENABLED=false
WEBHOOK_URL=https://your-webhook-url.com
WEBHOOK_SECRET=your-webhook-secret
```
## 📋 Configuration Validation
### Validation Rules
The application automatically validates configuration on startup:
1. **Required Variables**: Must be present and non-empty
2. **Numeric Values**: Must be valid numbers within acceptable ranges
3. **File Paths**: Must be accessible and have appropriate permissions
4. **URLs**: Must be valid URL format
5. **Encryption Keys**: Must be exactly 32 bytes for AES-256
### Configuration Errors
Common configuration errors and solutions:
#### "JWT_SECRET must be at least 32 bytes long"
- **Solution**: Generate a longer JWT secret using `openssl rand -base64 64`
#### "ENCRYPTION_KEY must be exactly 32 bytes long"
- **Solution**: Generate a 32-byte key using `openssl rand -hex 32`
#### "Invalid port number"
- **Solution**: Ensure port numbers are between 1 and 65535
#### "SteamCMD not found"
- **Solution**: Install SteamCMD and update the `STEAMCMD_PATH` variable
## 🔧 Configuration Management
### Environment-Specific Configurations
#### Development (.env.development)
```env
DEV_MODE=true
LOG_LEVEL=debug
CORS_ALLOWED_ORIGIN=http://localhost:3000
```
#### Production (.env.production)
```env
PRODUCTION=true
FORCE_HTTPS=true
LOG_LEVEL=warn
SECURITY_STRICT=true
```
#### Testing (.env.test)
```env
DB_NAME=acc_test.db
LOG_LEVEL=error
DISABLE_RATE_LIMITING=true
```
### Configuration Templates
Create configuration templates for common setups:
#### Single Server Setup
```env
# Minimal configuration for single server
PORT=3000
DB_NAME=acc.db
SERVICE_NAME_PREFIX=ACC-Server
```
#### Multi-Server Setup
```env
# Configuration for multiple servers
AUTO_FIREWALL_RULES=true
PORT_RANGE_SIZE=20
SERVICE_START_TIMEOUT=120
```
#### High-Security Setup
```env
# Maximum security configuration
FORCE_HTTPS=true
RATE_LIMIT_AUTH=3
SESSION_TIMEOUT=30
MAX_LOGIN_ATTEMPTS=3
LOCKOUT_DURATION=30
SECURITY_STRICT=true
```
## 🚨 Security Best Practices
### Secret Management
1. **Never commit secrets to version control**
2. **Use environment-specific secret files**
3. **Rotate secrets regularly**
4. **Use secure secret generation methods**
5. **Limit access to configuration files**
### Production Security
1. **Enable HTTPS enforcement**
2. **Configure appropriate CORS origins**
3. **Set up proper rate limiting**
4. **Enable comprehensive logging**
5. **Regular security audits**
## 📞 Configuration Support
### Troubleshooting
For configuration issues:
1. Check the application logs for specific error messages
2. Validate environment variables using the built-in validation
3. Refer to the examples in `.env.example`
4. Test configuration changes in development first
### Getting Help
- **Documentation**: Check this guide and other documentation files
- **Issues**: Report configuration bugs via GitHub Issues
- **Community**: Ask questions in community discussions
- **Professional Support**: Contact maintainers for enterprise support
---
**Note**: Always test configuration changes in a development environment before applying them to production.

View File

@@ -1,691 +0,0 @@
# Deployment Guide for ACC Server Manager
## Overview
This guide provides comprehensive instructions for deploying the ACC Server Manager in various environments, from development to production. It covers security considerations, performance optimization, monitoring setup, and maintenance procedures.
## 🚀 Quick Start Deployment
### Prerequisites Checklist
- [ ] Windows 10/11 or Windows Server 2016+
- [ ] Go 1.23.0 or later installed
- [ ] Administrative privileges
- [ ] Valid Steam account
- [ ] Internet connection for Steam downloads
### Minimum System Requirements
| Component | Minimum | Recommended |
|-----------|---------|-------------|
| **CPU** | 2 cores | 4+ cores |
| **RAM** | 4 GB | 8+ GB |
| **Storage** | 10 GB free | 50+ GB SSD |
| **Network** | 10 Mbps | 100+ Mbps |
## 📦 Installation Methods
### Method 1: Binary Deployment (Recommended)
1. **Download Release Binary**
```bash
# Download the latest release from GitHub
# Extract to your installation directory
cd C:\ACC-Server-Manager
```
2. **Configure Environment**
```bash
copy .env.example .env
# Edit .env with your configuration
```
3. **Generate Secrets**
```bash
# Generate JWT secret
openssl rand -base64 64
# Generate app secrets
openssl rand -hex 32
# Generate encryption key
openssl rand -hex 32
```
4. **Run Application**
```bash
.\acc-server-manager.exe
```
### Method 2: Source Code Deployment
1. **Clone Repository**
```bash
git clone https://github.com/FJurmanovic/acc-server-manager.git
cd acc-server-manager
```
2. **Install Dependencies**
```bash
go mod download
go mod verify
```
3. **Build Application**
```bash
# Development build
go build -o acc-server-manager.exe cmd/api/main.go
# Production build (optimized)
go build -ldflags="-w -s" -o acc-server-manager.exe cmd/api/main.go
```
4. **Configure and Run**
```bash
copy .env.example .env
# Configure your .env file
.\acc-server-manager.exe
```
## 🔧 Environment Configuration
### Production Environment Variables
Create a production `.env` file:
```env
# ========================================
# PRODUCTION CONFIGURATION
# ========================================
# Security (REQUIRED - Generate unique values)
JWT_SECRET=your-production-jwt-secret-64-chars-minimum
APP_SECRET=your-production-app-secret-32-chars
APP_SECRET_CODE=your-production-secret-code-32-chars
ENCRYPTION_KEY=your-production-encryption-key-32-bytes
# Server Configuration
PORT=8080
HOST=0.0.0.0
PRODUCTION=true
FORCE_HTTPS=true
# Database
DB_NAME=acc_production.db
DB_PATH=./data
# CORS (Set to your actual domain)
CORS_ALLOWED_ORIGIN=https://yourdomain.com
# Security Settings
RATE_LIMIT_GLOBAL=1000
RATE_LIMIT_AUTH=10
SESSION_TIMEOUT=120
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION=30
# Steam Configuration
STEAMCMD_PATH=C:\steamcmd\steamcmd.exe
NSSM_PATH=C:\nssm\nssm.exe
# Logging
LOG_LEVEL=warn
LOG_FILE=./logs/production.log
LOG_MAX_SIZE=100
LOG_MAX_FILES=10
# Monitoring
HEALTH_CHECK_ENABLED=true
METRICS_ENABLED=true
PERFORMANCE_MONITORING=true
# Backup
AUTO_BACKUP=true
BACKUP_INTERVAL=12
BACKUP_RETENTION=30
BACKUP_DIR=./backups
```
### Development Environment Variables
```env
# ========================================
# DEVELOPMENT CONFIGURATION
# ========================================
# Security (Use secure values even in dev)
JWT_SECRET=dev-jwt-secret-but-still-secure-64-chars-minimum
APP_SECRET=dev-app-secret-32-chars-here
APP_SECRET_CODE=dev-secret-code-32-chars-here
ENCRYPTION_KEY=dev-encryption-key-32-bytes-here
# Server Configuration
PORT=3000
HOST=localhost
DEV_MODE=true
DEBUG_ENDPOINTS=true
# Database
DB_NAME=acc_dev.db
# CORS
CORS_ALLOWED_ORIGIN=http://localhost:3000,http://localhost:5173
# Relaxed Security (Development Only)
RATE_LIMIT_GLOBAL=1000
DISABLE_SECURITY=false
# Logging
LOG_LEVEL=debug
LOG_COLORS=true
ENABLE_SQL_LOGGING=true
# Development Tools
HOT_RELOAD=true
ENABLE_TEST_FIXTURES=true
```
## 🔒 Security Hardening
### SSL/TLS Configuration
1. **Obtain SSL Certificate**
```bash
# Option 1: Let's Encrypt (Free)
certbot certonly --webroot -w /var/www/html -d yourdomain.com
# Option 2: Commercial Certificate
# Purchase and install certificate from CA
```
2. **Configure Reverse Proxy (Nginx)**
```nginx
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE+AESGCM:ECDHE+AES256:ECDHE+AES128:!aNULL:!MD5:!DSS;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$server_name$request_uri;
}
```
3. **Configure Application for SSL**
```env
FORCE_HTTPS=true
CORS_ALLOWED_ORIGIN=https://yourdomain.com
```
### Firewall Configuration
1. **Windows Firewall Rules**
```powershell
# Allow application through Windows Firewall
New-NetFirewallRule -DisplayName "ACC Server Manager" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow
# Allow ACC server ports (adjust range as needed)
New-NetFirewallRule -DisplayName "ACC Servers TCP" -Direction Inbound -Protocol TCP -LocalPort 9600-9700 -Action Allow
New-NetFirewallRule -DisplayName "ACC Servers UDP" -Direction Inbound -Protocol UDP -LocalPort 9600-9700 -Action Allow
```
2. **Network Security Groups (Azure)**
```json
{
"securityRules": [
{
"name": "AllowHTTPS",
"properties": {
"protocol": "TCP",
"sourcePortRange": "*",
"destinationPortRange": "443",
"sourceAddressPrefix": "*",
"destinationAddressPrefix": "*",
"access": "Allow",
"priority": 1000,
"direction": "Inbound"
}
}
]
}
```
### User Access Control
1. **Create Dedicated Service Account**
```powershell
# Create service account
New-LocalUser -Name "ACCServiceUser" -Description "ACC Server Manager Service Account" -NoPassword
Add-LocalGroupMember -Group "Users" -Member "ACCServiceUser"
# Set permissions on application directory
icacls "C:\ACC-Server-Manager" /grant "ACCServiceUser:(OI)(CI)F"
```
2. **Configure Service Permissions**
```powershell
# Grant service logon rights
secedit /export /cfg security.inf
# Edit security.inf to add ACCServiceUser to SeServiceLogonRight
secedit /configure /db security.sdb /cfg security.inf
```
## 🏗️ Service Installation
### Windows Service with NSSM
1. **Install NSSM**
```bash
# Download NSSM from https://nssm.cc/
# Extract nssm.exe to C:\nssm\
```
2. **Create Service**
```powershell
# Install service
C:\nssm\nssm.exe install "ACCServerManager" "C:\ACC-Server-Manager\acc-server-manager.exe"
# Configure service
C:\nssm\nssm.exe set "ACCServerManager" DisplayName "ACC Server Manager"
C:\nssm\nssm.exe set "ACCServerManager" Description "Assetto Corsa Competizione Server Manager"
C:\nssm\nssm.exe set "ACCServerManager" Start SERVICE_AUTO_START
C:\nssm\nssm.exe set "ACCServerManager" AppDirectory "C:\ACC-Server-Manager"
C:\nssm\nssm.exe set "ACCServerManager" ObjectName ".\ACCServiceUser" "password"
# Configure logging
C:\nssm\nssm.exe set "ACCServerManager" AppStdout "C:\ACC-Server-Manager\logs\service.log"
C:\nssm\nssm.exe set "ACCServerManager" AppStderr "C:\ACC-Server-Manager\logs\service-error.log"
# Start service
C:\nssm\nssm.exe start "ACCServerManager"
```
3. **Service Management**
```powershell
# Check service status
Get-Service -Name "ACCServerManager"
# Start/Stop service
Start-Service -Name "ACCServerManager"
Stop-Service -Name "ACCServerManager"
# Remove service (if needed)
C:\nssm\nssm.exe remove "ACCServerManager" confirm
```
### Systemd Service (Linux/WSL)
```ini
[Unit]
Description=ACC Server Manager
After=network.target
[Service]
Type=simple
User=accmanager
WorkingDirectory=/opt/acc-server-manager
ExecStart=/opt/acc-server-manager/acc-server-manager
Restart=always
RestartSec=10
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
EnvironmentFile=/opt/acc-server-manager/.env
[Install]
WantedBy=multi-user.target
```
## 📊 Monitoring Setup
### Health Check Monitoring
1. **Configure Health Checks**
```env
HEALTH_CHECK_ENABLED=true
HEALTH_CHECK_PATH=/health
HEALTH_CHECK_TIMEOUT=10
```
2. **External Monitoring (UptimeRobot)**
```bash
# Monitor endpoint: https://yourdomain.com/health
# Expected response: 200 OK with JSON health status
```
### Log Management
1. **Log Rotation Configuration**
```env
LOG_MAX_SIZE=100
LOG_MAX_FILES=10
LOG_MAX_AGE=30
```
2. **Centralized Logging (Optional)**
```yaml
# docker-compose.yml for ELK Stack
version: '3'
services:
elasticsearch:
image: elasticsearch:7.14.0
logstash:
image: logstash:7.14.0
kibana:
image: kibana:7.14.0
```
### Performance Monitoring
1. **Enable Metrics**
```env
METRICS_ENABLED=true
METRICS_PORT=9090
PERFORMANCE_MONITORING=true
```
2. **Prometheus Configuration**
```yaml
# prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'acc-server-manager'
static_configs:
- targets: ['localhost:9090']
```
## 🔄 Database Management
### Database Backup Strategy
1. **Automated Backups**
```env
AUTO_BACKUP=true
BACKUP_INTERVAL=12
BACKUP_RETENTION=30
BACKUP_DIR=./backups
BACKUP_COMPRESS=true
```
2. **Manual Backup**
```powershell
# Create manual backup
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
Copy-Item "acc.db" "backups/acc-backup-$timestamp.db"
# Compress backup
Compress-Archive "backups/acc-backup-$timestamp.db" "backups/acc-backup-$timestamp.zip"
```
3. **Backup Verification**
```bash
# Test backup integrity
sqlite3 backup.db "PRAGMA integrity_check;"
```
### Database Migration
1. **Pre-Migration Backup**
```bash
# Always backup before migration
copy acc.db acc-pre-migration-backup.db
```
2. **Migration Process**
```bash
# Migration runs automatically on startup
# Check logs for migration status
tail -f logs/app.log | grep -i migration
```
## 🌐 Load Balancing (High Availability)
### Multiple Instance Setup
1. **Load Balancer Configuration (HAProxy)**
```haproxy
global
daemon
defaults
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend acc_frontend
bind *:80
default_backend acc_servers
backend acc_servers
balance roundrobin
server acc1 10.0.0.10:8080 check
server acc2 10.0.0.11:8080 check
server acc3 10.0.0.12:8080 check
```
2. **Shared Database Setup**
```bash
# Use network-attached storage for database
# Mount shared volume on all instances
net use Z: \\fileserver\acc-shared
```
### Session Clustering
```env
# Redis for session storage
REDIS_URL=redis://localhost:6379
SESSION_STORE=redis
```
## 🔧 Maintenance Procedures
### Regular Maintenance Tasks
1. **Daily Tasks**
```powershell
# Check service status
Get-Service -Name "ACCServerManager"
# Check disk space
Get-WmiObject -Class Win32_LogicalDisk | Select-Object DeviceID, Size, FreeSpace
# Review error logs
Get-Content "logs/error.log" -Tail 50
```
2. **Weekly Tasks**
```powershell
# Update system patches
Install-Module PSWindowsUpdate
Get-WUInstall -AcceptAll -AutoReboot
# Clean old log files
Get-ChildItem "logs\" -Name "*.log.*" | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} | Remove-Item
# Verify backup integrity
sqlite3 backups/latest.db "PRAGMA integrity_check;"
```
3. **Monthly Tasks**
```powershell
# Update dependencies
go get -u ./...
go mod tidy
# Security scan
go install github.com/securecodewarrior/gosec/v2/cmd/gosec@latest
gosec ./...
# Performance review
# Review metrics and optimize based on usage patterns
```
### Update Procedures
1. **Backup Current Installation**
```bash
# Stop service
Stop-Service -Name "ACCServerManager"
# Backup application
Copy-Item -Recurse "C:\ACC-Server-Manager" "C:\ACC-Server-Manager-Backup-$(Get-Date -Format 'yyyyMMdd')"
```
2. **Deploy New Version**
```bash
# Download new version
# Replace executable
# Update configuration if needed
# Start service
Start-Service -Name "ACCServerManager"
```
3. **Rollback Procedure**
```bash
# Stop service
Stop-Service -Name "ACCServerManager"
# Restore backup
Remove-Item -Recurse "C:\ACC-Server-Manager"
Copy-Item -Recurse "C:\ACC-Server-Manager-Backup-$(Get-Date -Format 'yyyyMMdd')" "C:\ACC-Server-Manager"
# Start service
Start-Service -Name "ACCServerManager"
```
## 🐛 Troubleshooting
### Common Issues
1. **Service Won't Start**
```powershell
# Check service status
Get-Service -Name "ACCServerManager"
# Check service logs
Get-Content "logs/service-error.log" -Tail 50
# Check Windows Event Log
Get-EventLog -LogName System -Source "ACCServerManager" -Newest 10
```
2. **Database Connection Issues**
```bash
# Check database file permissions
icacls acc.db
# Test database connection
sqlite3 acc.db ".tables"
# Check for database locks
lsof acc.db # Linux
```
3. **Steam Integration Issues**
```bash
# Verify SteamCMD installation
C:\steamcmd\steamcmd.exe +quit
# Check Steam credentials
# Review Steam-related logs
```
### Performance Issues
1. **High CPU Usage**
```bash
# Check for resource-intensive operations
# Monitor process performance
Get-Process -Name "acc-server-manager" | Select-Object CPU, WorkingSet
```
2. **Memory Leaks**
```bash
# Monitor memory usage over time
# Enable detailed memory profiling
go tool pprof http://localhost:8080/debug/pprof/heap
```
3. **Database Performance**
```sql
-- Analyze database performance
PRAGMA table_info(servers);
EXPLAIN QUERY PLAN SELECT * FROM servers WHERE status = 'running';
```
## 📞 Support and Resources
### Documentation Resources
- [README.md](../README.md) - Getting started guide
- [SECURITY.md](SECURITY.md) - Security guidelines
- [API.md](API.md) - API documentation
- [CONFIGURATION.md](CONFIGURATION.md) - Configuration reference
### Community Support
- **GitHub Issues** - Bug reports and feature requests
- **Discord Community** - Real-time community support
- **Wiki** - Community-maintained documentation
### Professional Support
- **Enterprise Support** - Professional deployment assistance
- **Consulting Services** - Custom implementation and optimization
- **Training** - Team training and best practices
### Emergency Contacts
```
Production Issues: support@yourdomain.com
Security Issues: security@yourdomain.com
Emergency Hotline: +1-XXX-XXX-XXXX
```
## 📋 Deployment Checklist
### Pre-Deployment
- [ ] System requirements verified
- [ ] Dependencies installed
- [ ] Secrets generated and secured
- [ ] Configuration reviewed
- [ ] Security hardening applied
- [ ] Backup strategy implemented
- [ ] Monitoring configured
### Post-Deployment
- [ ] Service running successfully
- [ ] Health checks passing
- [ ] Logs being written correctly
- [ ] Database accessible
- [ ] API endpoints responding
- [ ] Frontend integration working
- [ ] Monitoring alerts configured
- [ ] Documentation updated
### Production Readiness
- [ ] SSL/TLS configured
- [ ] Firewall rules applied
- [ ] Performance monitoring active
- [ ] Backup procedures tested
- [ ] Update procedures documented
- [ ] Disaster recovery plan created
- [ ] Team training completed
---
**Remember**: Always test deployments in a staging environment before applying to production!

View File

@@ -1,406 +0,0 @@
# ACC Server Manager
A comprehensive web-based management system for Assetto Corsa Competizione (ACC) dedicated servers. This application provides a modern, secure interface for managing multiple ACC server instances with advanced features like automated Steam integration, firewall management, and real-time monitoring.
## 🚀 Features
### Core Server Management
- **Multi-Server Support**: Manage multiple ACC server instances from a single interface
- **Configuration Management**: Web-based configuration editor with validation
- **Service Integration**: Windows Service management via NSSM
- **Port Management**: Automatic port allocation and firewall rule creation
- **Real-time Monitoring**: Live server status and performance metrics
### Steam Integration
- **Automated Installation**: Automatic ACC server installation via SteamCMD
- **Credential Management**: Secure Steam credential storage with AES-256 encryption
- **Update Management**: Automated server updates and maintenance
### Security Features
- **JWT Authentication**: Secure token-based authentication system
- **Role-Based Access**: Granular permission system with user roles
- **Rate Limiting**: Protection against brute force and DoS attacks
- **Input Validation**: Comprehensive input sanitization and validation
- **Security Headers**: OWASP-compliant security headers
- **Password Security**: Bcrypt password hashing with strength validation
### Monitoring & Analytics
- **State History**: Track server state changes and player activity
- **Performance Metrics**: Server performance and usage statistics
- **Activity Logs**: Comprehensive logging and audit trails
- **Dashboard**: Real-time overview of all managed servers
## 🏗️ Architecture
### Technology Stack
- **Backend**: Go 1.23.0 with Fiber web framework
- **Database**: SQLite with GORM ORM
- **Authentication**: JWT tokens with bcrypt password hashing
- **API Documentation**: Swagger/OpenAPI integration
- **Dependency Injection**: Uber Dig container
### Project Structure
```
acc-server-manager/
├── cmd/
│ └── api/ # Application entry point
├── local/
│ ├── api/ # API route definitions
│ ├── controller/ # HTTP request handlers
│ ├── middleware/ # Authentication and security middleware
│ ├── model/ # Database models and business logic
│ ├── repository/ # Data access layer
│ ├── service/ # Business logic services
│ └── utl/ # Utilities and shared components
│ ├── cache/ # Caching utilities
│ ├── command/ # Command execution utilities
│ ├── common/ # Common utilities
│ ├── configs/ # Configuration management
│ ├── db/ # Database connection and migration
│ ├── jwt/ # JWT token management
│ ├── logging/ # Logging utilities
│ ├── network/ # Network utilities
│ ├── password/ # Password hashing utilities
│ ├── regex_handler/ # Regular expression utilities
│ ├── server/ # HTTP server configuration
│ └── tracking/ # Server state tracking
├── docs/ # Documentation
├── logs/ # Application logs
└── vendor/ # Go dependencies
```
## 📋 Prerequisites
### System Requirements
- **Operating System**: Windows 10/11 or Windows Server 2016+
- **Go**: Version 1.23.0 or later
- **SteamCMD**: For ACC server installation and updates
- **NSSM**: Non-Sucking Service Manager for Windows services
- **PowerShell**: Version 5.0 or later
### Dependencies
- ACC Dedicated Server files
- Valid Steam account (for server installation)
- Administrative privileges (for service and firewall management)
## ⚙️ Installation
### 1. Clone the Repository
```bash
git clone <repository-url>
cd acc-server-manager
```
### 2. Install Dependencies
```bash
go mod download
```
### 3. Generate Environment Configuration
We provide scripts to automatically generate secure secrets and create your `.env` file:
**Windows (PowerShell):**
```powershell
.\scripts\generate-secrets.ps1
```
**Linux/macOS (Bash):**
```bash
./scripts/generate-secrets.sh
```
**Manual Setup:**
If you prefer to set up manually:
```bash
copy .env.example .env
```
Then generate secure secrets:
```bash
# JWT Secret (64 bytes, base64 encoded)
openssl rand -base64 64
# Application secrets (32 bytes, hex encoded)
openssl rand -hex 32
# Encryption key (16 bytes, hex encoded = 32 characters)
openssl rand -hex 16
```
Edit `.env` with your generated secrets:
```env
# Security Settings (REQUIRED)
JWT_SECRET=your-generated-jwt-secret-here
APP_SECRET=your-generated-app-secret-here
APP_SECRET_CODE=your-generated-secret-code-here
ENCRYPTION_KEY=your-generated-32-character-hex-key
# Core Application Settings
PORT=3000
CORS_ALLOWED_ORIGIN=http://localhost:5173
DB_NAME=acc.db
PASSWORD=change-this-default-admin-password
```
### 4. Build the Application
```bash
go build -o api.exe cmd/api/main.go
```
### 5. Run the Application
```bash
./api.exe
```
The application will be available at `http://localhost:3000`
## 🔧 Configuration
### Environment Variables
The application uses minimal environment variables, with most settings managed through the web interface:
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `JWT_SECRET` | Yes | - | JWT signing secret (64+ chars, base64) |
| `APP_SECRET` | Yes | - | Application secret key (32 bytes, hex) |
| `APP_SECRET_CODE` | Yes | - | Application secret code (32 bytes, hex) |
| `ENCRYPTION_KEY` | Yes | - | AES-256 encryption key (32 hex chars) |
| `PORT` | No | 3000 | HTTP server port |
| `DB_NAME` | No | acc.db | SQLite database filename |
| `CORS_ALLOWED_ORIGIN` | No | http://localhost:5173 | CORS allowed origin |
| `PASSWORD` | No | - | Default admin password for initial setup |
**⚠️ Important**: All required secrets are automatically generated by the provided scripts in `scripts/` directory.
### System Configuration (Web Interface)
Advanced settings are managed through the web interface and stored in the database:
- **Steam Integration**: SteamCMD path and credentials
- **Service Management**: NSSM path and service settings
- **Server Settings**: Default ports, firewall rules
- **Security Policies**: Rate limits, session timeouts
- **Monitoring**: Logging levels, performance tracking
- **Backup Settings**: Automatic backup configuration
Access these settings through the admin panel after initial setup.
## 🔒 Security
This application implements comprehensive security measures:
### Authentication & Authorization
- **JWT Tokens**: Secure token-based authentication
- **Password Security**: Bcrypt hashing with strength validation
- **Role-Based Access**: Granular permission system
- **Session Management**: Configurable timeouts and lockouts
### Protection Mechanisms
- **Rate Limiting**: Multiple layers of rate limiting
- **Input Validation**: Comprehensive input sanitization
- **Security Headers**: OWASP-compliant HTTP headers
- **CORS Protection**: Configurable cross-origin restrictions
- **Request Limits**: Size and timeout limitations
### Monitoring & Logging
- **Security Events**: Authentication and authorization logging
- **Audit Trail**: Comprehensive activity logging
- **Threat Detection**: Suspicious activity monitoring
For detailed security information, see [SECURITY.md](docs/SECURITY.md).
## 📚 API Documentation
The application includes comprehensive API documentation via Swagger UI:
- **Local Development**: http://localhost:3000/swagger/
- **Interactive Testing**: Test API endpoints directly from the browser
- **Schema Documentation**: Complete request/response schemas
### Key API Endpoints
#### Authentication
- `POST /api/v1/auth/login` - User authentication
- `POST /api/v1/auth/register` - User registration
- `GET /api/v1/auth/me` - Get current user
#### Server Management
- `GET /api/v1/servers` - List all servers
- `POST /api/v1/servers` - Create new server
- `GET /api/v1/servers/{id}` - Get server details
- `PUT /api/v1/servers/{id}` - Update server
- `DELETE /api/v1/servers/{id}` - Delete server
#### Configuration
- `GET /api/v1/servers/{id}/config/{file}` - Get configuration file
- `PUT /api/v1/servers/{id}/config/{file}` - Update configuration
- `POST /api/v1/servers/{id}/restart` - Restart server
## 🖥️ Frontend Integration
This backend is designed to work with a modern web frontend. Recommended stack:
- **React/Vue/Angular**: Modern JavaScript framework
- **TypeScript**: Type safety and better development experience
- **Axios/Fetch**: HTTP client for API communication
- **WebSocket**: Real-time server status updates
### CORS Configuration
Configure `CORS_ALLOWED_ORIGIN` to match your frontend URL:
```env
CORS_ALLOWED_ORIGIN=http://localhost:3000,https://yourdomain.com
```
## 🛠️ Development
### Running in Development Mode
```bash
# Install air for hot reloading (optional)
go install github.com/cosmtrek/air@latest
# Run with hot reload
air
# Or run directly with go
go run cmd/api/main.go
```
### Database Management
```bash
# View database schema
sqlite3 acc.db ".schema"
# Backup database
copy acc.db acc_backup.db
```
### Testing
```bash
# Run all tests
go test ./...
# Run tests with coverage
go test -cover ./...
# Run specific test package
go test ./local/service/...
```
## 🚀 Production Deployment
### 1. Generate Production Secrets
```bash
# Use the secret generation script for production
.\scripts\generate-secrets.ps1 # Windows
./scripts/generate-secrets.sh # Linux/macOS
```
### 2. Build for Production
```bash
# Build optimized binary
go build -ldflags="-w -s" -o acc-server-manager.exe cmd/api/main.go
```
### 3. Security Checklist
- [ ] Generate unique production secrets (use provided scripts)
- [ ] Configure production CORS origins in `.env`
- [ ] Change default admin password immediately after first login
- [ ] Enable HTTPS with valid certificates
- [ ] Set up proper firewall rules
- [ ] Configure system paths via web interface
- [ ] Set up monitoring and alerting
- [ ] Test all security configurations
### 3. Service Installation
```bash
# Create Windows service using NSSM
nssm install "ACC Server Manager" "C:\path\to\acc-server-manager.exe"
nssm set "ACC Server Manager" DisplayName "ACC Server Manager"
nssm set "ACC Server Manager" Description "Assetto Corsa Competizione Server Manager"
nssm start "ACC Server Manager"
```
### 4. Monitoring Setup
- Configure log rotation
- Set up health check monitoring
- Configure alerting for critical errors
- Monitor resource usage and performance
## 🔧 Troubleshooting
### Common Issues
#### "JWT_SECRET environment variable is required"
**Solution**: Set the JWT_SECRET environment variable with a secure 32+ character string.
#### "Failed to connect database"
**Solution**: Ensure the application has write permissions to the database directory.
#### "SteamCMD not found"
**Solution**: Install SteamCMD and update the `STEAMCMD_PATH` environment variable.
#### "Permission denied creating firewall rule"
**Solution**: Run the application as Administrator for firewall management.
### Log Locations
- **Application Logs**: `./logs/app.log`
- **Error Logs**: `./logs/error.log`
- **Security Logs**: `./logs/security.log`
### Debug Mode
Enable debug logging:
```env
LOG_LEVEL=debug
DEBUG_MODE=true
```
## 🤝 Contributing
### Development Setup
1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Make your changes and add tests
4. Ensure all tests pass: `go test ./...`
5. Commit your changes: `git commit -m 'Add amazing feature'`
6. Push to the branch: `git push origin feature/amazing-feature`
7. Open a Pull Request
### Code Style
- Follow Go best practices and conventions
- Use `gofmt` for code formatting
- Add comprehensive comments for public functions
- Include tests for new functionality
### Security Considerations
- Never commit secrets or credentials
- Follow secure coding practices
- Test security features thoroughly
- Report security issues privately
## 📝 License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## 🙏 Acknowledgments
- **Fiber Framework**: High-performance HTTP framework
- **GORM**: Powerful ORM for Go
- **Assetto Corsa Competizione**: The amazing racing simulation
- **Community**: Contributors and users who make this project possible
## 📞 Support
### Documentation
- [Security Guide](docs/SECURITY.md)
- [API Documentation](http://localhost:3000/swagger/)
- [Configuration Guide](docs/CONFIGURATION.md)
### Community
- **Issues**: Report bugs and request features via GitHub Issues
- **Discussions**: Join community discussions
- **Wiki**: Community-maintained documentation and guides
### Professional Support
For professional support, consulting, or custom development, please contact the maintainers.
---
**Happy Racing! 🏁**

View File

@@ -1,147 +0,0 @@
# Environment Variables Configuration
This document describes the environment variables used by the ACC Server Manager to replace the previous database-based system configuration.
## Overview
The `system_configs` database table has been completely removed and replaced with environment variables for better configuration management and deployment flexibility.
## Environment Variables
### STEAMCMD_PATH
**Description:** Path to the SteamCMD executable
**Default:** `c:\steamcmd\steamcmd.exe`
**Example:** `STEAMCMD_PATH=D:\tools\steamcmd\steamcmd.exe`
This path is used for:
- Installing ACC dedicated servers
- Updating server files
- Managing Steam-based server installations
### NSSM_PATH
**Description:** Path to the NSSM (Non-Sucking Service Manager) executable
**Default:** `.\nssm.exe`
**Example:** `NSSM_PATH=C:\tools\nssm\win64\nssm.exe`
This path is used for:
- Creating Windows services for ACC servers
- Managing service lifecycle (start, stop, restart)
- Service configuration and management
## Setting Environment Variables
### Windows Command Prompt
```cmd
set STEAMCMD_PATH=D:\tools\steamcmd\steamcmd.exe
set NSSM_PATH=C:\tools\nssm\win64\nssm.exe
```
### Windows PowerShell
```powershell
$env:STEAMCMD_PATH = "D:\tools\steamcmd\steamcmd.exe"
$env:NSSM_PATH = "C:\tools\nssm\win64\nssm.exe"
```
### System Environment Variables (Persistent)
1. Open System Properties → Advanced → Environment Variables
2. Add new system variables:
- Variable name: `STEAMCMD_PATH`
- Variable value: `D:\tools\steamcmd\steamcmd.exe`
3. Repeat for `NSSM_PATH`
### Docker Environment
```dockerfile
ENV STEAMCMD_PATH=/opt/steamcmd/steamcmd.sh
ENV NSSM_PATH=/usr/local/bin/nssm
```
### Docker Compose
```yaml
environment:
- STEAMCMD_PATH=/opt/steamcmd/steamcmd.sh
- NSSM_PATH=/usr/local/bin/nssm
```
## Migration from system_configs
### Automatic Migration
A migration script (`003_remove_system_configs.sql`) will automatically:
1. Remove the `system_configs` table
2. Clean up related database references
3. Record the migration in `migration_records`
### Manual Configuration Required
After upgrading, you must set the environment variables based on your previous system configuration:
1. Check your previous configuration (if you had custom paths):
```sql
SELECT key, value, default_value FROM system_configs;
```
2. Set environment variables accordingly:
- If you used custom `steamcmd_path`: Set `STEAMCMD_PATH`
- If you used custom `nssm_path`: Set `NSSM_PATH`
3. Restart the ACC Server Manager service
### Validation
The application will use default values if environment variables are not set. To validate your configuration:
1. Check the application logs on startup
2. The `env.ValidatePaths()` function can be used to verify paths exist
3. Monitor for any "failed to get path" errors in logs
## Benefits of Environment Variables
### Deployment Flexibility
- Different environments can have different tool paths
- No database dependency for basic configuration
- Container-friendly configuration
### Security
- Sensitive paths not stored in database
- Environment-specific configuration
- Better separation of configuration from data
### Performance
- No database queries for basic path lookups
- Reduced database load on every operation
- Faster service startup
## Troubleshooting
### Common Issues
**Issue:** SteamCMD operations fail
**Solution:** Verify `STEAMCMD_PATH` points to valid steamcmd.exe
**Issue:** Service creation fails
**Solution:** Verify `NSSM_PATH` points to valid nssm.exe
**Issue:** Using default paths
**Solution:** Set environment variables and restart application
### Debugging
Enable debug logging to see which paths are being used:
```
2024-01-01 12:00:00 DEBUG Using SteamCMD path: D:\tools\steamcmd\steamcmd.exe
2024-01-01 12:00:00 DEBUG Using NSSM path: C:\tools\nssm\win64\nssm.exe
```
## Code Changes Summary
### Removed Components
- `local/model/config.go` - SystemConfig struct and related constants
- `local/service/system_config_service.go` - SystemConfigService
- `local/repository/system_config_repository.go` - SystemConfigRepository
- Database table: `system_configs`
### Added Components
- `local/utl/env/env.go` - Environment variable utilities
- Migration script: `003_remove_system_configs.sql`
### Modified Services
- **SteamService**: Now uses `env.GetSteamCMDPath()`
- **WindowsService**: Now uses `env.GetNSSMPath()`
- **ServerService**: Removed SystemConfigService dependency
- **ApiService**: Removed SystemConfigService dependency

View File

@@ -1,255 +0,0 @@
# Implementation Summary
## Completed Tasks
### 1. UUID Migration Scripts ✅
**Created comprehensive migration system to convert integer primary keys to UUIDs:**
- **Migration SQL Script**: `scripts/migrations/002_migrate_servers_to_uuid.sql`
- Migrates servers table from integer to UUID primary key
- Updates all foreign key references in configs and state_histories tables
- Migrates steam_credentials and system_configs tables
- Preserves all existing data while maintaining referential integrity
- Uses SQLite-compatible UUID generation functions
- **Go Migration Handler**: `local/migrations/002_migrate_to_uuid.go`
- Wraps SQL migration with Go logic
- Includes migration tracking and error handling
- Integrates with existing migration system
- **Migration Runner**: `scripts/run_migrations.go`
- Standalone utility to run migrations
- Automatic database detection
- Migration status reporting
- Error handling and rollback support
### 2. Enhanced Role System ✅
**Implemented comprehensive role-based access control:**
- **Three Predefined Roles**:
- **Super Admin**: Full access to all features, cannot be deleted
- **Admin**: Full access to all features, can be deleted
- **Manager**: Limited access (cannot create/delete servers, users, roles, memberships)
- **Permission System**:
- Granular permissions for all operations
- Service-level permission validation
- Role-permission many-to-many relationships
- **Backend Updates**:
- Updated `MembershipService.SetupInitialData()` to create all three roles
- Added `MembershipService.GetAllRoles()` method
- Enhanced `MembershipRepository` with `ListRoles()` method
- Added `/membership/roles` API endpoint in controller
### 3. Super Admin Protection ✅
**Added validation to prevent Super Admin user deletion:**
- Modified `MembershipService.DeleteUser()` to check user role
- Returns error "cannot delete Super Admin user" when attempting to delete Super Admin
- Maintains system integrity by ensuring at least one Super Admin exists
### 4. Frontend Role Dropdown ✅
**Replaced text input with dropdown for role selection:**
- **API Service Updates**:
- Added `getRoles()` method to `membershipService.ts`
- Defined `Role` interface for type safety
- Both server-side and client-side implementations
- **Page Updates**:
- Modified `+page.server.ts` to fetch roles data
- Updated load function to include roles in page data
- **UI Updates**:
- Replaced role text input with select dropdown in `+page.svelte`
- Populates dropdown with available roles from API
- Improved user experience with consistent role selection
### 5. Database Integration ✅
**Integrated migrations into application startup:**
- Updated `local/utl/db/db.go` to run migrations automatically
- Added migration runner function
- Non-blocking migration execution with error logging
- Maintains backward compatibility
### 6. Comprehensive Testing ✅
**Created test suite to verify all functionality:**
- **Test Script**: `scripts/test_migrations.go`
- Creates temporary test database
- Simulates old schema with integer IDs
- Runs migration and verifies UUID conversion
- Tests role system functionality
- Validates Super Admin deletion prevention
- Automatic cleanup after testing
### 7. Documentation ✅
**Created comprehensive documentation:**
- **Migration Guide**: `MIGRATION_GUIDE.md`
- Detailed explanation of all changes
- Installation and usage instructions
- Troubleshooting guide
- API documentation
- Security considerations
## Technical Details
### Database Schema Changes
**Before Migration:**
```sql
CREATE TABLE servers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
-- other columns
);
CREATE TABLE configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
server_id INTEGER NOT NULL,
-- other columns
);
```
**After Migration:**
```sql
CREATE TABLE servers (
id TEXT PRIMARY KEY, -- UUID stored as TEXT
name TEXT NOT NULL,
-- other columns
);
CREATE TABLE configs (
id TEXT PRIMARY KEY, -- UUID
server_id TEXT NOT NULL, -- UUID reference
-- other columns
FOREIGN KEY (server_id) REFERENCES servers(id)
);
```
### Role Permission Matrix
| Permission | Super Admin | Admin | Manager |
|------------|------------|-------|---------|
| server.view | ✅ | ✅ | ✅ |
| server.create | ✅ | ✅ | ❌ |
| server.update | ✅ | ✅ | ✅ |
| server.delete | ✅ | ✅ | ❌ |
| server.start | ✅ | ✅ | ✅ |
| server.stop | ✅ | ✅ | ✅ |
| user.view | ✅ | ✅ | ✅ |
| user.create | ✅ | ✅ | ❌ |
| user.update | ✅ | ✅ | ❌ |
| user.delete | ✅ | ✅ | ❌ |
| role.view | ✅ | ✅ | ✅ |
| role.create | ✅ | ✅ | ❌ |
| role.update | ✅ | ✅ | ❌ |
| role.delete | ✅ | ✅ | ❌ |
| membership.view | ✅ | ✅ | ✅ |
| membership.create | ✅ | ✅ | ❌ |
| membership.edit | ✅ | ✅ | ❌ |
| config.view | ✅ | ✅ | ✅ |
| config.update | ✅ | ✅ | ✅ |
### API Endpoints Added
1. **GET /membership/roles**
- Returns list of available roles
- Requires `role.view` permission
- Used by frontend dropdown
### Frontend Changes
1. **Role Selection UI**:
```html
<!-- Before -->
<input type="text" name="role" placeholder="e.g., Admin, User" />
<!-- After -->
<select name="role" required>
<option value="">Select a role...</option>
<option value="Super Admin">Super Admin</option>
<option value="Admin">Admin</option>
<option value="Manager">Manager</option>
</select>
```
2. **TypeScript Interfaces**:
```typescript
export interface Role {
id: string;
name: string;
}
```
## Migration Safety Features
1. **Transaction-based**: All migrations run within database transactions
2. **Backup tables**: Temporary backup tables created during migration
3. **Rollback support**: Failed migrations are automatically rolled back
4. **Idempotent**: Migrations can be safely re-run
5. **Data validation**: Comprehensive validation of migrated data
6. **Foreign key preservation**: All relationships maintained during migration
## Testing Coverage
1. **Unit Tests**: Service and repository layer testing
2. **Integration Tests**: End-to-end migration testing
3. **Permission Tests**: Role-based access control validation
4. **UI Tests**: Frontend dropdown functionality
5. **Data Integrity Tests**: Foreign key relationship validation
## Performance Considerations
1. **Efficient UUID generation**: Uses SQLite-compatible UUID functions
2. **Batch processing**: Minimizes memory usage during migration
3. **Index creation**: Proper indexing on UUID columns
4. **Connection pooling**: Efficient database connection management
## Security Enhancements
1. **Role-based access control**: Granular permission system
2. **Super Admin protection**: Prevents accidental deletion
3. **Input validation**: Secure role selection
4. **Audit trail**: Migration tracking and logging
## Files Created/Modified
### New Files:
- `scripts/migrations/002_migrate_servers_to_uuid.sql`
- `local/migrations/002_migrate_to_uuid.go`
- `scripts/run_migrations.go`
- `scripts/test_migrations.go`
- `MIGRATION_GUIDE.md`
### Modified Files:
- `local/service/membership.go`
- `local/repository/membership.go`
- `local/controller/membership.go`
- `local/utl/db/db.go`
- `acc-server-manager-web/src/api/membershipService.ts`
- `acc-server-manager-web/src/routes/dashboard/membership/+page.server.ts`
- `acc-server-manager-web/src/routes/dashboard/membership/+page.svelte`
## Ready for Production
All requirements have been successfully implemented and tested:
**UUID Migration Scripts** - Complete with foreign key handling
**Super Admin Deletion Prevention** - Service-level validation implemented
**Enhanced Role System** - Admin and Manager roles with proper permissions
**Frontend Dropdown** - Role selection UI improved
**Comprehensive Testing** - Full test suite created
**Documentation** - Detailed guides and API documentation
The system is now ready for deployment with enhanced security, better user experience, and improved database architecture.

View File

@@ -1,275 +0,0 @@
# Logging and Error Handling Implementation Summary
This document summarizes the comprehensive logging and error handling improvements implemented in the ACC Server Manager project.
## Overview
The logging system has been completely refactored to provide:
- **Structured logging** with separate files for each log level
- **Base logger architecture** using shared functionality
- **Centralized error handling** for all controllers
- **Backward compatibility** with existing code
- **Enhanced debugging capabilities**
## Architecture Changes
### New File Structure
```
acc-server-manager/local/utl/logging/
├── base.go # Base logger with core functionality
├── error.go # Error-specific logging methods
├── warn.go # Warning-specific logging methods
├── info.go # Info-specific logging methods
├── debug.go # Debug-specific logging methods
├── logger.go # Main logger for backward compatibility
└── USAGE_EXAMPLES.md # Comprehensive usage documentation
acc-server-manager/local/utl/error_handler/
└── controller_error_handler.go # Centralized controller error handling
acc-server-manager/local/middleware/logging/
└── request_logging.go # HTTP request/response logging middleware
```
## Key Features Implemented
### 1. Structured Logging Architecture
#### Base Logger (`base.go`)
- Singleton pattern for consistent logging across the application
- Thread-safe operations with mutex protection
- Centralized file handling and formatting
- Support for custom caller depth tracking
- Panic recovery with stack trace logging
#### Specialized Loggers
Each log level has its own dedicated file with specialized methods:
**Error Logger (`error.go`)**
- `LogError(err, message)` - Log error objects with optional context
- `LogWithStackTrace()` - Include full stack traces for critical errors
- `LogFatal()` - Log fatal errors that require application termination
- `LogWithContext()` - Add contextual information to error logs
**Info Logger (`info.go`)**
- `LogStartup(component, message)` - Application startup logging
- `LogShutdown(component, message)` - Graceful shutdown logging
- `LogOperation(operation, details)` - Business operation tracking
- `LogRequest/LogResponse()` - HTTP request/response logging
- `LogStatus()` - Status change notifications
**Warn Logger (`warn.go`)**
- `LogDeprecation(feature, alternative)` - Deprecation warnings
- `LogConfiguration(setting, message)` - Configuration issues
- `LogPerformance(operation, threshold, actual)` - Performance warnings
**Debug Logger (`debug.go`)**
- `LogFunction(name, args)` - Function call tracing
- `LogVariable(name, value)` - Variable state inspection
- `LogState(component, state)` - Application state logging
- `LogSQL(query, args)` - Database query logging
- `LogMemory()` - Memory usage monitoring
- `LogGoroutines()` - Goroutine count tracking
- `LogTiming(operation, duration)` - Performance timing
### 2. Centralized Controller Error Handling
#### Controller Error Handler (`controller_error_handler.go`)
A comprehensive error handling system that:
- **Automatically logs all controller errors** with context information
- **Provides standardized HTTP error responses**
- **Includes request metadata** (method, path, IP, user agent)
- **Sanitizes error messages** (removes null bytes, handles internal errors)
- **Categorizes errors** by type for better debugging
#### Available Error Handler Methods:
```go
HandleError(c *fiber.Ctx, err error, statusCode int, context ...string)
HandleValidationError(c *fiber.Ctx, err error, field string)
HandleDatabaseError(c *fiber.Ctx, err error)
HandleAuthError(c *fiber.Ctx, err error)
HandleNotFoundError(c *fiber.Ctx, resource string)
HandleBusinessLogicError(c *fiber.Ctx, err error)
HandleServiceError(c *fiber.Ctx, err error)
HandleParsingError(c *fiber.Ctx, err error)
HandleUUIDError(c *fiber.Ctx, field string)
```
### 3. Request Logging Middleware
#### Features:
- **Automatic request/response logging** for all HTTP endpoints
- **Performance tracking** with request duration measurement
- **User agent tracking** for debugging and analytics
- **Error correlation** between middleware and controller errors
## Implementation Details
### Controllers Updated
All controllers have been updated to use the centralized error handler:
1. **ApiController** (`api.go`)
- Replaced manual error logging with `HandleServiceError()`
- Added proper UUID validation with `HandleUUIDError()`
- Implemented consistent parsing error handling
2. **ServerController** (`server.go`)
- Standardized all error responses
- Added validation error handling for query filters
- Consistent UUID parameter validation
3. **ConfigController** (`config.go`)
- Enhanced error context for configuration operations
- Improved restart operation error handling
- Better parsing error management
4. **LookupController** (`lookup.go`)
- Simplified error handling for lookup operations
- Consistent service error responses
5. **MembershipController** (`membership.go`)
- Enhanced authentication error handling
- Improved user management error responses
- Better UUID validation for user operations
6. **StateHistoryController** (`stateHistory.go`)
- Standardized query filter validation errors
- Consistent service error handling
### Main Application Changes
#### Updated `cmd/api/main.go`:
- Integrated new logging system initialization
- Added application lifecycle logging
- Enhanced startup/shutdown tracking
- Maintained backward compatibility with existing logger
## Usage Examples
### Basic Logging (Backward Compatible)
```go
logging.Info("Server started on port %d", 8080)
logging.Error("Database connection failed: %v", err)
logging.Warn("Configuration missing, using defaults")
logging.Debug("Processing request ID: %s", requestID)
```
### Enhanced Contextual Logging
```go
logging.ErrorWithContext("DATABASE", "Connection pool exhausted: %v", err)
logging.InfoStartup("API_SERVER", "HTTP server listening on :8080")
logging.WarnConfiguration("database.max_connections", "Value too high, reducing to 100")
logging.DebugSQL("SELECT * FROM users WHERE active = ?", true)
```
### Controller Error Handling
```go
func (c *MyController) GetUser(ctx *fiber.Ctx) error {
userID, err := uuid.Parse(ctx.Params("id"))
if err != nil {
return c.errorHandler.HandleUUIDError(ctx, "user ID")
}
user, err := c.service.GetUser(userID)
if err != nil {
return c.errorHandler.HandleServiceError(ctx, err)
}
return ctx.JSON(user)
}
```
## Benefits Achieved
### 1. Comprehensive Error Logging
- **Every controller error is now automatically logged** with full context
- **Standardized error format** across all API endpoints
- **Rich debugging information** including file, line, method, path, and IP
- **Stack traces** for critical errors
### 2. Improved Debugging Capabilities
- **Specialized logging methods** for different types of operations
- **Performance monitoring** with timing and memory usage tracking
- **Database query logging** for optimization
- **Request/response correlation** for API debugging
### 3. Better Code Organization
- **Separation of concerns** with dedicated logger files
- **Consistent error handling** across all controllers
- **Reduced code duplication** in error management
- **Cleaner controller code** with centralized error handling
### 4. Enhanced Observability
- **Structured log output** with consistent formatting
- **Contextual information** for better log analysis
- **Application lifecycle tracking** for operational insights
- **Performance metrics** for optimization opportunities
### 5. Backward Compatibility
- **Existing logging calls continue to work** without modification
- **Gradual migration path** to new features
- **No breaking changes** to existing functionality
## Log Output Format
All logs follow a consistent format:
```
[2024-01-15 10:30:45.123] [LEVEL] [file.go:line] [CONTEXT] Message with details
```
Examples:
```
[2024-01-15 10:30:45.123] [INFO] [server.go:45] [STARTUP] HTTP server started on port 8080
[2024-01-15 10:30:46.456] [ERROR] [database.go:12] [CONTROLLER_ERROR [api.go:67]] [SERVICE] Connection timeout: dial tcp 127.0.0.1:5432: timeout
[2024-01-15 10:30:47.789] [WARN] [config.go:23] [CONFIG] Missing database.max_connections, using default: 50
[2024-01-15 10:30:48.012] [DEBUG] [handler.go:34] [REQUEST] GET /api/v1/servers User-Agent: curl/7.68.0
```
## Migration Impact
### Zero Breaking Changes
- All existing `logging.Info()`, `logging.Error()`, etc. calls continue to work
- No changes required to existing service or repository layers
- Controllers benefit from automatic error logging without code changes
### Immediate Benefits
- **All controller errors are now logged** automatically
- **Better error responses** with consistent format
- **Enhanced debugging** with contextual information
- **Performance insights** through timing logs
## Configuration
### Automatic Setup
- Logs are automatically written to `logs/acc-server-YYYY-MM-DD.log`
- Both console and file output are enabled
- Thread-safe operation across all components
- Automatic log rotation by date
### Customization Options
- Individual logger instances can be created for specific components
- Context information can be added to any log entry
- Error handler behavior can be customized per controller
- Request logging middleware can be selectively applied
## Future Enhancements
The new logging architecture provides a foundation for:
- **Log level filtering** based on environment
- **Structured JSON logging** for log aggregation systems
- **Metrics collection** integration
- **Distributed tracing** correlation
- **Custom log formatters** for different output targets
## Conclusion
This implementation provides a robust, scalable logging and error handling system that:
- **Ensures all controller errors are logged** with rich context
- **Maintains full backward compatibility** with existing code
- **Provides specialized logging capabilities** for different use cases
- **Improves debugging and operational visibility**
- **Establishes a foundation** for future observability enhancements
The system is production-ready and provides immediate benefits while supporting future growth and enhancement needs.

View File

@@ -1,396 +0,0 @@
# Logging System Usage Examples
This document provides comprehensive examples and documentation for using the new structured logging system in the ACC Server Manager.
## Overview
The logging system has been refactored to provide:
- **Structured logging** with separate files for each log level
- **Base logger** providing core functionality
- **Centralized error handling** for controllers
- **Backward compatibility** with existing code
## Architecture
```
logging/
├── base.go # Base logger with core functionality
├── error.go # Error-specific logging
├── warn.go # Warning-specific logging
├── info.go # Info-specific logging
├── debug.go # Debug-specific logging
└── logger.go # Main logger for backward compatibility
```
## Basic Usage
### Simple Logging (Backward Compatible)
```go
import "acc-server-manager/local/utl/logging"
// These work exactly as before
logging.Info("Server started on port %d", 8080)
logging.Error("Failed to connect to database: %v", err)
logging.Warn("Configuration value missing, using default")
logging.Debug("Processing request with ID: %s", requestID)
```
### Enhanced Logging with Context
```go
// Error logging with context
logging.ErrorWithContext("DATABASE", "Connection failed: %v", err)
logging.ErrorWithContext("AUTH", "Invalid credentials for user: %s", username)
// Info logging with context
logging.InfoWithContext("STARTUP", "Service initialized: %s", serviceName)
logging.InfoWithContext("SHUTDOWN", "Gracefully shutting down service: %s", serviceName)
// Warning with context
logging.WarnWithContext("CONFIG", "Missing configuration key: %s", configKey)
// Debug with context
logging.DebugWithContext("REQUEST", "Processing API call: %s", endpoint)
```
### Specialized Logging Functions
```go
// Application lifecycle
logging.LogStartup("DATABASE", "Connection pool initialized")
logging.LogShutdown("API_SERVER", "HTTP server stopped")
// Operations tracking
logging.LogOperation("USER_CREATE", "Created user with ID: " + userID.String())
logging.LogOperation("SERVER_START", "Started ACC server: " + serverName)
// HTTP request/response logging
logging.LogRequest("GET", "/api/v1/servers", "Mozilla/5.0...")
logging.LogResponse("GET", "/api/v1/servers", 200, "15ms")
// Error object logging
logging.LogError(err, "Failed to parse configuration file")
// Performance and debugging
logging.LogSQL("SELECT * FROM servers WHERE active = ?", true)
logging.LogMemory() // Logs current memory usage
logging.LogTiming("database_query", duration)
```
### Direct Logger Instances
```go
// Get specific logger instances for advanced usage
errorLogger := logging.GetErrorLogger()
infoLogger := logging.GetInfoLogger()
debugLogger := logging.GetDebugLogger()
warnLogger := logging.GetWarnLogger()
// Use specific logger methods
errorLogger.LogWithStackTrace("Critical system error occurred")
debugLogger.LogVariable("userConfig", userConfigObject)
debugLogger.LogState("cache", cacheState)
warnLogger.LogDeprecation("OldFunction", "NewFunction")
```
## Controller Error Handling
### Using the Centralized Error Handler
```go
package controller
import (
"acc-server-manager/local/utl/error_handler"
"github.com/gofiber/fiber/v2"
)
type MyController struct {
service *MyService
errorHandler *error_handler.ControllerErrorHandler
}
func NewMyController(service *MyService) *MyController {
return &MyController{
service: service,
errorHandler: error_handler.NewControllerErrorHandler(),
}
}
func (mc *MyController) GetUser(c *fiber.Ctx) error {
userID, err := uuid.Parse(c.Params("id"))
if err != nil {
// Automatically logs error and returns standardized response
return mc.errorHandler.HandleUUIDError(c, "user ID")
}
user, err := mc.service.GetUser(userID)
if err != nil {
// Logs error with context and returns appropriate HTTP status
return mc.errorHandler.HandleServiceError(c, err)
}
return c.JSON(user)
}
func (mc *MyController) CreateUser(c *fiber.Ctx) error {
var user User
if err := c.BodyParser(&user); err != nil {
return mc.errorHandler.HandleParsingError(c, err)
}
if err := mc.service.CreateUser(&user); err != nil {
return mc.errorHandler.HandleServiceError(c, err)
}
return c.JSON(user)
}
```
### Available Error Handler Methods
```go
// Generic error handling
HandleError(c *fiber.Ctx, err error, statusCode int, context ...string)
// Specific error types
HandleValidationError(c *fiber.Ctx, err error, field string)
HandleDatabaseError(c *fiber.Ctx, err error)
HandleAuthError(c *fiber.Ctx, err error)
HandleNotFoundError(c *fiber.Ctx, resource string)
HandleBusinessLogicError(c *fiber.Ctx, err error)
HandleServiceError(c *fiber.Ctx, err error)
HandleParsingError(c *fiber.Ctx, err error)
HandleUUIDError(c *fiber.Ctx, field string)
```
### Global Error Handler Functions
```go
import "acc-server-manager/local/utl/error_handler"
// Use global error handler functions for convenience
func (mc *MyController) SomeEndpoint(c *fiber.Ctx) error {
if err := someOperation(); err != nil {
return error_handler.HandleServiceError(c, err)
}
return c.JSON(result)
}
```
## Request Logging Middleware
### Setup Request Logging
```go
import (
middlewareLogging "acc-server-manager/local/middleware/logging"
)
func setupRoutes(app *fiber.App) {
// Add request logging middleware
app.Use(middlewareLogging.Handler())
// Your routes here...
}
```
This will automatically log:
- Incoming requests with method, URL, and user agent
- Outgoing responses with status code and duration
- Any errors that occur during request processing
## Advanced Usage Examples
### Custom Logger with Specific Configuration
```go
// Create a custom base logger instance
baseLogger, err := logging.InitializeBase()
if err != nil {
log.Fatal("Failed to initialize logger")
}
// Create specialized loggers
errorLogger := logging.NewErrorLogger()
debugLogger := logging.NewDebugLogger()
// Use them directly
errorLogger.LogWithStackTrace("Critical error in payment processing")
debugLogger.LogMemory()
debugLogger.LogGoroutines()
```
### Panic Recovery and Logging
```go
func dangerousOperation() {
defer logging.RecoverAndLog()
// Your potentially panicking code here
// If panic occurs, it will be logged with full stack trace
}
```
### Performance Monitoring
```go
func processRequest() {
start := time.Now()
defer func() {
duration := time.Since(start)
logging.LogTiming("request_processing", duration)
}()
// Log memory usage periodically
logging.LogMemory()
// Your processing logic here
}
```
### Database Query Logging
```go
func (r *Repository) GetUser(id uuid.UUID) (*User, error) {
query := "SELECT * FROM users WHERE id = ?"
logging.LogSQL(query, id)
var user User
err := r.db.Get(&user, query, id)
if err != nil {
logging.ErrorWithContext("DATABASE", "Failed to get user %s: %v", id, err)
return nil, err
}
return &user, nil
}
```
## Migration Guide
### For Existing Code
Your existing logging calls will continue to work:
```go
// These still work exactly as before
logging.Info("Message")
logging.Error("Error: %v", err)
logging.Warn("Warning message")
logging.Debug("Debug info")
```
### Upgrading to New Features
Consider upgrading to new features gradually:
```go
// Instead of:
logging.Error("Database error: %v", err)
// Use:
logging.ErrorWithContext("DATABASE", "Connection failed: %v", err)
// or
logging.LogError(err, "Database connection failed")
```
### Controller Updates
Replace manual error handling:
```go
// Old way:
if err != nil {
logging.Error("Service error: %v", err)
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
}
// New way:
if err != nil {
return mc.errorHandler.HandleServiceError(c, err)
}
```
## Configuration
### Log Levels
The system automatically handles different log levels. All logs are written to the same file but with different level indicators:
```
[2024-01-15 10:30:45.123] [INFO] [server.go:45] Server started successfully
[2024-01-15 10:30:46.456] [ERROR] [database.go:12] Connection failed: timeout
[2024-01-15 10:30:47.789] [WARN] [config.go:67] Using default configuration
[2024-01-15 10:30:48.012] [DEBUG] [handler.go:23] Processing request ID: 12345
```
### File Organization
Logs are automatically organized by date in the `logs/` directory:
- `logs/acc-server-2024-01-15.log`
- `logs/acc-server-2024-01-16.log`
### Output Destinations
All logs are written to both:
- Console (stdout) for development
- Log files for persistence
## Best Practices
1. **Use contextual logging** for better debugging
2. **Use appropriate log levels** (DEBUG for development, INFO for operations, WARN for issues, ERROR for failures)
3. **Use the error handler** in controllers for consistent error responses
4. **Include relevant information** in log messages (IDs, timestamps, etc.)
5. **Avoid logging sensitive information** (passwords, tokens, etc.)
6. **Use structured fields** when possible for better parsing
## Examples by Use Case
### API Controller Logging
```go
func (ac *APIController) CreateServer(c *fiber.Ctx) error {
var server Server
if err := c.BodyParser(&server); err != nil {
return ac.errorHandler.HandleParsingError(c, err)
}
logging.InfoOperation("SERVER_CREATE", fmt.Sprintf("Creating server: %s", server.Name))
if err := ac.service.CreateServer(&server); err != nil {
return ac.errorHandler.HandleServiceError(c, err)
}
logging.InfoOperation("SERVER_CREATE", fmt.Sprintf("Successfully created server: %s (ID: %s)", server.Name, server.ID))
return c.JSON(server)
}
```
### Service Layer Logging
```go
func (s *ServerService) StartServer(serverID uuid.UUID) error {
logging.InfoWithContext("SERVER_SERVICE", "Starting server %s", serverID)
server, err := s.repository.GetServer(serverID)
if err != nil {
logging.ErrorWithContext("SERVER_SERVICE", "Failed to get server %s: %v", serverID, err)
return err
}
logging.DebugState("server_config", server)
if err := s.processManager.Start(server); err != nil {
logging.ErrorWithContext("SERVER_SERVICE", "Failed to start server %s: %v", serverID, err)
return err
}
logging.InfoOperation("SERVER_START", fmt.Sprintf("Server %s started successfully", server.Name))
return nil
}
```
This new logging system provides comprehensive error handling and logging capabilities while maintaining backward compatibility with existing code.

View File

@@ -1,321 +0,0 @@
# ACC Server Manager - Migration and Role System Enhancement Guide
## Overview
This guide documents the comprehensive updates made to the ACC Server Manager, including UUID migrations, enhanced role system, and frontend improvements.
## Changes Made
### 1. Database Migration to UUID Primary Keys
**Problem**: The original database used integer primary keys which could cause issues with scaling and distributed systems.
**Solution**: Migrated all primary keys to UUIDs while preserving data integrity and foreign key relationships.
#### Tables Migrated:
- `servers` - Server configurations
- `configs` - Configuration history
- `state_histories` - Server state tracking
- `steam_credentials` - Steam login credentials
- `system_configs` - System configuration settings
#### Migration Scripts:
- `scripts/migrations/002_migrate_servers_to_uuid.sql` - SQL migration script
- `local/migrations/002_migrate_to_uuid.go` - Go migration handler
- `scripts/run_migrations.go` - Standalone migration runner
- `scripts/test_migrations.go` - Test suite for migrations
### 2. Enhanced Role System
**Problem**: The original system only had "Super Admin" role with limited role management.
**Solution**: Implemented a comprehensive role system with three predefined roles and permission-based access control.
#### New Roles:
1. **Super Admin**
- All permissions
- Cannot be deleted (protected)
- System administrator level access
2. **Admin**
- All permissions (same as Super Admin)
- Can be deleted
- Regular administrative access
3. **Manager**
- Limited permissions
- Cannot create/delete: servers, users, roles, memberships
- Can view and manage existing resources
#### Permission Structure:
```
Server Permissions:
- server.view, server.create, server.update, server.delete
- server.start, server.stop
Configuration Permissions:
- config.view, config.update
User Management Permissions:
- user.view, user.create, user.update, user.delete
Role Management Permissions:
- role.view, role.create, role.update, role.delete
Membership Permissions:
- membership.view, membership.create, membership.edit
```
### 3. Frontend Improvements
**Problem**: Role assignment used a text input field, making it error-prone and inconsistent.
**Solution**: Replaced text input with a dropdown populated from the backend API.
#### Changes:
- Added `/membership/roles` API endpoint
- Updated membership service to fetch available roles
- Modified create user modal to use dropdown selection
- Improved user experience with consistent role selection
### 4. Super Admin Protection
**Problem**: No protection against accidentally deleting the Super Admin user.
**Solution**: Added validation to prevent deletion of users with "Super Admin" role.
#### Implementation:
- Service-level validation in `DeleteUser` method
- Returns error: "cannot delete Super Admin user"
- Maintains system integrity by ensuring at least one Super Admin exists
## Installation and Usage
### Running Migrations
#### Option 1: Automatic Migration (Recommended)
Migrations run automatically when the application starts:
```bash
cd acc-server-manager
go run cmd/api/main.go
```
#### Option 2: Manual Migration
Run migrations manually using the migration script:
```bash
cd acc-server-manager
go run scripts/run_migrations.go [database_path]
```
#### Option 3: Test Migrations
Test the migration process with the test suite:
```bash
cd acc-server-manager
go run scripts/test_migrations.go
```
### Backend API Changes
#### New Endpoints:
1. **Get All Roles**
```
GET /membership/roles
Authorization: Bearer <token>
Required Permission: role.view
Response:
[
{
"id": "uuid",
"name": "Super Admin"
},
{
"id": "uuid",
"name": "Admin"
},
{
"id": "uuid",
"name": "Manager"
}
]
```
2. **Enhanced User Creation**
```
POST /membership
Authorization: Bearer <token>
Required Permission: membership.create
Body:
{
"username": "string",
"password": "string",
"role": "Super Admin|Admin|Manager"
}
```
### Frontend Changes
#### Role Selection Dropdown
The user creation form now includes a dropdown for role selection:
```html
<select name="role" required>
<option value="">Select a role...</option>
<option value="Super Admin">Super Admin</option>
<option value="Admin">Admin</option>
<option value="Manager">Manager</option>
</select>
```
#### Updated API Service
The membership service includes the new `getRoles()` method:
```typescript
async getRoles(event: RequestEvent): Promise<Role[]> {
return await fetchAPIEvent(event, '/membership/roles');
}
```
## Migration Safety
### Backup Strategy
1. **Automatic Backup**: The migration script creates temporary backup tables
2. **Transaction Safety**: All migrations run within database transactions
3. **Rollback Support**: Failed migrations are automatically rolled back
### Data Integrity
- Foreign key relationships are maintained during migration
- Existing data is preserved with new UUID identifiers
- Lookup tables (tracks, car models, etc.) remain unchanged
### Validation
- UUID format validation for all migrated IDs
- Referential integrity checks after migration
- Comprehensive test suite verifies migration success
## Troubleshooting
### Common Issues
1. **Migration Already Applied**
- Error: "UUID migration already applied, skipping"
- Solution: This is normal, migrations are idempotent
2. **Database Lock Error**
- Error: "database is locked"
- Solution: Ensure no other processes are using the database
3. **Permission Denied**
- Error: "failed to execute UUID migration"
- Solution: Check file permissions and disk space
4. **Foreign Key Constraint Error**
- Error: "FOREIGN KEY constraint failed"
- Solution: Verify database integrity before running migration
### Debugging
Enable debug logging to see detailed migration progress:
```bash
# Set environment variable
export DEBUG=true
# Or modify the Go code
logging.Init(true) // Enable debug logging
```
### Recovery
If migration fails:
1. **Restore from backup**: Use the backup files created during migration
2. **Re-run migration**: The migration is idempotent and can be safely re-run
3. **Manual cleanup**: Remove temporary tables and retry
## Testing
### Automated Tests
Run the comprehensive test suite:
```bash
cd acc-server-manager
go run scripts/test_migrations.go
```
### Manual Testing
1. Create test users with different roles
2. Verify permission restrictions work correctly
3. Test Super Admin deletion prevention
4. Confirm frontend dropdown functionality
### Test Database
The test suite creates a temporary database (`test_migrations.db`) that is automatically cleaned up after testing.
## Performance Considerations
### Database Performance
- UUIDs are stored as TEXT in SQLite for compatibility
- Indexes are created on frequently queried UUID columns
- Foreign key constraints ensure referential integrity
### Memory Usage
- Migration process uses temporary tables to minimize memory footprint
- Batch processing for large datasets
- Transaction-based approach reduces memory leaks
## Security Enhancements
### Role-Based Access Control
- Granular permissions for different operations
- Service-level permission validation
- Middleware-based authentication and authorization
### Super Admin Protection
- Prevents accidental deletion of critical users
- Maintains system accessibility
- Audit trail for all user management operations
## Future Enhancements
### Planned Features
1. **Custom Roles**: Allow creation of custom roles with specific permissions
2. **Role Inheritance**: Implement role hierarchy with permission inheritance
3. **Audit Logging**: Track all role and permission changes
4. **Bulk Operations**: Support for bulk user management operations
### Migration Extensions
1. **Data Archival**: Migrate old data to archive tables
2. **Performance Optimization**: Add database-specific optimizations
3. **Incremental Migrations**: Support for partial migrations
## Support
For issues or questions regarding the migration and role system:
1. Check the logs for detailed error messages
2. Review this guide for common solutions
3. Run the test suite to verify system integrity
4. Consult the API documentation for endpoint details
## Changelog
### Version 2.0.0
- ✅ Migrated all primary keys to UUID
- ✅ Added Super Admin, Admin, and Manager roles
- ✅ Implemented permission-based access control
- ✅ Added Super Admin deletion protection
- ✅ Created role selection dropdown in frontend
- ✅ Added comprehensive test suite
- ✅ Improved database migration system
### Version 1.0.0
- Basic user management with Super Admin role
- Integer primary keys
- Text-based role assignment

View File

@@ -1,144 +0,0 @@
# Documentation Index
Welcome to the ACC Server Manager documentation! This comprehensive guide covers all aspects of installation, configuration, usage, and development.
## 📚 Quick Navigation
### 🚀 Getting Started
- **[Detailed README](DETAILED_README.md)** - Complete installation and setup guide
- **[Configuration Guide](CONFIGURATION.md)** - Advanced configuration options
- **[Deployment Guide](DEPLOYMENT.md)** - Production deployment instructions
### 🔒 Security & Authentication
- **[Security Guide](SECURITY.md)** - Security features, best practices, and compliance
- **[API Documentation](API.md)** - Complete API reference with authentication details
### 🔧 Development & Technical
- **[Implementation Summary](IMPLEMENTATION_SUMMARY.md)** - Technical architecture overview
- **[Logging System](LOGGING_IMPLEMENTATION_SUMMARY.md)** - Enhanced logging and error handling
- **[Logging Usage Examples](LOGGING_USAGE_EXAMPLES.md)** - Practical logging implementation guide
### 📈 Migration & Upgrades
- **[Migration Guide](MIGRATION_GUIDE.md)** - General migration procedures
- **[UUID Migration Instructions](UUID_MIGRATION_INSTRUCTIONS.md)** - Database UUID migration guide
## 📋 Documentation Structure
### Core Documentation
| Document | Purpose | Audience |
|----------|---------|----------|
| [Detailed README](DETAILED_README.md) | Complete setup and usage guide | All users |
| [Security Guide](SECURITY.md) | Security features and best practices | Administrators, Developers |
| [Configuration](CONFIGURATION.md) | Advanced configuration options | System administrators |
| [API Documentation](API.md) | Complete API reference | Developers, Integrators |
| [Deployment Guide](DEPLOYMENT.md) | Production deployment | DevOps, System administrators |
### Technical Documentation
| Document | Purpose | Audience |
|----------|---------|----------|
| [Implementation Summary](IMPLEMENTATION_SUMMARY.md) | Technical architecture overview | Developers, Architects |
| [Logging System](LOGGING_IMPLEMENTATION_SUMMARY.md) | Logging and error handling details | Developers |
| [Logging Usage Examples](LOGGING_USAGE_EXAMPLES.md) | Practical logging examples | Developers |
### Migration Documentation
| Document | Purpose | Audience |
|----------|---------|----------|
| [Migration Guide](MIGRATION_GUIDE.md) | General migration procedures | System administrators |
| [UUID Migration Instructions](UUID_MIGRATION_INSTRUCTIONS.md) | Database UUID migration | Developers, DBAs |
## 🎯 Quick Access by Role
### 👤 End Users
1. Start with [Detailed README](DETAILED_README.md) for installation
2. Review [Configuration Guide](CONFIGURATION.md) for setup
3. Check [Security Guide](SECURITY.md) for security best practices
### 🔧 System Administrators
1. [Detailed README](DETAILED_README.md) - Installation and basic setup
2. [Security Guide](SECURITY.md) - Security configuration
3. [Configuration Guide](CONFIGURATION.md) - Advanced configuration
4. [Deployment Guide](DEPLOYMENT.md) - Production deployment
5. [Migration Guide](MIGRATION_GUIDE.md) - System migrations
### 💻 Developers
1. [Implementation Summary](IMPLEMENTATION_SUMMARY.md) - Architecture overview
2. [API Documentation](API.md) - API reference
3. [Logging System](LOGGING_IMPLEMENTATION_SUMMARY.md) - Logging architecture
4. [Logging Usage Examples](LOGGING_USAGE_EXAMPLES.md) - Implementation examples
5. [UUID Migration Instructions](UUID_MIGRATION_INSTRUCTIONS.md) - Database changes
### 🏢 DevOps Engineers
1. [Deployment Guide](DEPLOYMENT.md) - Production deployment
2. [Security Guide](SECURITY.md) - Security configuration
3. [Configuration Guide](CONFIGURATION.md) - Environment setup
4. [Migration Guide](MIGRATION_GUIDE.md) - System migrations
## 🔍 Feature Documentation
### Authentication & Security
- JWT token-based authentication → [Security Guide](SECURITY.md)
- Role-based access control → [Security Guide](SECURITY.md)
- API authentication → [API Documentation](API.md)
### Server Management
- Multi-server configuration → [Configuration Guide](CONFIGURATION.md)
- Steam integration → [Detailed README](DETAILED_README.md)
- Service management → [Deployment Guide](DEPLOYMENT.md)
### Monitoring & Logging
- Centralized error handling → [Logging System](LOGGING_IMPLEMENTATION_SUMMARY.md)
- Usage examples → [Logging Usage Examples](LOGGING_USAGE_EXAMPLES.md)
- Performance monitoring → [Implementation Summary](IMPLEMENTATION_SUMMARY.md)
### Database & Migrations
- Database schema → [Implementation Summary](IMPLEMENTATION_SUMMARY.md)
- UUID migration → [UUID Migration Instructions](UUID_MIGRATION_INSTRUCTIONS.md)
- General migrations → [Migration Guide](MIGRATION_GUIDE.md)
## 📝 Document Status
| Document | Status | Last Updated | Version |
|----------|--------|--------------|---------|
| Detailed README | ✅ Complete | Current | 2.0 |
| Security Guide | ✅ Complete | Current | 1.0 |
| API Documentation | ✅ Complete | Current | 1.0 |
| Configuration Guide | ✅ Complete | Current | 1.0 |
| Deployment Guide | ✅ Complete | Current | 1.0 |
| Implementation Summary | ✅ Complete | Current | 1.0 |
| Logging System | ✅ Complete | Current | 2.0 |
| Logging Usage Examples | ✅ Complete | Current | 2.0 |
| Migration Guide | ✅ Complete | Current | 1.0 |
| UUID Migration Instructions | ✅ Complete | Current | 1.0 |
## 🆘 Support & Help
### Common Issues
- Installation problems → [Detailed README](DETAILED_README.md#troubleshooting)
- Security configuration → [Security Guide](SECURITY.md)
- API integration → [API Documentation](API.md)
- Performance issues → [Logging System](LOGGING_IMPLEMENTATION_SUMMARY.md)
### Development Support
- Architecture questions → [Implementation Summary](IMPLEMENTATION_SUMMARY.md)
- Logging implementation → [Logging Usage Examples](LOGGING_USAGE_EXAMPLES.md)
- Database migrations → [Migration Guide](MIGRATION_GUIDE.md)
### Community Resources
- GitHub Issues for bug reports
- GitHub Discussions for community support
- API documentation at `/swagger/` endpoint
## 🔄 Documentation Updates
This documentation is actively maintained and updated with each release. For the latest version, always refer to the documentation in the main branch.
### Contributing to Documentation
1. Follow the existing documentation structure
2. Use clear, concise language
3. Include practical examples
4. Update this index when adding new documents
5. Maintain cross-references between documents
---
**Need immediate help?** Start with the [Detailed README](DETAILED_README.md) for installation and basic usage, or jump directly to the specific guide for your role above.

View File

@@ -1,264 +0,0 @@
# Security Guide for ACC Server Manager
## Overview
This document outlines the security features, best practices, and requirements for the ACC Server Manager application. Following these guidelines is essential for maintaining a secure deployment.
## 🔐 Authentication & Authorization
### JWT Token Security
- **Secret Key**: Must be at least 32 bytes long and cryptographically secure
- **Token Expiration**: Default 24 hours, configurable via environment
- **Refresh Strategy**: Implement token refresh before expiration
- **Storage**: Store tokens securely (httpOnly cookies recommended for web)
### Password Security
- **Hashing**: Uses bcrypt with cost factor 12
- **Requirements**: Minimum 8 characters, must include uppercase, lowercase, digit, and special character
- **Validation**: Real-time strength validation during registration/update
- **Storage**: Never store plain text passwords
### Rate Limiting
- **Global**: 100 requests per minute per IP
- **Authentication**: 5 attempts per 15 minutes per IP+User-Agent
- **API Endpoints**: 60 requests per minute per IP
- **Customizable**: Configurable via environment variables
## 🛡️ Security Headers
The application automatically sets the following security headers:
- `X-Content-Type-Options: nosniff`
- `X-Frame-Options: DENY`
- `X-XSS-Protection: 1; mode=block`
- `Referrer-Policy: strict-origin-when-cross-origin`
- `Content-Security-Policy: [configured policy]`
- `Permissions-Policy: [restricted permissions]`
## 🔒 Data Protection
### Encryption
- **Algorithm**: AES-256-GCM for sensitive data
- **Key Management**: 32-byte keys from environment variables
- **Usage**: Steam credentials and other sensitive configuration data
### Database Security
- **SQLite**: Default database with file-level security
- **Migrations**: Automatic password security upgrades
- **Backup**: Encrypted backups with retention policies
## 🌐 Network Security
### HTTPS
- **Production**: HTTPS enforced in production environments
- **Certificates**: Use valid SSL/TLS certificates
- **Redirection**: Automatic HTTP to HTTPS redirect
### CORS Configuration
- **Origins**: Configured per environment
- **Headers**: Properly configured for API access
- **Credentials**: Enabled for authenticated requests
### Firewall Rules
- **Automatic**: Creates Windows Firewall rules for server ports
- **Management**: Centralized firewall rule management
- **Cleanup**: Automatic rule removal when servers are deleted
## 🚨 Input Validation & Sanitization
### Request Validation
- **Content-Type**: Validates expected content types
- **Size Limits**: 10MB request body limit
- **User-Agent**: Blocks suspicious user agents
- **Timeout**: 30-second request timeout
### Input Sanitization
- **XSS Prevention**: Removes dangerous HTML/JavaScript patterns
- **SQL Injection**: Uses parameterized queries
- **Path Traversal**: Validates file paths and names
## 📊 Monitoring & Logging
### Security Events
- **Authentication**: All login attempts (success/failure)
- **Authorization**: Permission checks and violations
- **Rate Limiting**: Blocked requests and patterns
- **Suspicious Activity**: Automated threat detection
### Log Security
- **Sensitive Data**: Never logs passwords or tokens
- **Format**: Structured logging with security context
- **Retention**: Configurable log retention policies
- **Access**: Restricted access to log files
## ⚙️ Environment Configuration
### Required Environment Variables
```bash
# Critical Security Settings
JWT_SECRET=<64-character-base64-string>
APP_SECRET=<32-character-hex-string>
APP_SECRET_CODE=<32-character-hex-string>
ENCRYPTION_KEY=<32-character-hex-string>
# Security Features
FORCE_HTTPS=true
RATE_LIMIT_GLOBAL=100
RATE_LIMIT_AUTH=5
SESSION_TIMEOUT=60
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION=15
```
### Secret Generation
Generate secure secrets using:
```bash
# JWT Secret (Base64, 64 bytes)
openssl rand -base64 64
# Application Secrets (Hex, 32 bytes)
openssl rand -hex 32
# Encryption Key (Hex, 32 bytes)
openssl rand -hex 32
```
## 🔄 Security Migrations
### Password Security Upgrade
The application includes an automatic migration that:
1. Upgrades old encrypted passwords to bcrypt hashes
2. Maintains data integrity during the process
3. Provides rollback protection
4. Logs migration status and errors
### Migration Safety
- **Backup**: Automatically creates password backups
- **Validation**: Verifies password strength requirements
- **Recovery**: Handles corrupted or invalid passwords
- **Logging**: Detailed migration logs for auditing
## 🚀 Deployment Security
### Production Checklist
- [ ] Generate unique secrets for production
- [ ] Enable HTTPS with valid certificates
- [ ] Configure appropriate CORS origins
- [ ] Set up proper firewall rules
- [ ] Enable security monitoring and alerting
- [ ] Configure secure backup strategies
- [ ] Review and adjust rate limits
- [ ] Set up log monitoring and analysis
- [ ] Test security configurations
- [ ] Document security procedures
### Container Security (if applicable)
- **Base Images**: Use official, minimal base images
- **User Privileges**: Run as non-root user
- **Secrets**: Use container secret management
- **Network**: Isolate containers appropriately
## 🔍 Security Testing
### Automated Testing
- **Dependencies**: Regular security scanning of dependencies
- **SAST**: Static application security testing
- **DAST**: Dynamic application security testing
- **Penetration Testing**: Regular security assessments
### Manual Testing
- **Authentication Bypass**: Test authentication mechanisms
- **Authorization**: Verify permission controls
- **Input Validation**: Test input sanitization
- **Rate Limiting**: Verify rate limiting effectiveness
## 🚨 Incident Response
### Security Incident Procedures
1. **Detection**: Monitor logs and alerts
2. **Assessment**: Evaluate impact and scope
3. **Containment**: Isolate affected systems
4. **Eradication**: Remove threats and vulnerabilities
5. **Recovery**: Restore normal operations
6. **Lessons Learned**: Document and improve
### Emergency Contacts
- **Security Team**: [Configure your security team contacts]
- **System Administrators**: [Configure admin contacts]
- **Management**: [Configure management contacts]
## 📋 Security Maintenance
### Regular Tasks
- **Weekly**: Review security logs and alerts
- **Monthly**: Update dependencies and security patches
- **Quarterly**: Security configuration review
- **Annually**: Comprehensive security assessment
### Monitoring
- **Failed Logins**: Monitor authentication failures
- **Rate Limit Hits**: Track rate limiting events
- **Error Patterns**: Identify suspicious error patterns
- **Performance**: Monitor for DoS attacks
## 🔗 Additional Resources
### Security Standards
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)
- [CIS Controls](https://www.cisecurity.org/controls/)
### Go Security
- [Go Security Policy](https://golang.org/security)
- [Secure Coding Practices](https://github.com/OWASP/Go-SCP)
### Dependencies
- [Fiber Security](https://docs.gofiber.io/api/middleware/helmet)
- [GORM Security](https://gorm.io/docs/security.html)
## 📞 Support
For security questions or concerns:
- **Security Issues**: Report via private channels
- **Documentation**: Refer to this guide and code comments
- **Updates**: Monitor security advisories for dependencies
## 🔄 Version History
- **v1.0.0**: Initial security implementation
- **v1.1.0**: Added password security migration
- **v1.2.0**: Enhanced rate limiting and monitoring
---
**Important**: This security guide should be reviewed and updated regularly as the application evolves and new security threats emerge.

View File

@@ -1,208 +0,0 @@
# UUID Migration Instructions
## Overview
This guide explains how to migrate your ACC Server Manager database from integer primary keys to UUIDs. This migration is required to update your system with the new role management features and improved database architecture.
## ⚠️ Important: Backup First
**ALWAYS backup your database before running any migration!**
```bash
# Create a backup of your database
copy acc.db acc.db.backup
# or on Linux/Mac
cp acc.db acc.db.backup
```
## Migration Methods
### Option 1: Standalone Migration Tool (Recommended)
Use the dedicated migration tool to safely migrate your database:
```bash
# Navigate to the project directory
cd acc-server-manager
# Build and run the migration tool
go run cmd/migrate/main.go
# Or specify a custom database path
go run cmd/migrate/main.go path/to/your/acc.db
```
**What this does:**
- Checks if migration is needed
- Uses the existing SQL migration script (`scripts/migrations/002_migrate_servers_to_uuid.sql`)
- Safely migrates all tables from integer IDs to UUIDs
- Preserves all existing data and relationships
- Creates migration tracking records
### Option 2: Using the Migration Script
You can also run the standalone migration script:
```bash
cd acc-server-manager
go run scripts/run_migrations.go
```
**Note:** Both migration tools use the same SQL migration file (`scripts/migrations/002_migrate_servers_to_uuid.sql`) to ensure consistency.
## What Gets Migrated
The migration will update these tables to use UUID primary keys:
1. **servers** - Server configurations
2. **configs** - Configuration change history
3. **state_histories** - Server state tracking
4. **steam_credentials** - Steam login credentials
5. **system_configs** - System configuration settings
## Verification
After migration, verify it worked correctly:
1. **Check Migration Status:**
```bash
go run cmd/migrate/main.go
# Should show: "Migration not needed - database already uses UUID primary keys"
```
2. **Check Database Schema:**
```bash
sqlite3 acc.db ".schema servers"
# Should show: CREATE TABLE `servers` (`id` text,...)
```
3. **Start the Application:**
```bash
go run cmd/api/main.go
# Should start without UUID-related errors
```
## Troubleshooting
### Error: "NOT NULL constraint failed"
If you see this error, it means there's a conflict between the old schema and new models. Run the migration tool first:
```bash
# Stop the application if running
# Run migration
go run cmd/migrate/main.go
# Then restart the application
go run cmd/api/main.go
```
### Error: "Database is locked"
Make sure the ACC Server Manager application is not running during migration:
```bash
# Stop any running instances
# Then run migration
go run cmd/migrate/main.go
```
### Error: "Migration failed"
If migration fails:
1. Restore from backup:
```bash
copy acc.db.backup acc.db
```
2. Check database integrity:
```bash
sqlite3 acc.db "PRAGMA integrity_check;"
```
3. Try migration again or contact support
## After Migration
Once migration is complete:
1. **New Role System Available:**
- Super Admin (cannot be deleted)
- Admin (full permissions)
- Manager (limited permissions)
2. **Improved Frontend:**
- Role dropdown in user creation
- Better user management interface
3. **Enhanced Security:**
- Super Admin deletion protection
- Permission-based access control
## Migration Safety Features
- **Transaction-based:** All changes are wrapped in database transactions
- **Rollback support:** Failed migrations are automatically rolled back
- **Data preservation:** All existing data is maintained
- **Idempotent:** Can be safely run multiple times
- **Backup creation:** Temporary backup tables during migration
## Manual Rollback (If Needed)
If you need to rollback manually:
```bash
# Restore from backup
copy acc.db.backup acc.db
# Or if you have the old integer schema SQL:
sqlite3 acc.db < old_schema.sql
```
## Testing Migration
To test the migration on a copy of your database:
```bash
# Create test copy
copy acc.db test.db
# Run migration on test copy
go run cmd/migrate/main.go test.db
# Verify test database works
# If successful, run on real database
```
## Support
If you encounter issues:
1. Check this troubleshooting guide
2. Verify you have a backup
3. Check the application logs for detailed errors
4. Try running the test migration first
## Migration Checklist
- [ ] Application is stopped
- [ ] Database is backed up
- [ ] Migration tool is run successfully
- [ ] Migration verification completed
- [ ] Application starts without errors
- [ ] User management features work correctly
- [ ] Role dropdown functions properly
## Technical Details
The migration:
- Uses the SQL script: `scripts/migrations/002_migrate_servers_to_uuid.sql`
- Converts integer primary keys to UUID (stored as TEXT)
- Updates all foreign key references
- Preserves data integrity and relationships
- Uses SQLite-compatible UUID generation
- Creates proper indexes for performance
- Maintains GORM model compatibility
- Both Go and standalone tools use the same SQL for consistency
This migration is a one-time process that prepares your database for the enhanced role management system and future scalability improvements.

View File

@@ -13,7 +13,7 @@ import (
type ConfigController struct {
service *service.ConfigService
apiService *service.ApiService
apiService *service.ServiceControlService
errorHandler *error_handler.ControllerErrorHandler
}
@@ -25,7 +25,7 @@ type ConfigController struct {
// *Fiber.RouterGroup: Fiber Router Group
// Returns:
// *ConfigController: Controller for "Config" interactions
func NewConfigController(as *service.ConfigService, routeGroups *common.RouteGroups, as2 *service.ApiService, auth *middleware.AuthMiddleware) *ConfigController {
func NewConfigController(as *service.ConfigService, routeGroups *common.RouteGroups, as2 *service.ServiceControlService, auth *middleware.AuthMiddleware) *ConfigController {
ac := &ConfigController{
service: as,
apiService: as2,
@@ -43,13 +43,21 @@ func NewConfigController(as *service.ConfigService, routeGroups *common.RouteGro
// updateConfig returns Config
//
// @Summary Update config
// @Description Updates config
// @Param id path number true "required"
// @Param file path string true "required"
// @Param content body string true "required"
// @Tags Config
// @Success 200 {array} string
// @Summary Update server configuration file
// @Description Update a specific configuration file for an ACC server
// @Tags Server Configuration
// @Accept json
// @Produce json
// @Param id path string true "Server ID (UUID format)"
// @Param file path string true "Config file name (e.g., configuration.json, settings.json, event.json)"
// @Param content body object true "Configuration file content as JSON"
// @Success 200 {object} object{message=string} "Update successful"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid request or JSON format"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
// @Failure 404 {object} error_handler.ErrorResponse "Server or config file not found"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/server/{id}/config/{file} [put]
func (ac *ConfigController) UpdateConfig(c *fiber.Ctx) error {
restart := c.QueryBool("restart")
@@ -73,7 +81,7 @@ func (ac *ConfigController) UpdateConfig(c *fiber.Ctx) error {
}
logging.Info("restart: %v", restart)
if restart {
_, err := ac.apiService.ApiRestartServer(c)
_, err := ac.apiService.ServiceControlRestartServer(c)
if err != nil {
logging.ErrorWithContext("CONFIG_RESTART", "Failed to restart server after config update: %v", err)
}
@@ -84,12 +92,20 @@ func (ac *ConfigController) UpdateConfig(c *fiber.Ctx) error {
// getConfig returns Config
//
// @Summary Return Config file
// @Description Returns Config file
// @Param id path number true "required"
// @Param file path string true "required"
// @Tags Config
// @Success 200 {array} string
// @Summary Get server configuration file
// @Description Retrieve a specific configuration file for an ACC server
// @Tags Server Configuration
// @Accept json
// @Produce json
// @Param id path string true "Server ID (UUID format)"
// @Param file path string true "Config file name (e.g., configuration.json, settings.json, event.json)"
// @Success 200 {object} object "Configuration file content as JSON"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid server ID"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
// @Failure 404 {object} error_handler.ErrorResponse "Server or config file not found"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/server/{id}/config/{file} [get]
func (ac *ConfigController) GetConfig(c *fiber.Ctx) error {
Model, err := ac.service.GetConfig(c)
@@ -101,11 +117,19 @@ func (ac *ConfigController) GetConfig(c *fiber.Ctx) error {
// getConfigs returns Config
//
// @Summary Return Configs
// @Description Return Config files
// @Param id path number true "required"
// @Tags Config
// @Success 200 {array} string
// @Summary List available configuration files
// @Description Get a list of all available configuration files for an ACC server
// @Tags Server Configuration
// @Accept json
// @Produce json
// @Param id path string true "Server ID (UUID format)"
// @Success 200 {array} string "List of available configuration files"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid server ID"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
// @Failure 404 {object} error_handler.ErrorResponse "Server not found"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/server/{id}/config [get]
func (ac *ConfigController) GetConfigs(c *fiber.Ctx) error {
Model, err := ac.service.GetConfigs(c)

View File

@@ -20,9 +20,9 @@ func InitializeControllers(c *dig.Container) {
logging.Panic("unable to initialize auth middleware")
}
err := c.Invoke(NewApiController)
err := c.Invoke(NewServiceControlController)
if err != nil {
logging.Panic("unable to initialize api controller")
logging.Panic("unable to initialize service control controller")
}
err = c.Invoke(NewConfigController)

View File

@@ -37,10 +37,15 @@ func NewLookupController(as *service.LookupService, routeGroups *common.RouteGro
// getTracks returns Tracks
//
// @Summary Return Tracks Lookup
// @Description Return Tracks Lookup
// @Tags Lookup
// @Success 200 {array} string
// @Summary Get available tracks
// @Description Get a list of all available ACC tracks with their identifiers
// @Tags Lookups
// @Accept json
// @Produce json
// @Success 200 {array} object{id=string,name=string} "List of tracks"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/lookup/tracks [get]
func (ac *LookupController) GetTracks(c *fiber.Ctx) error {
result, err := ac.service.GetTracks(c)
@@ -52,10 +57,15 @@ func (ac *LookupController) GetTracks(c *fiber.Ctx) error {
// getCarModels returns CarModels
//
// @Summary Return CarModels Lookup
// @Description Return CarModels Lookup
// @Tags Lookup
// @Success 200 {array} string
// @Summary Get available car models
// @Description Get a list of all available ACC car models with their identifiers
// @Tags Lookups
// @Accept json
// @Produce json
// @Success 200 {array} object{id=string,name=string,class=string} "List of car models"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/lookup/car-models [get]
func (ac *LookupController) GetCarModels(c *fiber.Ctx) error {
result, err := ac.service.GetCarModels(c)
@@ -67,10 +77,15 @@ func (ac *LookupController) GetCarModels(c *fiber.Ctx) error {
// getDriverCategories returns DriverCategories
//
// @Summary Return DriverCategories Lookup
// @Description Return DriverCategories Lookup
// @Tags Lookup
// @Success 200 {array} string
// @Summary Get driver categories
// @Description Get a list of all driver categories (Bronze, Silver, Gold, Platinum)
// @Tags Lookups
// @Accept json
// @Produce json
// @Success 200 {array} object{id=number,name=string,description=string} "List of driver categories"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/lookup/driver-categories [get]
func (ac *LookupController) GetDriverCategories(c *fiber.Ctx) error {
result, err := ac.service.GetDriverCategories(c)
@@ -82,10 +97,15 @@ func (ac *LookupController) GetDriverCategories(c *fiber.Ctx) error {
// getCupCategories returns CupCategories
//
// @Summary Return CupCategories Lookup
// @Description Return CupCategories Lookup
// @Tags Lookup
// @Success 200 {array} string
// @Summary Get cup categories
// @Description Get a list of all available racing cup categories
// @Tags Lookups
// @Accept json
// @Produce json
// @Success 200 {array} object{id=number,name=string} "List of cup categories"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/lookup/cup-categories [get]
func (ac *LookupController) GetCupCategories(c *fiber.Ctx) error {
result, err := ac.service.GetCupCategories(c)
@@ -97,10 +117,15 @@ func (ac *LookupController) GetCupCategories(c *fiber.Ctx) error {
// getSessionTypes returns SessionTypes
//
// @Summary Return SessionTypes Lookup
// @Description Return SessionTypes Lookup
// @Tags Lookup
// @Success 200 {array} string
// @Summary Get session types
// @Description Get a list of all available session types (Practice, Qualifying, Race)
// @Tags Lookups
// @Accept json
// @Produce json
// @Success 200 {array} object{id=string,name=string,code=string} "List of session types"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/lookup/session-types [get]
func (ac *LookupController) GetSessionTypes(c *fiber.Ctx) error {
result, err := ac.service.GetSessionTypes(c)

View File

@@ -51,6 +51,17 @@ func NewMembershipController(service *service.MembershipService, auth *middlewar
}
// Login handles user login.
// @Summary User login
// @Description Authenticate a user and receive a JWT token
// @Tags Authentication
// @Accept json
// @Produce json
// @Param credentials body object{username=string,password=string} true "Login credentials"
// @Success 200 {object} object{token=string} "JWT token"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid request body"
// @Failure 401 {object} error_handler.ErrorResponse "Invalid credentials"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Router /auth/login [post]
func (c *MembershipController) Login(ctx *fiber.Ctx) error {
type request struct {
Username string `json:"username"`
@@ -72,6 +83,20 @@ func (c *MembershipController) Login(ctx *fiber.Ctx) error {
}
// CreateUser creates a new user.
// @Summary Create a new user
// @Description Create a new user account with specified role
// @Tags User Management
// @Accept json
// @Produce json
// @Param user body object{username=string,password=string,role=string} true "User details"
// @Success 200 {object} model.User "Created user details"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid request body"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
// @Failure 409 {object} error_handler.ErrorResponse "User already exists"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /membership [post]
func (mc *MembershipController) CreateUser(c *fiber.Ctx) error {
type request struct {
Username string `json:"username"`
@@ -93,6 +118,17 @@ func (mc *MembershipController) CreateUser(c *fiber.Ctx) error {
}
// ListUsers lists all users.
// @Summary List all users
// @Description Get a list of all registered users
// @Tags User Management
// @Accept json
// @Produce json
// @Success 200 {array} model.User "List of users"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /membership [get]
func (mc *MembershipController) ListUsers(c *fiber.Ctx) error {
users, err := mc.service.ListUsers(c.UserContext())
if err != nil {

View File

@@ -34,10 +34,23 @@ func NewServerController(ss *service.ServerService, routeGroups *common.RouteGro
apiServerRoutes := routeGroups.Api.Group("/server")
apiServerRoutes.Get("/", auth.HasPermission(model.ServerView), ac.GetAllApi)
return ac
}
// GetAll returns Servers
// GetAllApi returns all servers in API format
// @Summary List all servers (API format)
// @Description Get a list of all ACC servers with filtering options
// @Tags Server
// @Accept json
// @Produce json
// @Param filter query model.ServerFilter false "Filter options"
// @Success 200 {array} model.ServerAPI "List of servers"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid filter parameters"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /server [get]
func (ac *ServerController) GetAllApi(c *fiber.Ctx) error {
var filter model.ServerFilter
if err := common.ParseQueryFilter(c, &filter); err != nil {
@@ -53,6 +66,20 @@ func (ac *ServerController) GetAllApi(c *fiber.Ctx) error {
}
return c.JSON(apiServers)
}
// GetAll returns all servers
// @Summary List all servers
// @Description Get a list of all ACC servers with detailed information
// @Tags Server
// @Accept json
// @Produce json
// @Param filter query model.ServerFilter false "Filter options"
// @Success 200 {array} model.Server "List of servers with full details"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid filter parameters"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/server [get]
func (ac *ServerController) GetAll(c *fiber.Ctx) error {
var filter model.ServerFilter
if err := common.ParseQueryFilter(c, &filter); err != nil {
@@ -66,6 +93,19 @@ func (ac *ServerController) GetAll(c *fiber.Ctx) error {
}
// GetById returns a single server by its ID
// @Summary Get server by ID
// @Description Get detailed information about a specific ACC server
// @Tags Server
// @Accept json
// @Produce json
// @Param id path string true "Server ID (UUID format)"
// @Success 200 {object} model.Server "Server details"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid server ID format"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 404 {object} error_handler.ErrorResponse "Server not found"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/server/{id} [get]
func (ac *ServerController) GetById(c *fiber.Ctx) error {
serverIDStr := c.Params("id")
serverID, err := uuid.Parse(serverIDStr)
@@ -81,6 +121,19 @@ func (ac *ServerController) GetById(c *fiber.Ctx) error {
}
// CreateServer creates a new server
// @Summary Create a new ACC server
// @Description Create a new ACC server instance with the provided configuration
// @Tags Server
// @Accept json
// @Produce json
// @Param server body model.Server true "Server configuration"
// @Success 200 {object} object "Created server details"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid server data"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/server [post]
func (ac *ServerController) CreateServer(c *fiber.Ctx) error {
server := new(model.Server)
if err := c.BodyParser(server); err != nil {
@@ -94,6 +147,21 @@ func (ac *ServerController) CreateServer(c *fiber.Ctx) error {
}
// UpdateServer updates an existing server
// @Summary Update an ACC server
// @Description Update configuration for an existing ACC server
// @Tags Server
// @Accept json
// @Produce json
// @Param id path string true "Server ID (UUID format)"
// @Param server body model.Server true "Updated server configuration"
// @Success 200 {object} object "Updated server details"
// @Failure 400 {object} error_handler.ErrorResponse "Invalid server data or ID"
// @Failure 401 {object} error_handler.ErrorResponse "Unauthorized"
// @Failure 403 {object} error_handler.ErrorResponse "Insufficient permissions"
// @Failure 404 {object} error_handler.ErrorResponse "Server not found"
// @Failure 500 {object} error_handler.ErrorResponse "Internal server error"
// @Security BearerAuth
// @Router /v1/server/{id} [put]
func (ac *ServerController) UpdateServer(c *fiber.Ctx) error {
serverIDStr := c.Params("id")
serverID, err := uuid.Parse(serverIDStr)

View File

@@ -72,7 +72,7 @@ type State struct {
}
type ServerState struct {
sync.RWMutex
sync.RWMutex `swaggerignore:"-" json:"-"`
Session string `json:"session"`
SessionStart time.Time `json:"sessionStart"`
PlayerCount int `json:"playerCount"`

View File

@@ -1,256 +1,54 @@
# ACC Server Manager Deployment Scripts
# Scripts
This directory contains scripts and tools for deploying the ACC Server Manager to a Windows server.
This directory contains utility scripts for ACC Server Manager.
## Overview
## Setup Script
The deployment process automates the following steps:
1. Build the application binaries for Windows
2. Copy binaries to the target server
3. Stop the Windows service
4. Backup current deployment
5. Deploy new binaries
6. Run database migrations
7. Start the Windows service
8. Verify deployment success
### generate-secrets.ps1 (Windows PowerShell)
## Files
- `deploy.ps1` - Main PowerShell deployment script
- `deploy.bat` - Batch file wrapper for easier execution
- `deploy.config.example` - Configuration template
- `README.md` - This documentation
## Prerequisites
### Local Machine (Build Environment)
- Go 1.23 or later
- PowerShell (Windows PowerShell 5.1+ or PowerShell Core 7+)
- SSH client (OpenSSH recommended)
- SCP utility
### Target Windows Server
- Windows Server 2016 or later
- PowerShell 5.1 or later
- SSH Server (OpenSSH Server or similar)
- ACC Server Manager Windows service configured
## Setup
### 1. Configure SSH Access
Ensure SSH access to your Windows server:
Generates secure random secrets for the application and creates a `.env` file.
**Usage:**
```powershell
# On Windows Server, install OpenSSH Server
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
.\generate-secrets.ps1
```
### 2. Create Deployment Configuration
This script:
- Generates a 64-byte JWT secret
- Generates 32-byte application secrets
- Generates a 32-character encryption key
- Creates a `.env` file with all required configuration
Copy the configuration template and customize it:
### generate-secrets.sh (Linux/macOS)
Same functionality for Unix-like systems.
**Usage:**
```bash
./generate-secrets.sh
```
## Manual Secret Generation
If you prefer to generate secrets manually:
```bash
cp deploy.config.example deploy.config
# Edit deploy.config with your server details
# JWT Secret (64 bytes, base64 encoded)
openssl rand -base64 64
# Application secrets (32 bytes, hex encoded)
openssl rand -hex 32
# Encryption key (16 bytes = 32 hex characters)
openssl rand -hex 16
```
### 3. Set Up Windows Service
Ensure the ACC Server Manager is installed as a Windows service on the target server. You can use tools like NSSM or create a native Windows service.
## Usage
### Option 1: Using Batch Script (Recommended)
```batch
# Basic deployment
deploy.bat 192.168.1.100 admin "C:\AccServerManager"
# With additional options
deploy.bat 192.168.1.100 admin "C:\AccServerManager" -SkipTests
# Test deployment (dry run)
deploy.bat 192.168.1.100 admin "C:\AccServerManager" -WhatIf
Then create `.env` file with:
```env
JWT_SECRET=your-jwt-secret
APP_SECRET=your-app-secret
APP_SECRET_CODE=your-app-secret-code
ENCRYPTION_KEY=your-32-char-hex-key
PORT=3000
DB_NAME=acc.db
```
### Option 2: Using PowerShell Script Directly
```powershell
# Basic deployment
.\deploy.ps1 -ServerHost "192.168.1.100" -ServerUser "admin" -DeployPath "C:\AccServerManager"
# With custom service name
.\deploy.ps1 -ServerHost "192.168.1.100" -ServerUser "admin" -DeployPath "C:\AccServerManager" -ServiceName "MyAccService"
# Skip tests and build
.\deploy.ps1 -ServerHost "192.168.1.100" -ServerUser "admin" -DeployPath "C:\AccServerManager" -SkipTests -SkipBuild
# Dry run
.\deploy.ps1 -ServerHost "192.168.1.100" -ServerUser "admin" -DeployPath "C:\AccServerManager" -WhatIf
```
### Option 3: Using GitHub Actions
The CI/CD pipeline automatically deploys when changes are pushed to the main branch. Configure the following secrets in your GitHub repository:
- `WINDOWS_SERVER_HOST` - Server hostname or IP
- `WINDOWS_SERVER_USER` - SSH username
- `WINDOWS_SERVER_SSH_KEY` - SSH private key
- `DEPLOY_PATH` - Deployment directory on server
- `SLACK_WEBHOOK_URL` - (Optional) Slack webhook for notifications
## Parameters
### Required Parameters
- `ServerHost` - Target Windows server hostname or IP address
- `ServerUser` - Username for SSH connection
- `DeployPath` - Full path where the application will be deployed
### Optional Parameters
- `ServiceName` - Windows service name (default: "ACC Server Manager")
- `BinaryName` - Main binary name (default: "acc-server-manager")
- `MigrateBinaryName` - Migration binary name (default: "acc-migrate")
- `SkipBuild` - Skip the build process
- `SkipTests` - Skip running tests
- `WhatIf` - Show what would be done without executing
## Deployment Process Details
### 1. Build Phase
- Runs Go tests (unless `-SkipTests` is specified)
- Builds API binary for Windows (GOOS=windows, GOARCH=amd64)
- Builds migration tool for Windows
- Creates binaries in `.\build` directory
### 2. Pre-deployment
- Copies binaries to server's temporary directory
- Creates deployment script on server
### 3. Deployment
- Stops the Windows service
- Creates backup of current deployment
- Copies new binaries to deployment directory
- Runs database migrations
- Starts the Windows service
- Verifies service is running
### 4. Rollback (if deployment fails)
- Restores from backup
- Restarts service with previous version
- Reports failure
### 5. Cleanup
- Removes temporary files
- Keeps last 5 backups (configurable)
## Troubleshooting
### Common Issues
#### SSH Connection Failed
```
Test-NetConnection -ComputerName <server> -Port 22
```
Ensure SSH server is running and accessible.
#### Service Not Found
Verify the service name matches exactly:
```powershell
Get-Service -Name "ACC Server Manager"
```
#### Permission Denied
Ensure the SSH user has permissions to:
- Stop/start the service
- Write to the deployment directory
- Execute PowerShell scripts
#### Build Failures
Check Go version and dependencies:
```bash
go version
go mod tidy
go test ./...
```
### Debug Mode
Run with verbose output:
```powershell
$VerbosePreference = "Continue"
.\deploy.ps1 -ServerHost "..." -ServerUser "..." -DeployPath "..." -Verbose
```
### Log Files
Deployment logs are stored in:
- Local: PowerShell transcript files
- Remote: Windows Event Log (Application log)
## Security Considerations
1. **SSH Keys**: Use SSH key authentication instead of passwords
2. **Service Account**: Run the service with minimal required permissions
3. **Firewall**: Restrict SSH access to deployment machines only
4. **Backup Encryption**: Consider encrypting backup files
5. **Secrets Management**: Use secure storage for configuration files
## Customization
### Custom Migration Scripts
Place custom migration scripts in the `scripts/migrations` directory. They will be executed in alphabetical order.
### Pre/Post Deployment Hooks
Configure custom scripts in the deployment configuration:
```ini
PreDeployScript=scripts/pre-deploy.ps1
PostDeployScript=scripts/post-deploy.ps1
```
### Environment Variables
Set environment variables during deployment:
```ini
EnvironmentVariables=ENV=production,LOG_LEVEL=info
```
## Monitoring and Notifications
### Slack Notifications
Configure Slack webhook URL to receive deployment notifications:
```ini
SlackWebhookUrl=https://hooks.slack.com/services/YOUR/WEBHOOK/URL
```
### Health Checks
Configure health check endpoint to verify deployment:
```ini
HealthCheckUrl=http://localhost:8080/health
HealthCheckTimeout=60
```
## Best Practices
1. **Test deployments** in a staging environment first
2. **Use the `-WhatIf` flag** to preview changes
3. **Monitor service logs** after deployment
4. **Keep backups** of working deployments
5. **Use version tagging** for releases
6. **Document configuration changes**
7. **Test rollback procedures** regularly
## Support
For issues with deployment scripts:
1. Check the troubleshooting section
2. Review deployment logs
3. Verify server prerequisites
4. Test SSH connectivity manually
5. Check Windows service configuration
For application-specific issues, refer to the main project documentation.

1648
swagger/docs.go Normal file

File diff suppressed because it is too large Load Diff

1628
swagger/swagger.json Normal file

File diff suppressed because it is too large Load Diff

1045
swagger/swagger.yaml Normal file

File diff suppressed because it is too large Load Diff