This commit is contained in:
Mateusz Gruszczyński
2025-11-04 10:19:12 +01:00
parent f8a05554c1
commit bb3aa9f179
3 changed files with 62 additions and 68 deletions

54
app.py
View File

@@ -12,7 +12,7 @@ from flask import Flask, render_template, redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy
from config.settings import *
from database import db, migrate # ✅ NIE importuj init_db tutaj!
from database import db, migrate, init_db
from routes.main_routes import main_bp
from routes.edit_routes import edit_bp
from routes.auth_routes import auth_bp
@@ -60,7 +60,6 @@ app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
print("[APP] Initializing database...", flush=True)
db.init_app(app)
migrate.init_app(app, db)
# ❌ USUŃ TĘ LINIĘ: init_db(app)
print("[APP] Database initialized", flush=True)
@@ -87,23 +86,26 @@ private_key_path = None
ssl_context = None
try:
config_ssl = configparser.ConfigParser()
config_ssl.read(SSL_INI)
if os.path.exists(SSL_INI):
config_ssl = configparser.ConfigParser()
config_ssl.read(SSL_INI)
if config_ssl.has_section('ssl'):
certificate_path = config_ssl.get('ssl', 'certificate_path')
private_key_path = config_ssl.get('ssl', 'private_key_path')
if config_ssl.has_section('ssl'):
certificate_path = config_ssl.get('ssl', 'certificate_path')
private_key_path = config_ssl.get('ssl', 'private_key_path')
if os.path.exists(certificate_path) and os.path.exists(private_key_path):
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ssl_context.load_cert_chain(certfile=certificate_path, keyfile=private_key_path)
print("[APP] SSL context loaded successfully", flush=True)
if os.path.exists(certificate_path) and os.path.exists(private_key_path):
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ssl_context.load_cert_chain(certfile=certificate_path, keyfile=private_key_path)
print("[APP] SSL context loaded successfully", flush=True)
else:
print(f"[APP] SSL certificate files not found", flush=True)
print(f" Certificate: {certificate_path}", flush=True)
print(f" Private Key: {private_key_path}", flush=True)
else:
print(f"[APP] SSL certificate files not found", flush=True)
print(f" Certificate: {certificate_path}", flush=True)
print(f" Private Key: {private_key_path}", flush=True)
print(f"[APP] No [ssl] section in {SSL_INI}", flush=True)
else:
print(f"[APP] No [ssl] section in {SSL_INI}", flush=True)
print(f"[APP] No SSL config file found: {SSL_INI}", flush=True)
except Exception as e:
print(f"[APP] SSL warning (non-critical): {e}", flush=True)
@@ -182,8 +184,6 @@ def make_shell_context():
}
# ===== APPLICATION CONTEXT =====
@app.before_request
def before_request():
"""Run before each request"""
@@ -201,10 +201,8 @@ def after_request(response):
@app.cli.command()
def init_db_cli():
"""Initialize database"""
with app.app_context():
from database import init_db
init_db(app)
print("[CLI] Database initialized successfully")
init_db(app)
print("[CLI] Database initialized successfully", flush=True)
@app.cli.command()
@@ -229,16 +227,6 @@ def create_admin():
print(f"[CLI] Admin user '{username}' created successfully")
@app.cli.command()
def import_config():
"""Import existing haproxy.cfg to database"""
from database.migration import parse_existing_haproxy_config
config_path = HAPROXY_CONFIG_PATH
count = parse_existing_haproxy_config(config_path)
print(f"[CLI] Successfully imported {count} vhosts from {config_path}")
# ===== MAIN ENTRY POINT =====
if __name__ == '__main__':
@@ -253,9 +241,7 @@ if __name__ == '__main__':
print(f"[APP] Running on: https://[::]:5000 (IPv6)", flush=True)
# Initialize database before running
with app.app_context():
from database import init_db
init_db(app)
init_db(app)
app.run(
host='::',

View File

@@ -1,39 +1,48 @@
"""Application Settings and Configuration"""
"""Application Settings"""
import os
from datetime import timedelta
# ===== FLASK =====
DEBUG = os.environ.get('FLASK_DEBUG', False)
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production')
# ===== ENVIRONMENT =====
DEBUG = os.getenv('FLASK_DEBUG', 'False').lower() == 'true'
ENV = os.getenv('FLASK_ENV', 'production')
# ===== BASE PATHS =====
BASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
INSTANCE_DIR = os.path.join(BASE_DIR, 'instance')
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'uploads/certificates')
HAPROXY_BACKUP_DIR = os.path.join(BASE_DIR, 'backups')
# ===== DATABASE =====
BASEDIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
f'sqlite:///{os.path.join(BASEDIR, "instance", "app.db")}'
SQLALCHEMY_DATABASE_URI = os.getenv(
'DATABASE_URL',
f'sqlite:///{os.path.join(INSTANCE_DIR, "app.db")}'
)
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = DEBUG
# ===== SESSION =====
# ===== FLASK SETTINGS =====
SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key-change-in-production')
PERMANENT_SESSION_LIFETIME = timedelta(days=7)
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
# ===== FILE UPLOAD =====
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16MB max
UPLOAD_FOLDER = os.path.join(BASEDIR, 'uploads', 'certificates')
ALLOWED_EXTENSIONS = {'pem', 'crt', 'key', 'cert'}
# ===== HAPROXY =====
HAPROXY_CONFIG_PATH = '/etc/haproxy/haproxy.cfg'
HAPROXY_BACKUP_DIR = os.path.join(BASEDIR, 'backups')
HAPROXY_STATS_PORT = 8404 # Hardcoded na stałe dla statystyk
HAPROXY_LOG_FILE = '/var/log/haproxy.log'
HAPROXY_CONFIG_PATH = os.getenv('HAPROXY_CONFIG_PATH', '/etc/haproxy/haproxy.cfg')
HAPROXY_BACKUP_DIR = os.path.join(BASE_DIR, 'backups')
HAPROXY_STATS_PORT = int(os.getenv('HAPROXY_STATS_PORT', '8404'))
# ===== DEFAULT AUTH =====
DEFAULT_ADMIN_USERNAME = os.environ.get('ADMIN_USERNAME', 'admin')
DEFAULT_ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'admin123')
# ===== SSL =====
SSL_INI = os.path.join(BASE_DIR, 'config', 'ssl.ini')
# ===== MAX UPLOAD SIZE =====
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16MB
# ===== LOGGING =====
LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
LOG_FILE = os.path.join(BASE_DIR, 'logs', 'app.log')
os.makedirs(INSTANCE_DIR, exist_ok=True)
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(HAPROXY_BACKUP_DIR, exist_ok=True)
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)

View File

@@ -1,4 +1,4 @@
"""Database initialization"""
"""Database module initialization"""
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
@@ -6,22 +6,21 @@ from flask_migrate import Migrate
db = SQLAlchemy()
migrate = Migrate()
def init_db(app):
"""Initialize database with app"""
db.init_app(app)
migrate.init_app(app, db)
# Create tables
def init_db(app):
"""Initialize database - create tables"""
with app.app_context():
db.create_all()
print("[DB] All tables created successfully", flush=True)
# Create default admin user if not exists
from database.models import User
admin = User.query.filter_by(username='admin').first()
if not admin:
from config.settings import DEFAULT_ADMIN_USERNAME, DEFAULT_ADMIN_PASSWORD
admin = User(username=DEFAULT_ADMIN_USERNAME)
admin.set_password(DEFAULT_ADMIN_PASSWORD)
admin = User(username='admin', is_admin=True)
admin.set_password('admin123')
db.session.add(admin)
db.session.commit()
print(f"[DB] Created default admin user: {DEFAULT_ADMIN_USERNAME}", flush=True)
print("[DB] Default admin user created (admin/admin123)", flush=True)
else:
print("[DB] Admin user already exists", flush=True)