From: Giorgio Ravera Date: Thu, 12 Mar 2026 17:03:53 +0000 (+0100) Subject: Updated config db and added cache X-Git-Url: http://git.giorgioravera.it/?a=commitdiff_plain;h=776d2d5f2293cf87083b9992a725272075a59d41;p=network-manager.git Updated config db and added cache --- diff --git a/backend/db/config.py b/backend/db/config.py index add67e2..8d877e4 100644 --- a/backend/db/config.py +++ b/backend/db/config.py @@ -14,29 +14,73 @@ from backend.log.log import setup_logging, get_logger # Logger initialization logger = get_logger(__name__) -# ----------------------------- -# Return a specific config value -# ----------------------------- +# --------------------------------------------------------- +# Type mapping for config keys +# --------------------------------------------------------- +CONFIG_TYPES = { + "external_name": str, + "login_max_attempts": int, + "login_window_seconds": int, +} + +# --------------------------------------------------------- +# Runtime cache to avoid repeated DB queries +# --------------------------------------------------------- +_config_cache = {} + +def invalidate_config(key=None): + """Clear cached config entry (or full cache).""" + if key: + _config_cache.pop(key, None) + else: + _config_cache.clear() + +# --------------------------------------------------------- +# Return a specific config value (with cache + type casting) +# --------------------------------------------------------- def get_config(key): + # ---- Cache hit ---- + if key in _config_cache: + return _config_cache[key] + + # ---- Read from DB ---- conn = get_db() cur = conn.execute("SELECT value FROM config WHERE key = ?", (key,)) row = cur.fetchone() - return row["value"] if row else None -# ----------------------------- + if not row: + return None + + raw_value = row["value"] + + # ---- Type casting ---- + caster = CONFIG_TYPES.get(key, str) + try: + value = caster(raw_value) + except Exception: + value = raw_value # fallback safe + + # ---- Save in cache ---- + _config_cache[key] = value + return value + +# --------------------------------------------------------- # Initialize Config DB Table -# ----------------------------- +# --------------------------------------------------------- @register_init def init_db_hosts_table(cur): - # SETTINGS TABLE + # CONFIG TABLE cur.execute(""" CREATE TABLE config ( key TEXT PRIMARY KEY, value TEXT ); """) - cur.execute("INSERT INTO config (key, value) VALUES (?, ?)", ("domain", settings.DOMAIN)) + + # Initial values from settings (as strings in DB) cur.execute("INSERT INTO config (key, value) VALUES (?, ?)", ("external_name", settings.EXTERNAL_NAME)) + cur.execute("INSERT INTO config (key, value) VALUES (?, ?)", ("login_max_attempts", str(settings.LOGIN_MAX_ATTEMPTS))) + cur.execute("INSERT INTO config (key, value) VALUES (?, ?)", ("login_window_seconds", str(settings.LOGIN_WINDOW_SECONDS))) logger.info("CONFIG DB: Tables initialized successfully") diff --git a/backend/routes/dns.py b/backend/routes/dns.py index e5d18c8..68851e4 100644 --- a/backend/routes/dns.py +++ b/backend/routes/dns.py @@ -44,9 +44,6 @@ async def api_dns_reload(request: Request): line = f"{h.get('name')}\t\t IN\tA\t{h.get('ipv4')}\n" f.write(line) - # Get Domain - domain = get_config("domain") - # Save DNS Reverse Configuration path = settings.DNS_REVERSE_FILE with open(path, "w", encoding="utf-8") as f: @@ -55,7 +52,7 @@ async def api_dns_reload(request: Request): if ip: parts = ip.split(".") rev = f"{parts[-1]}.{parts[-2]}" - line = f"{rev}\t\t IN PTR\t{h.get('name')}.{domain}\n" + line = f"{rev}\t\t IN PTR\t{h.get('name')}.{settings.DOMAIN}\n" f.write(line) # Get Aliases List diff --git a/backend/routes/login.py b/backend/routes/login.py index 608ba85..d454b4a 100644 --- a/backend/routes/login.py +++ b/backend/routes/login.py @@ -7,6 +7,7 @@ import os import time # Import local modules +from backend.db.config import get_config from backend.security import verify_login, apply_session, close_session # Import Settings & Logging @@ -22,9 +23,9 @@ def check_rate_limit(ip: str): now = time.time() attempts = login_attempts.get(ip, []) # tieni solo tentativi negli ultimi LOGIN_WINDOW_SECONDS secondi - attempts = [t for t in attempts if now - t < settings.LOGIN_WINDOW_SECONDS] + attempts = [t for t in attempts if now - t < int(get_config("login_window_seconds"))] - if len(attempts) >= settings.LOGIN_MAX_ATTEMPTS: + if len(attempts) >= int(get_config("login_max_attempts")): raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail={