rewrite
This commit is contained in:
56
app.py
56
app.py
@@ -12,7 +12,7 @@ from flask import Flask, render_template, redirect, url_for, session
|
|||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
|
||||||
from config.settings import *
|
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.main_routes import main_bp
|
||||||
from routes.edit_routes import edit_bp
|
from routes.edit_routes import edit_bp
|
||||||
from routes.auth_routes import auth_bp
|
from routes.auth_routes import auth_bp
|
||||||
@@ -60,7 +60,6 @@ app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
|
|||||||
print("[APP] Initializing database...", flush=True)
|
print("[APP] Initializing database...", flush=True)
|
||||||
db.init_app(app)
|
db.init_app(app)
|
||||||
migrate.init_app(app, db)
|
migrate.init_app(app, db)
|
||||||
# ❌ USUŃ TĘ LINIĘ: init_db(app)
|
|
||||||
print("[APP] Database initialized", flush=True)
|
print("[APP] Database initialized", flush=True)
|
||||||
|
|
||||||
|
|
||||||
@@ -87,23 +86,26 @@ private_key_path = None
|
|||||||
ssl_context = None
|
ssl_context = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
config_ssl = configparser.ConfigParser()
|
if os.path.exists(SSL_INI):
|
||||||
config_ssl.read(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 os.path.exists(certificate_path) and os.path.exists(private_key_path):
|
if config_ssl.has_section('ssl'):
|
||||||
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
|
certificate_path = config_ssl.get('ssl', 'certificate_path')
|
||||||
ssl_context.load_cert_chain(certfile=certificate_path, keyfile=private_key_path)
|
private_key_path = config_ssl.get('ssl', '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:
|
else:
|
||||||
print(f"[APP] SSL certificate files not found", flush=True)
|
print(f"[APP] No [ssl] section in {SSL_INI}", flush=True)
|
||||||
print(f" Certificate: {certificate_path}", flush=True)
|
|
||||||
print(f" Private Key: {private_key_path}", flush=True)
|
|
||||||
else:
|
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:
|
except Exception as e:
|
||||||
print(f"[APP] SSL warning (non-critical): {e}", flush=True)
|
print(f"[APP] SSL warning (non-critical): {e}", flush=True)
|
||||||
@@ -182,8 +184,6 @@ def make_shell_context():
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# ===== APPLICATION CONTEXT =====
|
|
||||||
|
|
||||||
@app.before_request
|
@app.before_request
|
||||||
def before_request():
|
def before_request():
|
||||||
"""Run before each request"""
|
"""Run before each request"""
|
||||||
@@ -201,10 +201,8 @@ def after_request(response):
|
|||||||
@app.cli.command()
|
@app.cli.command()
|
||||||
def init_db_cli():
|
def init_db_cli():
|
||||||
"""Initialize database"""
|
"""Initialize database"""
|
||||||
with app.app_context():
|
init_db(app)
|
||||||
from database import init_db
|
print("[CLI] Database initialized successfully", flush=True)
|
||||||
init_db(app)
|
|
||||||
print("[CLI] Database initialized successfully")
|
|
||||||
|
|
||||||
|
|
||||||
@app.cli.command()
|
@app.cli.command()
|
||||||
@@ -229,16 +227,6 @@ def create_admin():
|
|||||||
print(f"[CLI] Admin user '{username}' created successfully")
|
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 =====
|
# ===== MAIN ENTRY POINT =====
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
@@ -253,9 +241,7 @@ if __name__ == '__main__':
|
|||||||
print(f"[APP] Running on: https://[::]:5000 (IPv6)", flush=True)
|
print(f"[APP] Running on: https://[::]:5000 (IPv6)", flush=True)
|
||||||
|
|
||||||
# Initialize database before running
|
# Initialize database before running
|
||||||
with app.app_context():
|
init_db(app)
|
||||||
from database import init_db
|
|
||||||
init_db(app)
|
|
||||||
|
|
||||||
app.run(
|
app.run(
|
||||||
host='::',
|
host='::',
|
||||||
|
|||||||
@@ -1,39 +1,48 @@
|
|||||||
"""Application Settings and Configuration"""
|
"""Application Settings"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
# ===== FLASK =====
|
# ===== ENVIRONMENT =====
|
||||||
DEBUG = os.environ.get('FLASK_DEBUG', False)
|
DEBUG = os.getenv('FLASK_DEBUG', 'False').lower() == 'true'
|
||||||
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production')
|
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 =====
|
# ===== DATABASE =====
|
||||||
BASEDIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
|
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||||
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
|
'DATABASE_URL',
|
||||||
f'sqlite:///{os.path.join(BASEDIR, "instance", "app.db")}'
|
f'sqlite:///{os.path.join(INSTANCE_DIR, "app.db")}'
|
||||||
|
)
|
||||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
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)
|
PERMANENT_SESSION_LIFETIME = timedelta(days=7)
|
||||||
SESSION_COOKIE_SECURE = True
|
SESSION_COOKIE_SECURE = True
|
||||||
SESSION_COOKIE_HTTPONLY = True
|
SESSION_COOKIE_HTTPONLY = True
|
||||||
SESSION_COOKIE_SAMESITE = 'Lax'
|
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 =====
|
||||||
HAPROXY_CONFIG_PATH = '/etc/haproxy/haproxy.cfg'
|
HAPROXY_CONFIG_PATH = os.getenv('HAPROXY_CONFIG_PATH', '/etc/haproxy/haproxy.cfg')
|
||||||
HAPROXY_BACKUP_DIR = os.path.join(BASEDIR, 'backups')
|
HAPROXY_BACKUP_DIR = os.path.join(BASE_DIR, 'backups')
|
||||||
HAPROXY_STATS_PORT = 8404 # Hardcoded na stałe dla statystyk
|
HAPROXY_STATS_PORT = int(os.getenv('HAPROXY_STATS_PORT', '8404'))
|
||||||
HAPROXY_LOG_FILE = '/var/log/haproxy.log'
|
|
||||||
|
|
||||||
# ===== DEFAULT AUTH =====
|
# ===== SSL =====
|
||||||
DEFAULT_ADMIN_USERNAME = os.environ.get('ADMIN_USERNAME', 'admin')
|
SSL_INI = os.path.join(BASE_DIR, 'config', 'ssl.ini')
|
||||||
DEFAULT_ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'admin123')
|
|
||||||
|
# ===== MAX UPLOAD SIZE =====
|
||||||
|
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16MB
|
||||||
|
|
||||||
# ===== LOGGING =====
|
# ===== 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)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Database initialization"""
|
"""Database module initialization"""
|
||||||
|
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
from flask_migrate import Migrate
|
from flask_migrate import Migrate
|
||||||
@@ -6,22 +6,21 @@ from flask_migrate import Migrate
|
|||||||
db = SQLAlchemy()
|
db = SQLAlchemy()
|
||||||
migrate = Migrate()
|
migrate = Migrate()
|
||||||
|
|
||||||
|
|
||||||
def init_db(app):
|
def init_db(app):
|
||||||
"""Initialize database with app"""
|
"""Initialize database - create tables"""
|
||||||
db.init_app(app)
|
|
||||||
migrate.init_app(app, db)
|
|
||||||
|
|
||||||
# Create tables
|
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
db.create_all()
|
db.create_all()
|
||||||
|
print("[DB] All tables created successfully", flush=True)
|
||||||
|
|
||||||
# Create default admin user if not exists
|
|
||||||
from database.models import User
|
from database.models import User
|
||||||
admin = User.query.filter_by(username='admin').first()
|
admin = User.query.filter_by(username='admin').first()
|
||||||
|
|
||||||
if not admin:
|
if not admin:
|
||||||
from config.settings import DEFAULT_ADMIN_USERNAME, DEFAULT_ADMIN_PASSWORD
|
admin = User(username='admin', is_admin=True)
|
||||||
admin = User(username=DEFAULT_ADMIN_USERNAME)
|
admin.set_password('admin123')
|
||||||
admin.set_password(DEFAULT_ADMIN_PASSWORD)
|
|
||||||
db.session.add(admin)
|
db.session.add(admin)
|
||||||
db.session.commit()
|
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)
|
||||||
|
|||||||
Reference in New Issue
Block a user