From d17ed79e29d631b552ae857f2c72576dc70a26c9 Mon Sep 17 00:00:00 2001 From: Quality App Developer Date: Thu, 15 Jan 2026 22:25:13 +0200 Subject: [PATCH] chore: remove caddy-related and obsolete files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removed: - Caddyfile: Caddy reverse proxy config (replaced by nginx.conf) - setup_https.sh: Caddy HTTPS setup script - https_manager.py: Caddy HTTPS management utility - HTTPS_STATUS.txt: Old HTTPS documentation - docker-compose.http.yml: HTTP-only Caddy compose file - player_auth_module.py: Old authentication module (unused) - player_config_template.ini: Old player config template (unused) - test connection.txr: Test file Updated: - init-data.sh: Removed references to deleted caddy/obsolete files - .dockerignore: Removed obsolete ignore entries This completes the Caddy → Nginx migration cleanup. --- .dockerignore | 4 +- Caddyfile | 73 ------- HTTPS_STATUS.txt | 413 ------------------------------------- docker-compose.http.yml | 27 --- https_manager.py | 157 -------------- init-data.sh | 10 +- player_auth_module.py | 254 ----------------------- player_config_template.ini | 51 ----- setup_https.sh | 146 ------------- test connection.txr | 26 --- 10 files changed, 4 insertions(+), 1157 deletions(-) delete mode 100755 Caddyfile delete mode 100644 HTTPS_STATUS.txt delete mode 100644 docker-compose.http.yml delete mode 100644 https_manager.py delete mode 100755 player_auth_module.py delete mode 100755 player_config_template.ini delete mode 100755 setup_https.sh delete mode 100644 test connection.txr diff --git a/.dockerignore b/.dockerignore index 50677da..412633d 100755 --- a/.dockerignore +++ b/.dockerignore @@ -52,6 +52,4 @@ PLAYER_AUTH.md PROGRESS.md README.md -# Config templates -player_config_template.ini -player_auth_module.py + diff --git a/Caddyfile b/Caddyfile deleted file mode 100755 index a9a54a7..0000000 --- a/Caddyfile +++ /dev/null @@ -1,73 +0,0 @@ -{ - # Global options - email admin@example.com - # Admin API for configuration management (listen on all interfaces) - admin 0.0.0.0:2019 -} - -# Shared reverse proxy configuration -(reverse_proxy_config) { - reverse_proxy digiserver-app:5000 { - header_up Host {host} - header_up X-Real-IP {remote_host} - header_up X-Forwarded-Proto {scheme} - - # Timeouts for large uploads - transport http { - read_timeout 300s - write_timeout 300s - } - } - - # File upload size limit (2GB) - request_body { - max_size 2GB - } - - # Security headers - header { - X-Frame-Options "SAMEORIGIN" - X-Content-Type-Options "nosniff" - X-XSS-Protection "1; mode=block" - } - - # Logging - log { - output file /var/log/caddy/access.log - } -} - -# Localhost (development/local access - HTTP only for local dev) -http://localhost { - import reverse_proxy_config -} - -# Main HTTPS entry point with multiple hostnames and IP -https://digiserver, https://10.76.152.164, https://digiserver.sibiusb.harting.intra { - import reverse_proxy_config - tls internal -} - -# HTTP redirects to HTTPS for each hostname -http://digiserver { - redir https://{host}{uri} -} - -http://10.76.152.164 { - redir https://{host}{uri} -} - -http://digiserver.sibiusb.harting.intra { - redir https://{host}{uri} -} - -# Catch-all for any other HTTP requests -http://* { - import reverse_proxy_config -} - -# Catch-all for any other HTTPS requests (fallback) -https://* { - import reverse_proxy_config - tls internal -} diff --git a/HTTPS_STATUS.txt b/HTTPS_STATUS.txt deleted file mode 100644 index b2b65e3..0000000 --- a/HTTPS_STATUS.txt +++ /dev/null @@ -1,413 +0,0 @@ -╔═══════════════════════════════════════════════════════════════════════════════╗ -║ HTTPS MANAGEMENT SYSTEM IMPLEMENTATION ║ -║ ✅ COMPLETE ║ -╚═══════════════════════════════════════════════════════════════════════════════╝ - -📦 DELIVERABLES -═══════════════════════════════════════════════════════════════════════════════ - -✅ CREATED FILES (9 new files) -─────────────────────────────────────────────────────────────────────────────── - -1. 🗄️ DATABASE MODEL - └─ app/models/https_config.py - • HTTPSConfig database model - • Fields: hostname, domain, ip_address, port, status, audit trail - • Methods: get_config(), create_or_update(), to_dict() - • Auto timestamps for created/updated dates - -2. 🛣️ ADMIN ROUTES - └─ app/blueprints/admin.py (UPDATED) - • GET /admin/https-config - Configuration page - • POST /admin/https-config/update - Update settings - • GET /admin/https-config/status - JSON status endpoint - • Full validation and error handling - • Admin-only access control - -3. 🎨 ADMIN TEMPLATE - └─ app/templates/admin/https_config.html - • Beautiful, user-friendly configuration interface - • Status display section - • Configuration form with toggle switch - • Input validation feedback - • Real-time preview of access points - • Comprehensive help sections - • Responsive mobile design - -4. 📊 ADMIN DASHBOARD - └─ app/templates/admin/admin.html (UPDATED) - • New card: "🔒 HTTPS Configuration" - • Links to HTTPS configuration page - • Gradient design with lock icon - -5. 🔄 DATABASE MIGRATION - └─ migrations/add_https_config_table.py - • Creates https_config table - • Sets up indexes and constraints - • Audit trail fields - -6. 🖥️ CLI UTILITY - └─ https_manager.py - • Command-line interface - • Commands: status, enable, disable, show - • Useful for automation and scripting - -7. 🚀 SETUP SCRIPT - └─ setup_https.sh - • Automated setup script - • Runs database migration - • Displays step-by-step instructions - -8. 📚 DOCUMENTATION - ├─ HTTPS_CONFIGURATION.md (Comprehensive guide) - ├─ HTTPS_IMPLEMENTATION_SUMMARY.md (Architecture & details) - └─ HTTPS_QUICK_REFERENCE.md (Admin quick start) - -═══════════════════════════════════════════════════════════════════════════════ - -✅ UPDATED FILES (3 modified files) -─────────────────────────────────────────────────────────────────────────────── - -1. ✏️ app/models/__init__.py - • Added HTTPSConfig import - • Exported in __all__ list - -2. ✏️ app/blueprints/admin.py - • Imported HTTPSConfig model - • Added three new routes for HTTPS management - • 160+ lines of new admin functionality - -3. ✏️ app/templates/admin/admin.html - • Added HTTPS Configuration card to dashboard - • Purple gradient with lock icon - -4. ✏️ Caddyfile - • Updated to use domain: digiserver.sibiusb.harting.intra - • IP fallback: 10.76.152.164 - -═══════════════════════════════════════════════════════════════════════════════ - -🎯 KEY FEATURES -═══════════════════════════════════════════════════════════════════════════════ - -✅ WEB INTERFACE - • Enable/Disable HTTPS with toggle switch - • Configure hostname, domain, IP address, port - • Status display with current settings - • Real-time preview of access URLs - • User-friendly form with validations - • Responsive design for all devices - -✅ CONFIGURATION OPTIONS - • Hostname: Short server name - • Domain: Full domain name (e.g., digiserver.sibiusb.harting.intra) - • IP Address: Server IP (e.g., 10.76.152.164) - • Port: HTTPS port (default 443) - • Enable/Disable toggle - -✅ SECURITY - • Admin-only access with permission checks - • Input validation (domain, IP, port) - • Admin audit trail (who changed what, when) - • Server-side validation - • Logged in system logs - -✅ VALIDATION - • Domain format validation - • IPv4 address validation (0-255 range) - • Port range validation (1-65535) - • Required field checks - • User-friendly error messages - -✅ LOGGING - • All configuration changes logged - • Admin username recorded - • Timestamps for all changes - • Searchable in admin dashboard - -✅ INTEGRATION - • Works with existing Caddy reverse proxy - • Automatic Let's Encrypt SSL certificates - • No manual certificate management - • Automatic certificate renewal - • HTTP/HTTPS dual access - -═══════════════════════════════════════════════════════════════════════════════ - -🚀 QUICK START (5 Minutes) -═══════════════════════════════════════════════════════════════════════════════ - -1️⃣ RUN DATABASE MIGRATION - ┌─ Option A: Automated - │ bash setup_https.sh - │ - └─ Option B: Manual - python /app/migrations/add_https_config_table.py - -2️⃣ START APPLICATION - docker-compose up -d - -3️⃣ LOG IN AS ADMIN - • Navigate to admin panel - • Use admin credentials - -4️⃣ CONFIGURE HTTPS - • Go to: Admin Panel → 🔒 HTTPS Configuration - • Toggle: Enable HTTPS ✅ - • Fill in: - - Hostname: digiserver - - Domain: digiserver.sibiusb.harting.intra - - IP: 10.76.152.164 - - Port: 443 - • Click: Save HTTPS Configuration - -5️⃣ VERIFY - • Check status shows "✅ HTTPS ENABLED" - • Access via: https://digiserver.sibiusb.harting.intra - • Fallback: http://10.76.152.164 - -═══════════════════════════════════════════════════════════════════════════════ - -📋 DATABASE SCHEMA -═══════════════════════════════════════════════════════════════════════════════ - -TABLE: https_config -┌─────────────────┬──────────────┬──────────────────────────────────────┐ -│ Column │ Type │ Purpose │ -├─────────────────┼──────────────┼──────────────────────────────────────┤ -│ id │ INTEGER (PK) │ Primary key │ -│ https_enabled │ BOOLEAN │ Enable/disable HTTPS │ -│ hostname │ STRING(255) │ Server hostname (e.g., digiserver) │ -│ domain │ STRING(255) │ Domain (e.g., domain.local) │ -│ ip_address │ STRING(45) │ IP address (IPv4/IPv6) │ -│ port │ INTEGER │ HTTPS port (default 443) │ -│ created_at │ DATETIME │ Creation timestamp │ -│ updated_at │ DATETIME │ Last update timestamp │ -│ updated_by │ STRING(255) │ Admin who made change │ -└─────────────────┴──────────────┴──────────────────────────────────────┘ - -═══════════════════════════════════════════════════════════════════════════════ - -🔐 SECURITY FEATURES -═══════════════════════════════════════════════════════════════════════════════ - -✅ Access Control - • Admin-only routes with @admin_required decorator - • Permission checks on all endpoints - • Login required for configuration access - -✅ Input Validation - • Domain format validation - • IP address validation (IPv4/IPv6) - • Port range validation (1-65535) - • Required field validation - • Error messages for invalid inputs - -✅ SSL/TLS Management - • Automatic Let's Encrypt certificates - • Automatic renewal before expiration - • Security headers (HSTS, X-Frame-Options, etc.) - • HTTP/2 and HTTP/3 support via Caddy - -✅ Audit Trail - • All changes logged with timestamp - • Admin username recorded - • Enable/disable events tracked - • Searchable in server logs - -═══════════════════════════════════════════════════════════════════════════════ - -🛠️ ADMIN COMMANDS -═══════════════════════════════════════════════════════════════════════════════ - -CLI UTILITY: https_manager.py -─────────────────────────────────────────────────────────────────────────── - -Show Status: - python https_manager.py status - -Enable HTTPS: - python https_manager.py enable digiserver digiserver.sibiusb.harting.intra 10.76.152.164 443 - -Disable HTTPS: - python https_manager.py disable - -Show Configuration: - python https_manager.py show - -═══════════════════════════════════════════════════════════════════════════════ - -📊 ACCESS POINTS -═══════════════════════════════════════════════════════════════════════════════ - -AFTER CONFIGURATION: - -┌─ HTTPS (Recommended) ────────────────────────────────────────────┐ -│ URL: https://digiserver.sibiusb.harting.intra │ -│ Protocol: HTTPS (SSL/TLS) │ -│ Port: 443 │ -│ Certificate: Let's Encrypt (auto-renewed) │ -│ Use: All secure connections, recommended for everyone │ -└──────────────────────────────────────────────────────────────────┘ - -┌─ HTTP (Fallback) ────────────────────────────────────────────────┐ -│ URL: http://10.76.152.164 │ -│ Protocol: HTTP (plain text) │ -│ Port: 80 │ -│ Use: Troubleshooting, direct IP access, local network │ -└──────────────────────────────────────────────────────────────────┘ - -═══════════════════════════════════════════════════════════════════════════════ - -📚 DOCUMENTATION FILES -═══════════════════════════════════════════════════════════════════════════════ - -1. HTTPS_QUICK_REFERENCE.md - • Quick setup guide (5 minutes) - • Admin checklist - • Common tasks - • Troubleshooting basics - • STATUS: ⭐ START HERE! - -2. HTTPS_CONFIGURATION.md - • Comprehensive feature guide - • Step-by-step workflow - • Configuration details - • Prerequisites and requirements - • Integration overview - • Troubleshooting guide - • STATUS: For detailed reference - -3. HTTPS_IMPLEMENTATION_SUMMARY.md - • Architecture and design - • Files created/modified - • Database schema - • Integration details - • Implementation checklist - • STATUS: For developers - -═══════════════════════════════════════════════════════════════════════════════ - -✅ WORKFLOW -═══════════════════════════════════════════════════════════════════════════════ - -INITIAL STATE (HTTP ONLY) - ┌─────────────────────┐ - │ App on Port 80 │ - │ HTTP only │ - └────────┬────────────┘ - │ - └─ Accessible at: http://10.76.152.164 - -USER CONFIGURES HTTPS - ┌─────────────────────────────────────────────┐ - │ Admin Sets: │ - │ • Hostname: digiserver │ - │ • Domain: digiserver.sibiusb.harting.intra │ - │ • IP: 10.76.152.164 │ - │ • Port: 443 │ - └────────┬────────────────────────────────────┘ - │ - ↓ -CONFIGURATION SAVED - ┌──────────────────────────────────────────────┐ - │ • Settings stored in database │ - │ • Change logged with admin name & timestamp │ - │ • Status updated in admin panel │ - └────────┬─────────────────────────────────────┘ - │ - ↓ -SYSTEM OPERATIONAL - ├─ HTTPS Active (Port 443) - │ URL: https://digiserver.sibiusb.harting.intra - │ Certificate: Auto-managed by Let's Encrypt - │ - └─ HTTP Fallback (Port 80) - URL: http://10.76.152.164 - For troubleshooting and backup access - -═══════════════════════════════════════════════════════════════════════════════ - -✨ HIGHLIGHTS -═══════════════════════════════════════════════════════════════════════════════ - -🎯 USER EXPERIENCE - • No manual configuration needed - • Simple toggle to enable/disable - • Real-time preview of settings - • Status display shows current state - • Mobile-responsive interface - -🔒 SECURITY - • Admin-only access - • Input validation on all fields - • Audit trail of all changes - • Automatic SSL certificates - • No sensitive data stored in plain text - -⚙️ FLEXIBILITY - • Configurable hostname, domain, IP - • Custom port support - • Enable/disable without data loss - • CLI and web interface both available - • Works with existing Caddy setup - -📊 MONITORING - • Status endpoint for integration - • Logged changes in server logs - • Admin dashboard status display - • CLI status command - -🚀 AUTOMATION - • CLI interface for scripting - • Can be automated via setup scripts - • Supports headless configuration - • REST API endpoint for status - -═══════════════════════════════════════════════════════════════════════════════ - -📋 CHECKLIST -═══════════════════════════════════════════════════════════════════════════════ - -IMPLEMENTATION -✅ Database model created (https_config.py) -✅ Admin routes added (3 new endpoints) -✅ Admin template created (https_config.html) -✅ Dashboard card added -✅ Database migration created -✅ CLI utility implemented -✅ Setup script created -✅ Documentation completed (3 guides) -✅ Code integrated with existing system -✅ Admin-only access enforced -✅ Input validation implemented -✅ Logging implemented -✅ Error handling added - -DEPLOYMENT -⏳ Run database migration: python migrations/add_https_config_table.py -⏳ Start application: docker-compose up -d -⏳ Configure via admin panel -⏳ Verify access points -⏳ Check status display -⏳ Review logs for changes - -═══════════════════════════════════════════════════════════════════════════════ - -🎉 SYSTEM READY -═══════════════════════════════════════════════════════════════════════════════ - -All files have been created and integrated. -The HTTPS configuration management system is complete and ready to use. - -NEXT STEPS: -1. Run database migration -2. Restart application -3. Access admin panel -4. Navigate to HTTPS Configuration -5. Enable and configure HTTPS settings -6. Verify access points - -For detailed instructions, see: HTTPS_QUICK_REFERENCE.md - -═══════════════════════════════════════════════════════════════════════════════ diff --git a/docker-compose.http.yml b/docker-compose.http.yml deleted file mode 100644 index 797cfc2..0000000 --- a/docker-compose.http.yml +++ /dev/null @@ -1,27 +0,0 @@ -version: '3.8' - -services: - digiserver: - build: . - container_name: digiserver-v2-http - ports: - - "80:5000" # Direct HTTP exposure on port 80 - volumes: - - ./instance:/app/instance - - ./app/static/uploads:/app/app/static/uploads - environment: - - FLASK_ENV=production - - SECRET_KEY=${SECRET_KEY:-your-secret-key-change-this} - - ADMIN_USERNAME=${ADMIN_USERNAME:-admin} - - ADMIN_PASSWORD=${ADMIN_PASSWORD:-admin123} - restart: unless-stopped - healthcheck: - test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5000/').read()"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 40s - -# Usage: docker-compose -f docker-compose.http.yml up -d -# Access at: http://localhost or http://your-server-ip -# Note: This is for development/testing only. Use docker-compose.yml for production HTTPS. diff --git a/https_manager.py b/https_manager.py deleted file mode 100644 index 97a3423..0000000 --- a/https_manager.py +++ /dev/null @@ -1,157 +0,0 @@ -"""Utility script for managing HTTPS configuration from command line.""" -import sys -import os -sys.path.insert(0, '/app') - -from app.app import create_app -from app.models.https_config import HTTPSConfig - -def show_help(): - """Display help information.""" - print(""" -HTTPS Configuration Management Utility -====================================== - -Usage: - python https_manager.py [arguments] - -Commands: - status Show current HTTPS configuration status - enable [port] - Enable HTTPS with specified settings - disable Disable HTTPS - show Show detailed configuration - -Examples: - # Show current status - python https_manager.py status - - # Enable HTTPS - python https_manager.py enable digiserver digiserver.sibiusb.harting.intra admin@example.com 10.76.152.164 443 - - # Disable HTTPS - python https_manager.py disable - - # Show detailed config - python https_manager.py show -""") - -def show_status(): - """Show current HTTPS status.""" - app = create_app() - with app.app_context(): - config = HTTPSConfig.get_config() - if config: - print("\n" + "=" * 50) - print("HTTPS Configuration Status") - print("=" * 50) - print(f"Status: {'✅ ENABLED' if config.https_enabled else '⚠️ DISABLED'}") - print(f"Hostname: {config.hostname or 'N/A'}") - print(f"Domain: {config.domain or 'N/A'}") - print(f"IP Address: {config.ip_address or 'N/A'}") - print(f"Port: {config.port}") - print(f"Updated: {config.updated_at.strftime('%Y-%m-%d %H:%M:%S')} by {config.updated_by or 'N/A'}") - if config.https_enabled: - print(f"\nAccess URL: https://{config.domain}") - print(f"Fallback: http://{config.ip_address}") - print("=" * 50 + "\n") - else: - print("\n⚠️ No HTTPS configuration found. Use 'enable' command to create one.\n") - -def enable_https(hostname: str, domain: str, ip_address: str, email: str, port: str = '443'): - """Enable HTTPS with specified settings.""" - app = create_app() - with app.app_context(): - try: - port_num = int(port) - config = HTTPSConfig.create_or_update( - https_enabled=True, - hostname=hostname, - domain=domain, - ip_address=ip_address, - email=email, - port=port_num, - updated_by='cli_admin' - ) - print("\n" + "=" * 50) - print("✅ HTTPS Configuration Updated") - print("=" * 50) - print(f"Hostname: {hostname}") - print(f"Domain: {domain}") - print(f"Email: {email}") - print(f"IP Address: {ip_address}") - print(f"Port: {port_num}") - print(f"\nAccess URL: https://{domain}") - print(f"Fallback: http://{ip_address}") - print("=" * 50 + "\n") - except Exception as e: - print(f"\n❌ Error: {str(e)}\n") - sys.exit(1) - -def disable_https(): - """Disable HTTPS.""" - app = create_app() - with app.app_context(): - try: - config = HTTPSConfig.create_or_update( - https_enabled=False, - updated_by='cli_admin' - ) - print("\n" + "=" * 50) - print("⚠️ HTTPS Disabled") - print("=" * 50) - print("The application is now running on HTTP only (port 80)") - print("=" * 50 + "\n") - except Exception as e: - print(f"\n❌ Error: {str(e)}\n") - sys.exit(1) - -def show_config(): - """Show detailed configuration.""" - app = create_app() - with app.app_context(): - config = HTTPSConfig.get_config() - if config: - print("\n" + "=" * 50) - print("Detailed HTTPS Configuration") - print("=" * 50) - for key, value in config.to_dict().items(): - print(f"{key:.<30} {value}") - print("=" * 50 + "\n") - else: - print("\n⚠️ No HTTPS configuration found.\n") - -def main(): - """Main entry point.""" - if len(sys.argv) < 2: - show_help() - sys.exit(1) - - command = sys.argv[1].lower() - - if command == 'status': - show_status() - elif command == 'enable': - if len(sys.argv) < 6: - print("\nError: 'enable' requires: hostname domain email ip_address [port]\n") - show_help() - sys.exit(1) - hostname = sys.argv[2] - domain = sys.argv[3] - email = sys.argv[4] - ip_address = sys.argv[5] - port = sys.argv[6] if len(sys.argv) > 6 else '443' - enable_https(hostname, domain, ip_address, email, port) - elif command == 'disable': - disable_https() - elif command == 'show': - show_config() - elif command in ['help', '-h', '--help']: - show_help() - else: - print(f"\nUnknown command: {command}\n") - show_help() - sys.exit(1) - -if __name__ == '__main__': - main() diff --git a/init-data.sh b/init-data.sh index d5f6873..be2e5e3 100755 --- a/init-data.sh +++ b/init-data.sh @@ -4,7 +4,7 @@ set -e echo "🔧 Initializing data folder..." -mkdir -p data/{app,instance,uploads,caddy-data,caddy-config} +mkdir -p data/{app,instance,uploads} echo "📁 Copying app folder..." rm -rf data/app @@ -16,14 +16,10 @@ rm -rf data/migrations cp -r migrations data/ echo "🔧 Copying utility scripts..." -cp https_manager.py player_auth_module.py fix_player_user_schema.py data/ - -echo "📄 Copying Caddyfile..." -cp Caddyfile data/ +cp fix_player_user_schema.py data/ echo "🔐 Setting permissions..." -chmod 755 data/{app,instance,uploads,caddy-data,caddy-config} -chmod 644 data/Caddyfile +chmod 755 data/{app,instance,uploads} chmod -R 755 data/app/ find data/app -type f \( -name "*.py" -o -name "*.html" -o -name "*.css" -o -name "*.js" \) -exec chmod 644 {} \; chmod 777 data/instance data/uploads diff --git a/player_auth_module.py b/player_auth_module.py deleted file mode 100755 index 41d719d..0000000 --- a/player_auth_module.py +++ /dev/null @@ -1,254 +0,0 @@ -""" -Player Authentication Module for Kiwy-Signage -Handles authentication with DigiServer v2 and secure config storage -""" -import configparser -import os -import requests -from typing import Optional, Dict, Tuple -import json - - -class PlayerAuth: - """Handle player authentication and configuration management.""" - - def __init__(self, config_path: str = 'player_config.ini'): - """Initialize player authentication. - - Args: - config_path: Path to configuration file - """ - self.config_path = config_path - self.config = configparser.ConfigParser() - self.load_config() - - def load_config(self) -> None: - """Load configuration from file.""" - if os.path.exists(self.config_path): - self.config.read(self.config_path) - else: - # Create default config - self._create_default_config() - - def _create_default_config(self) -> None: - """Create default configuration file.""" - self.config['server'] = { - 'server_url': 'http://localhost:5000' - } - self.config['player'] = { - 'hostname': '', - 'auth_code': '', - 'player_id': '', - 'group_id': '' - } - self.config['display'] = { - 'orientation': 'Landscape', - 'resolution': '1920x1080' - } - self.config['security'] = { - 'verify_ssl': 'true', - 'timeout': '30' - } - self.config['cache'] = { - 'cache_dir': './cache', - 'max_cache_size': '1024' - } - self.config['logging'] = { - 'enabled': 'true', - 'log_level': 'INFO', - 'log_file': './player.log' - } - self.save_config() - - def save_config(self) -> None: - """Save configuration to file.""" - with open(self.config_path, 'w') as f: - self.config.write(f) - - def get_server_url(self) -> str: - """Get server URL from config.""" - return self.config.get('server', 'server_url', fallback='http://localhost:5000') - - def get_hostname(self) -> str: - """Get player hostname from config.""" - return self.config.get('player', 'hostname', fallback='') - - def get_auth_code(self) -> str: - """Get saved auth code from config.""" - return self.config.get('player', 'auth_code', fallback='') - - def is_authenticated(self) -> bool: - """Check if player has valid authentication.""" - return bool(self.get_hostname() and self.get_auth_code()) - - def authenticate(self, hostname: str, password: str = None, - quickconnect_code: str = None) -> Tuple[bool, Optional[str]]: - """Authenticate with server and save credentials. - - Args: - hostname: Player hostname/identifier - password: Player password (optional if using quickconnect) - quickconnect_code: Quick connect code (optional if using password) - - Returns: - Tuple of (success: bool, error_message: Optional[str]) - """ - if not password and not quickconnect_code: - return False, "Password or quick connect code required" - - server_url = self.get_server_url() - - try: - # Make authentication request - response = requests.post( - f"{server_url}/api/auth/player", - json={ - 'hostname': hostname, - 'password': password, - 'quickconnect_code': quickconnect_code - }, - timeout=int(self.config.get('security', 'timeout', fallback='30')), - verify=self.config.getboolean('security', 'verify_ssl', fallback=True) - ) - - if response.status_code == 200: - data = response.json() - - # Save authentication data - self.config['player']['hostname'] = hostname - self.config['player']['auth_code'] = data.get('auth_code', '') - self.config['player']['player_id'] = str(data.get('player_id', '')) - self.config['player']['group_id'] = str(data.get('group_id', '')) - self.config['display']['orientation'] = data.get('orientation', 'Landscape') - - self.save_config() - - return True, None - - else: - error_data = response.json() - return False, error_data.get('error', 'Authentication failed') - - except requests.exceptions.ConnectionError: - return False, "Cannot connect to server" - except requests.exceptions.Timeout: - return False, "Connection timeout" - except Exception as e: - return False, f"Error: {str(e)}" - - def verify_auth(self) -> Tuple[bool, Optional[Dict]]: - """Verify current auth code with server. - - Returns: - Tuple of (valid: bool, player_info: Optional[Dict]) - """ - auth_code = self.get_auth_code() - - if not auth_code: - return False, None - - server_url = self.get_server_url() - - try: - response = requests.post( - f"{server_url}/api/auth/verify", - json={'auth_code': auth_code}, - timeout=int(self.config.get('security', 'timeout', fallback='30')), - verify=self.config.getboolean('security', 'verify_ssl', fallback=True) - ) - - if response.status_code == 200: - data = response.json() - return data.get('valid', False), data - - return False, None - - except Exception: - return False, None - - def get_playlist(self) -> Optional[Dict]: - """Get playlist for this player from server. - - Returns: - Playlist data or None if failed - """ - auth_code = self.get_auth_code() - player_id = self.config.get('player', 'player_id', fallback='') - - if not auth_code or not player_id: - return None - - server_url = self.get_server_url() - - try: - response = requests.get( - f"{server_url}/api/playlists/{player_id}", - headers={'Authorization': f'Bearer {auth_code}'}, - timeout=int(self.config.get('security', 'timeout', fallback='30')), - verify=self.config.getboolean('security', 'verify_ssl', fallback=True) - ) - - if response.status_code == 200: - return response.json() - - return None - - except Exception: - return None - - def send_heartbeat(self, status: str = 'online') -> bool: - """Send heartbeat to server. - - Args: - status: Player status - - Returns: - True if successful, False otherwise - """ - auth_code = self.get_auth_code() - player_id = self.config.get('player', 'player_id', fallback='') - - if not auth_code or not player_id: - return False - - server_url = self.get_server_url() - - try: - response = requests.post( - f"{server_url}/api/players/{player_id}/heartbeat", - headers={'Authorization': f'Bearer {auth_code}'}, - json={'status': status}, - timeout=int(self.config.get('security', 'timeout', fallback='30')), - verify=self.config.getboolean('security', 'verify_ssl', fallback=True) - ) - - return response.status_code == 200 - - except Exception: - return False - - def clear_auth(self) -> None: - """Clear saved authentication data.""" - self.config['player']['auth_code'] = '' - self.config['player']['player_id'] = '' - self.config['player']['group_id'] = '' - self.save_config() - - -# Example usage -if __name__ == '__main__': - auth = PlayerAuth() - - # Check if already authenticated - if auth.is_authenticated(): - print(f"Already authenticated as: {auth.get_hostname()}") - - # Verify authentication - valid, info = auth.verify_auth() - if valid: - print(f"Authentication valid: {info}") - else: - print("Authentication expired or invalid") - else: - print("Not authenticated. Please run authentication:") - print("auth.authenticate(hostname='player-001', password='your_password')") diff --git a/player_config_template.ini b/player_config_template.ini deleted file mode 100755 index c436568..0000000 --- a/player_config_template.ini +++ /dev/null @@ -1,51 +0,0 @@ -# Player Configuration File -# This file is automatically generated and updated by the signage player -# DO NOT EDIT MANUALLY unless you know what you're doing - -[server] -# DigiServer URL (without trailing slash) -server_url = http://localhost:5000 - -[player] -# Player hostname/identifier (must be unique) -hostname = - -# Player authentication code (obtained after first authentication) -auth_code = - -# Player ID (assigned by server) -player_id = - -# Group ID (assigned by server) -group_id = - -[display] -# Display orientation: Landscape or Portrait -orientation = Landscape - -# Screen resolution (width x height) -resolution = 1920x1080 - -[security] -# Enable SSL certificate verification -verify_ssl = true - -# Connection timeout in seconds -timeout = 30 - -[cache] -# Local cache directory for downloaded content -cache_dir = ./cache - -# Maximum cache size in MB -max_cache_size = 1024 - -[logging] -# Enable logging -enabled = true - -# Log level: DEBUG, INFO, WARNING, ERROR -log_level = INFO - -# Log file path -log_file = ./player.log diff --git a/setup_https.sh b/setup_https.sh deleted file mode 100755 index 49ea46e..0000000 --- a/setup_https.sh +++ /dev/null @@ -1,146 +0,0 @@ -#!/bin/bash -# Setup script for HTTPS Configuration Management and complete system initialization -# This script can be run locally or on a new deployment PC - -set -e # Exit on any error - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -# Determine if we're running in Docker or on host -IN_DOCKER=false -if [ -f /.dockerenv ]; then - IN_DOCKER=true -fi - -echo -e "${BLUE}╔════════════════════════════════════════════════════════════════╗${NC}" -echo -e "${BLUE}║ DigiServer HTTPS Configuration Setup ║${NC}" -echo -e "${BLUE}╚════════════════════════════════════════════════════════════════╝${NC}" -echo "" - -# ============================================================================ -# OPTION 1: Running inside Docker container -# ============================================================================ -if [ "$IN_DOCKER" = true ]; then - echo -e "${YELLOW}📍 Running inside Docker container${NC}" - echo "" - - echo -e "${BLUE}Step 1/4:${NC} ${YELLOW}Creating https_config database table...${NC}" - python /app/migrations/add_https_config_table.py - echo -e "${GREEN}✅ https_config table created${NC}" - echo "" - - echo -e "${BLUE}Step 2/4:${NC} ${YELLOW}Creating player_user database table...${NC}" - python /app/migrations/add_player_user_table.py - echo -e "${GREEN}✅ player_user table created${NC}" - echo "" - - echo -e "${BLUE}Step 3/4:${NC} ${YELLOW}Adding email column to https_config...${NC}" - python /app/migrations/add_email_to_https_config.py - echo -e "${GREEN}✅ Email column added${NC}" - echo "" - - echo -e "${BLUE}Step 4/4:${NC} ${YELLOW}Migrating player_user global settings...${NC}" - python /app/migrations/migrate_player_user_global.py - echo -e "${GREEN}✅ Player user migration completed${NC}" - echo "" - - echo -e "${GREEN}✅ HTTPS Configuration Management is now ready!${NC}" - echo "" - echo -e "${BLUE}ℹ️ Next steps:${NC}" - echo "1. Log in to the admin panel" - echo "2. Navigate to: Admin Panel → 🔒 HTTPS Configuration" - echo "3. Configure your HTTPS settings:" - echo " - Enable HTTPS" - echo " - Set hostname: digiserver" - echo " - Set domain: digiserver.sibiusb.harting.intra" - echo " - Set IP: 10.76.152.164" - echo "4. Save the configuration" - echo "" - exit 0 -fi - -# ============================================================================ -# OPTION 2: Running on host machine with docker-compose -# ============================================================================ -echo -e "${YELLOW}📍 Running on host machine${NC}" -echo "" - -# Check if docker-compose is available -if ! command -v docker-compose &> /dev/null; then - echo -e "${RED}❌ docker-compose not found!${NC}" - exit 1 -fi - -# Check if we're in the project directory -if [ ! -f "docker-compose.yml" ]; then - echo -e "${RED}❌ docker-compose.yml not found!${NC}" - echo "Please run this script from the digiserver-v2 directory" - exit 1 -fi - -echo -e "${BLUE}Checking container status...${NC}" -RUNNING=$(docker-compose ps -q digiserver-app 2>/dev/null || echo "") -if [ -z "$RUNNING" ]; then - echo -e "${YELLOW}📦 Starting containers...${NC}" - docker-compose up -d - echo -e "${YELLOW}⏳ Waiting for containers to be ready...${NC}" - sleep 5 -fi - -echo -e "${GREEN}✅ Containers are running${NC}" -echo "" - -# Run all migrations -echo -e "${BLUE}Step 1/5:${NC} ${YELLOW}Creating https_config database table...${NC}" -docker-compose exec -T digiserver-app python /app/migrations/add_https_config_table.py -echo -e "${GREEN}✅ https_config table created${NC}" -echo "" - -echo -e "${BLUE}Step 2/5:${NC} ${YELLOW}Creating player_user database table...${NC}" -docker-compose exec -T digiserver-app python /app/migrations/add_player_user_table.py -echo -e "${GREEN}✅ player_user table created${NC}" -echo "" - -echo -e "${BLUE}Step 3/5:${NC} ${YELLOW}Adding email column to https_config...${NC}" -docker-compose exec -T digiserver-app python /app/migrations/add_email_to_https_config.py -echo -e "${GREEN}✅ Email column added${NC}" -echo "" - -echo -e "${BLUE}Step 4/5:${NC} ${YELLOW}Migrating player_user global settings...${NC}" -docker-compose exec -T digiserver-app python /app/migrations/migrate_player_user_global.py -echo -e "${GREEN}✅ Player user migration completed${NC}" -echo "" - -# Configure HTTPS automatically -echo -e "${BLUE}Step 5/5:${NC} ${YELLOW}Configuring HTTPS settings...${NC}" -docker-compose exec -T digiserver-app python /app/https_manager.py enable \ - digiserver \ - digiserver.sibiusb.harting.intra \ - admin@example.com \ - 10.76.152.164 \ - 443 - -echo -e "${GREEN}✅ HTTPS configured successfully${NC}" -echo "" - -# Display configuration status -echo -e "${BLUE}Configuration Status:${NC}" -docker-compose exec -T digiserver-app python /app/https_manager.py status -echo "" - -echo -e "${GREEN}╔════════════════════════════════════════════════════════════════╗${NC}" -echo -e "${GREEN}║ 🎉 Deployment Complete! ║${NC}" -echo -e "${GREEN}╚════════════════════════════════════════════════════════════════╝${NC}" -echo "" -echo -e "${BLUE}Access your application at:${NC}" -echo " 🔒 https://digiserver" -echo " 🔒 https://10.76.152.164" -echo " 🔒 https://digiserver.sibiusb.harting.intra" -echo "" -echo -e "${BLUE}📖 For more deployment commands, see: DEPLOYMENT_COMMANDS.md${NC}" -echo "" diff --git a/test connection.txr b/test connection.txr deleted file mode 100644 index 7670378..0000000 --- a/test connection.txr +++ /dev/null @@ -1,26 +0,0 @@ -# 1. Add virtual IP -sudo ip addr add 10.76.152.164/24 dev wlp0s20f3 - -# 2. Wait a moment for the interface to be ready -sleep 2 - -# 3. Test HTTP (should redirect to HTTPS) -echo "Testing HTTP:" -curl -i http://10.76.152.164 - -# 4. Test HTTPS -echo "Testing HTTPS:" -curl -k https://10.76.152.164 | head -20 - -# 5. When done, remove the alias -sudo ip addr del 10.76.152.164/24 dev wlp0s20f3 - - - -echo "📋 Step 1: Add virtual IP alias 10.76.152.164 to wlp0s20f3" && \ -sudo ip addr add 10.76.152.164/24 dev wlp0s20f3 && \ -echo "✅ Virtual IP added" && \ -sleep 2 && \ -echo "" && \ -echo "📋 Step 2: Verify the virtual IP is active" && \ -ip addr show wlp0s20f3 | grep "inet " \ No newline at end of file