]> git.giorgioravera.it Git - network-manager.git/commitdiff
Updated config db and added cache
authorGiorgio Ravera <giorgio.ravera@gmail.com>
Thu, 12 Mar 2026 17:03:53 +0000 (18:03 +0100)
committerGiorgio Ravera <giorgio.ravera@gmail.com>
Thu, 12 Mar 2026 17:03:53 +0000 (18:03 +0100)
backend/db/config.py
backend/routes/dns.py
backend/routes/login.py

index add67e25cedc43bd4f20212527476e25faec2aed..8d877e4099511f9ef928f5e184ed5f84e23ee38c 100644 (file)
@@ -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")
index e5d18c8293a15afa13f85c60a4e3b7a10a568595..68851e4537da2d0d28a7fdf9e881b171438fdebe 100644 (file)
@@ -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
index 608ba8564b811561bcd636c8bb7fe586ef98645f..d454b4a9ad84a520f3b81937ab22021d9701abb9 100644 (file)
@@ -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={