198 lines
6.3 KiB
Python
Executable File
198 lines
6.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Security setup script for Delphi Consulting Group Database System
|
|
Generates secure keys and helps configure environment variables
|
|
"""
|
|
|
|
import secrets
|
|
import string
|
|
import os
|
|
import sys
|
|
|
|
def generate_secret_key(length=32):
|
|
"""Generate a secure secret key"""
|
|
return secrets.token_urlsafe(length)
|
|
|
|
def generate_secure_password(length=16):
|
|
"""Generate a secure password with mixed characters"""
|
|
alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
|
|
password = ''.join(secrets.choice(alphabet) for _ in range(length))
|
|
return password
|
|
|
|
def create_env_file():
|
|
"""Create a .env file with secure defaults"""
|
|
env_path = ".env"
|
|
|
|
if os.path.exists(env_path):
|
|
response = input(f"{env_path} already exists. Overwrite? (y/N): ").strip().lower()
|
|
if response != 'y':
|
|
print("Keeping existing .env file.")
|
|
return False
|
|
|
|
print("🔐 Generating secure configuration...")
|
|
|
|
# Generate secure values
|
|
secret_key = generate_secret_key(32)
|
|
admin_password = generate_secure_password(16)
|
|
|
|
# Get user inputs
|
|
print("\n📝 Please provide the following information:")
|
|
admin_username = input("Admin username [admin]: ").strip() or "admin"
|
|
admin_email = input("Admin email [admin@delphicg.local]: ").strip() or "admin@delphicg.local"
|
|
admin_fullname = input("Admin full name [System Administrator]: ").strip() or "System Administrator"
|
|
external_port = input("External port [6920]: ").strip() or "6920"
|
|
|
|
# Ask about password
|
|
use_generated = input(f"Use generated password '{admin_password}'? (Y/n): ").strip().lower()
|
|
if use_generated == 'n':
|
|
admin_password = input("Enter custom admin password: ").strip()
|
|
while len(admin_password) < 8:
|
|
print("Password must be at least 8 characters long!")
|
|
admin_password = input("Enter custom admin password: ").strip()
|
|
|
|
# Create .env content
|
|
env_content = f"""# Delphi Consulting Group Database System - Environment Variables
|
|
# Generated by setup-security.py on {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
|
|
|
# ===== APPLICATION SETTINGS =====
|
|
APP_NAME=Delphi Consulting Group Database System
|
|
DEBUG=False
|
|
|
|
# ===== DATABASE CONFIGURATION =====
|
|
DATABASE_URL=sqlite:///data/delphi_database.db
|
|
|
|
# ===== SECURITY SETTINGS - GENERATED =====
|
|
SECRET_KEY={secret_key}
|
|
# Optional previous key for seamless rotation (leave blank initially)
|
|
PREVIOUS_SECRET_KEY=
|
|
ACCESS_TOKEN_EXPIRE_MINUTES=240
|
|
REFRESH_TOKEN_EXPIRE_MINUTES=43200
|
|
ALGORITHM=HS256
|
|
|
|
# ===== ADMIN USER CREATION =====
|
|
CREATE_ADMIN_USER=true
|
|
ADMIN_USERNAME={admin_username}
|
|
ADMIN_EMAIL={admin_email}
|
|
ADMIN_PASSWORD={admin_password}
|
|
ADMIN_FULLNAME={admin_fullname}
|
|
|
|
# ===== SERVER SETTINGS =====
|
|
HOST=0.0.0.0
|
|
PORT=8000
|
|
EXTERNAL_PORT={external_port}
|
|
|
|
# ===== FILE STORAGE =====
|
|
UPLOAD_DIR=./uploads
|
|
BACKUP_DIR=./backups
|
|
|
|
# ===== PAGINATION =====
|
|
DEFAULT_PAGE_SIZE=50
|
|
MAX_PAGE_SIZE=200
|
|
|
|
# ===== LOGGING =====
|
|
LOG_LEVEL=INFO
|
|
|
|
# ===== PRODUCTION SECURITY =====
|
|
SECURE_COOKIES=False
|
|
SECURE_SSL_REDIRECT=False
|
|
|
|
# ===== CORS SETTINGS =====
|
|
CORS_ORIGINS=["http://localhost:{external_port}"]
|
|
|
|
# ===== RATE LIMITING =====
|
|
RATE_LIMIT_PER_MINUTE=100
|
|
LOGIN_RATE_LIMIT_PER_MINUTE=10
|
|
|
|
# ===== DOCKER SETTINGS =====
|
|
WORKERS=4
|
|
WORKER_TIMEOUT=120
|
|
|
|
# ===== BACKUP SETTINGS =====
|
|
BACKUP_RETENTION_COUNT=10
|
|
|
|
# ===== MONITORING & HEALTH CHECKS =====
|
|
HEALTH_CHECK_INTERVAL=30
|
|
HEALTH_CHECK_TIMEOUT=10
|
|
"""
|
|
|
|
# Write .env file
|
|
try:
|
|
with open(env_path, 'w') as f:
|
|
f.write(env_content)
|
|
|
|
# Set restrictive permissions
|
|
os.chmod(env_path, 0o600)
|
|
|
|
print(f"\n✅ Created {env_path} with secure configuration!")
|
|
print(f"📁 File permissions set to 600 (owner read/write only)")
|
|
print(f"\n🔐 Generated credentials:")
|
|
print(f" Secret Key: {secret_key[:10]}... (truncated)")
|
|
print(f" Admin Username: {admin_username}")
|
|
print(f" Admin Email: {admin_email}")
|
|
print(f" Admin Password: {admin_password}")
|
|
print(f" External Port: {external_port}")
|
|
|
|
print(f"\n⚠️ IMPORTANT SECURITY NOTES:")
|
|
print(f" • Keep the .env file secure and never commit it to version control")
|
|
print(f" • Change the admin password after first login")
|
|
print(f" • The secret key is used for JWT token signing")
|
|
print(f" • For production, consider using stronger passwords and key rotation")
|
|
|
|
return True
|
|
|
|
except Exception as e:
|
|
print(f"❌ Error creating .env file: {e}")
|
|
return False
|
|
|
|
def show_security_checklist():
|
|
"""Display security checklist"""
|
|
print("\n📋 PRODUCTION SECURITY CHECKLIST:")
|
|
checklist = [
|
|
"✓ Generated secure SECRET_KEY",
|
|
"✓ Set strong admin password",
|
|
"✓ Configured proper CORS origins",
|
|
"□ Set up SSL/HTTPS in production",
|
|
"□ Configure firewall rules",
|
|
"□ Set up regular backups",
|
|
"□ Enable monitoring/logging",
|
|
"□ Review user access permissions",
|
|
"□ Update Docker images regularly",
|
|
"□ Set up intrusion detection"
|
|
]
|
|
|
|
for item in checklist:
|
|
print(f" {item}")
|
|
|
|
def main():
|
|
print("🛡️ Delphi Database Security Setup")
|
|
print("=" * 40)
|
|
|
|
if len(sys.argv) > 1 and sys.argv[1] == "--key-only":
|
|
print("🔑 Generating secure secret key:")
|
|
print(generate_secret_key(32))
|
|
return
|
|
|
|
if len(sys.argv) > 1 and sys.argv[1] == "--password-only":
|
|
print("🔒 Generating secure password:")
|
|
print(generate_secure_password(16))
|
|
return
|
|
|
|
print("This script will help you set up secure configuration for the")
|
|
print("Delphi Consulting Group Database System.\n")
|
|
|
|
# Create .env file
|
|
if create_env_file():
|
|
show_security_checklist()
|
|
|
|
print(f"\n🚀 Next steps:")
|
|
print(f" 1. Review the generated .env file")
|
|
print(f" 2. Start the application: docker-compose up -d")
|
|
print(f" 3. Access: http://localhost:{os.getenv('EXTERNAL_PORT', '6920')}")
|
|
print(f" 4. Login with the generated admin credentials")
|
|
print(f" 5. Change the admin password after first login")
|
|
else:
|
|
print("\n❌ Setup failed or cancelled.")
|
|
sys.exit(1)
|
|
|
|
if __name__ == "__main__":
|
|
main() |