Files
fitness/DEPLOYMENT_GUIDE.md
T
2026-10-04 00:19:45 +03:00

464 lines
15 KiB
Markdown

# Fitness Tracking App - Production Deployment Guide
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────┐
│ Flutter Mobile App │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ GetX Controller (State Management) │ │
│ │ - WorkoutController: Orchestrates tracking logic │ │
│ │ - LocationService: SQLite background storage │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────┴──────────────────────────────┐ │
│ │ Views & UI Components │ │
│ │ - WorkoutTrackingScreen: MapLibre map + stats │ │
│ │ - Real-time GPS overlay on MapLibre │ │
│ │ - Polyline encoding for route submission │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────┴──────────────────┐ │
│ │ HMAC-SHA256 Signature Generator │ │
│ └─────────────────┬──────────────────┘ │
│ ▼ │
└───────────────────────────────────────────────────────────────┘
│ HTTPS
│ HMAC-SHA256 Authenticated
▼
┌───────────────────────────────────────────────────────────────┐
│ PHP Backend (REST API) │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Authentication Layer │ │
│ │ - HMAC-SHA256 Signature Verification │ │
│ │ - Timestamp Validation (Replay Attack Prevention) │ │
│ │ - Rate Limiting & API Key Management │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────┴──────────────────────────────┐ │
│ │ /api/v1/workouts (POST) │ │
│ │ - WorkoutValidator: Validates payload structure │ │
│ │ - PolylineUtility: Decodes & validates routes │ │
│ │ - Database: Stores workouts & coordinates │ │
│ └─────────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────────┐
│ MySQL Database │
│ ┌──────────────┐ ┌─────────────┐ ┌──────────────────┐ │
│ │ users │ │ workouts │ │ api_logs │ │
│ │ - id │ │ - id │ │ - user_id │ │
│ │ - api_key │ │ - distance │ │ - endpoint │ │
│ │ - api_secret│ │ - polyline │ │ - status_code │ │
│ └──────────────┘ │ - duration │ └──────────────────┘ │
│ │ - calories │ │
│ │ - metadata │ │
│ └─────────────┘ │
└───────────────────────────────────────────────────────────────┘
```
## Backend Setup Instructions
### 1. Database Initialization
```bash
# Connect to MySQL server
mysql -u root -p
# Execute the schema creation
source backend/schema.sql
# Verify tables were created
USE fitness_app;
SHOW TABLES;
```
### 2. Database User Configuration
```sql
-- Create dedicated database user
CREATE USER 'fitness_app_user'@'localhost' IDENTIFIED BY 'your_secure_password_here';
-- Grant privileges
GRANT SELECT, INSERT, UPDATE, DELETE ON fitness_app.* TO 'fitness_app_user'@'localhost';
GRANT CREATE, ALTER ON fitness_app.* TO 'fitness_app_user'@'localhost';
FLUSH PRIVILEGES;
```
### 3. Update PHP Configuration
Edit `backend/Database.php`:
```php
private $db_host = 'your-db-host.com';
private $db_user = 'fitness_app_user';
private $db_pass = 'your_secure_password_here';
private $db_name = 'fitness_app';
private $db_port = 3306;
```
### 4. Deploy PHP Files
```bash
# Copy PHP files to web server
cp backend/*.php /var/www/html/api/v1/
# Set permissions
chmod 644 /var/www/html/api/v1/*.php
chown www-data:www-data /var/www/html/api/v1/
```
### 5. Configure Web Server (Apache or Nginx)
**Apache (.htaccess)**
```apache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /api/v1/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
# Enable HTTPS only
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /path/to/cert.crt
SSLCertificateKeyFile /path/to/key.key
# ... additional SSL config
</VirtualHost>
```
**Nginx**
```nginx
server {
listen 443 ssl http2;
server_name api.fitness-app.com;
ssl_certificate /path/to/cert.crt;
ssl_certificate_key /path/to/key.key;
ssl_protocols TLSv1.2 TLSv1.3;
location /api/v1/ {
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite ^/api/v1/(.*)$ /api/v1/index.php?url=$1 last;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
```
## Mobile Setup Instructions
### 1. Flutter Project Setup
```bash
# Create Flutter project
flutter create fitness_tracker
# Navigate to project
cd fitness_tracker
# Replace pubspec.yaml
cp mobile/pubspec.yaml ./
# Get dependencies
flutter pub get
```
### 2. Install Dependencies
```bash
# All dependencies are specified in pubspec.yaml
flutter pub get
# For iOS
cd ios && pod install && cd ..
# For Android - ensure minimum SDK is 21
# Check android/app/build.gradle:
# minSdkVersion 21
# targetSdkVersion 34
```
### 3. Set MapLibre Tile Server
Update `mobile/workout_tracking_screen.dart`:
```dart
MapLibreMap(
styleString: 'https://map-saas.intaleqapp.com/styles/basic-preview/style.json',
// ...
)
```
### 4. Configure Native Permissions
**iOS (ios/Runner/Info.plist)**
```xml
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs location access to track your workouts</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs location access to track your workouts</string>
<key>NSMotionUsageDescription</key>
<string>This app needs motion data to enhance workout tracking</string>
```
**Android (android/app/src/main/AndroidManifest.xml)**
```xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<service
android:name=".LocationService"
android:foregroundServiceType="location"
android:enabled="true"
android:exported="true" />
```
### 5. Generate API Credentials for Testing
```bash
# On server, generate test credentials
php -r "
require 'backend/AuthenticationHandler.php';
\$creds = AuthenticationHandler::generateApiCredentials();
echo 'API Key: ' . \$creds['api_key'] . PHP_EOL;
echo 'API Secret: ' . \$creds['api_secret'] . PHP_EOL;
"
```
Insert into database:
```sql
INSERT INTO users (uuid, username, email, password_hash, api_key, api_secret, full_name, is_active)
VALUES (
UUID(),
'testuser',
'test@example.com',
'$2y$12$...', -- bcrypt hash of password
'your_generated_api_key',
'your_generated_api_secret',
'Test User',
TRUE
);
```
### 6. Test API Endpoint
```bash
#!/bin/bash
API_KEY="your_api_key"
API_SECRET="your_api_secret"
TIMESTAMP=$(date +%s)
ENDPOINT="https://your-api.com/api/v1/workouts"
PAYLOAD='{
"workout_type": "running",
"distance_meters": 5000,
"duration_seconds": 1800,
"elevation_gain_meters": 150,
"elevation_loss_meters": 100,
"calories_burned": 350,
"max_speed_mps": 4.5,
"route_polyline": "abc123def456",
"start_time": "2026-04-21T10:00:00Z",
"end_time": "2026-04-21T10:30:00Z",
"weather_condition": "sunny",
"temperature_celsius": 22.5,
"notes": "Great run!",
"is_public": false
}'
MESSAGE="${TIMESTAMP}|${API_KEY}|${PAYLOAD}"
SIGNATURE=$(echo -n "$MESSAGE" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $NF}')
curl -X POST "$ENDPOINT" \
-H "Content-Type: application/json" \
-H "X-API-Key: $API_KEY" \
-H "X-Signature: $SIGNATURE" \
-H "X-Timestamp: $TIMESTAMP" \
-d "$PAYLOAD"
```
## Security Checklist
- [ ] HTTPS/TLS 1.2+ enforced on all endpoints
- [ ] HMAC-SHA256 signatures verified on every request
- [ ] Timestamp validation (5-minute window) prevents replay attacks
- [ ] Passwords hashed with bcrypt (cost=12)
- [ ] API secrets stored securely (never logged)
- [ ] Database credentials not in version control
- [ ] Flutter app uses flutter_secure_storage for credentials
- [ ] Rate limiting implemented per API key
- [ ] SQL injection prevented via prepared statements
- [ ] CORS properly configured for cross-origin requests
- [ ] Input validation on all endpoints
- [ ] Error messages don't leak sensitive information
- [ ] Regular security audits scheduled
- [ ] Audit logs maintained in api_logs table
- [ ] API keys rotated periodically
## Performance Optimization
### Database Indexes
All critical queries have indexes:
- `users(api_key)` - API authentication
- `workouts(user_id, created_at)` - User workout history
- `api_logs(user_id, created_at)` - Audit logging
### Caching Strategy
- User stats cached in `user_stats_cache` table
- Cache invalidated on new workout submission
- Consider Redis for high-traffic scenarios
### Mobile Optimization
- GPS coordinates batched before SQLite insertion
- Polyline encoding reduces payload size by ~75%
- Map updates throttled to prevent UI jank
- Background location updates configurable
## Monitoring & Analytics
### Key Metrics to Track
1. **API Performance**
- Average response time per endpoint
- 95th percentile latency
- Request volume and patterns
2. **User Activity**
- Active users (DAU/MAU)
- Workouts submitted per day
- Average workout distance/duration
3. **System Health**
- Database connection pool status
- Server CPU/memory usage
- Error rate and types
### Logging
- All API requests logged in `api_logs` table
- Failed authentication attempts tracked
- Unusual access patterns monitored
## Deployment Checklist
### Pre-Deployment
- [ ] All tests passing
- [ ] Code review completed
- [ ] Security scan completed
- [ ] Performance tested under load
- [ ] Backup strategy in place
- [ ] Rollback plan documented
### Deployment
- [ ] Database migrations executed
- [ ] PHP files deployed and tested
- [ ] SSL certificates valid
- [ ] API credentials generated
- [ ] Monitoring configured
- [ ] Alerts set up
### Post-Deployment
- [ ] Smoke tests passed
- [ ] API response times acceptable
- [ ] Database queries optimized
- [ ] Logs reviewed for errors
- [ ] Metrics collected and analyzed
## Troubleshooting
### Common Issues
**Invalid Signature Error**
- Verify API key and secret are correct
- Check timestamp is within 5 minutes
- Ensure payload JSON is not modified after signing
- Verify HMAC algorithm is SHA256
**Database Connection Error**
- Check MySQL server is running
- Verify credentials in Database.php
- Ensure firewall allows connection
- Check max_connections limit
**Location Tracking Not Working**
- Verify location permissions on device
- Check GPS is enabled
- Ensure app has foreground/background permission
- Check location_service package initialization
**Map Not Displaying**
- Verify MapLibre tile server is accessible
- Check API key for tile server
- Ensure device has internet connection
- Verify style JSON URL is correct
## Scaling Considerations
For production deployments with 100k+ users:
1. **Database**
- Implement read replicas for analytics queries
- Archive old workout data to separate table
- Implement partitioning by user_id
2. **API Server**
- Deploy multiple PHP instances behind load balancer
- Implement API gateway with rate limiting
- Use CDN for static assets
3. **Caching**
- Implement Redis for session/stats caching
- Cache user stats for 1 hour
- Cache API responses for 5 minutes
4. **Background Jobs**
- Use queue system for async processing
- Recalculate user stats in background
- Generate reports/analytics offline
## Support & Maintenance
### Regular Maintenance Tasks
- Monitor API logs for errors
- Review security audit logs
- Update dependencies monthly
- Performance tuning as needed
- Database optimization (ANALYZE/OPTIMIZE)
- Backup verification
### Contact
For issues or questions, contact: support@fitness-app.com