82 lines
2.6 KiB
Python
82 lines
2.6 KiB
Python
from flask import Flask
|
|
from .database.SlidingSqlite.SlidingSqlite import SlidingSQLite
|
|
import os
|
|
import configparser
|
|
import json
|
|
|
|
def load_admin_api_key(app):
|
|
"""Load admin API key from config file, env var, or database."""
|
|
admin_key = None
|
|
|
|
# 1. Try environment variable
|
|
admin_key = os.getenv('ADMIN_API_KEY')
|
|
if admin_key:
|
|
app.config['ADMIN_API_KEY'] = admin_key
|
|
return
|
|
|
|
# 2. Try config file (e.g., /app/config.ini or /app/config.json)
|
|
config_file = '/app/config.ini'
|
|
if os.path.exists(config_file):
|
|
config = configparser.ConfigParser()
|
|
config.read(config_file)
|
|
admin_key = config.get('auth', 'admin_api_key', fallback=None)
|
|
elif os.path.exists('/app/config.json'):
|
|
config_file = '/app/config.json'
|
|
with open(config_file, 'r') as f:
|
|
config = json.load(f)
|
|
admin_key = config.get('auth', {}).get('admin_api_key')
|
|
|
|
if admin_key:
|
|
app.config['ADMIN_API_KEY'] = admin_key
|
|
return
|
|
|
|
# Check database
|
|
query = "SELECT api_key FROM admin_keys LIMIT 1"
|
|
result = app.db.execute_read_sync(query)
|
|
if result.success and result.data:
|
|
app.config['ADMIN_API_KEY'] = result.data[0][0]
|
|
return
|
|
|
|
# Generate and store a new key
|
|
import secrets
|
|
default_key = secrets.token_hex(16)
|
|
app.config['ADMIN_API_KEY'] = default_key
|
|
app.db.execute_write(
|
|
"INSERT INTO admin_keys (api_key, description) VALUES (?, ?)",
|
|
(default_key, "Default admin key created on bootstrap")
|
|
)
|
|
# Log the default key (in a real app, you'd log this securely)
|
|
print(f"Generated and stored default admin API key: {default_key}")
|
|
|
|
def create_app():
|
|
app = Flask(__name__)
|
|
|
|
# Configuration
|
|
# app.config['DB_DIR'] = '/home/kalzu/src/ai-coding/node-monitor/temp_data/data/db' # Change this for container!
|
|
app.config['DB_DIR'] = '/data/db' # This is container version
|
|
app.config['RETENTION_PERIOD'] = 604800 # 7 days
|
|
app.config['ROTATION_INTERVAL'] = 3600 # 1 hour
|
|
|
|
# Load schema
|
|
with open(os.path.join(os.path.dirname(__file__), 'database', 'schema.sql'), 'r') as f:
|
|
schema = f.read()
|
|
|
|
# Initialize SlidingSQLite
|
|
app.db = SlidingSQLite(
|
|
db_dir=app.config['DB_DIR'],
|
|
schema=schema,
|
|
retention_period=app.config['RETENTION_PERIOD'],
|
|
rotation_interval=app.config['ROTATION_INTERVAL']
|
|
)
|
|
|
|
# Load admin API key
|
|
load_admin_api_key(app)
|
|
|
|
# Register blueprints
|
|
from .api import routes as api_routes
|
|
from .web import routes as web_routes
|
|
app.register_blueprint(api_routes.bp)
|
|
app.register_blueprint(web_routes.bp)
|
|
|
|
return app
|