Просмотр исходного кода

feat(blacklist): add BlacklistDomain model and related database functionality

Manuel 9 месяцев назад
Родитель
Сommit
4ac320bfbe

+ 62 - 0
alembic/versions/003_add_blacklist_domains.py

@@ -0,0 +1,62 @@
+"""Add blacklist_domains table
+
+Revision ID: 003_add_blacklist_domains
+Revises: 002_expand_varchar_columns
+Create Date: 2026-02-28 12:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy import inspect
+
+# revision identifiers, used by Alembic.
+revision: str = "003_add_blacklist_domains"
+down_revision: str | None = "002_expand_varchar_columns"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+    """Create blacklist_domains table."""
+    conn = op.get_bind()
+    inspector = inspect(conn)
+
+    if not inspector.has_table("blacklist_domains"):
+        op.create_table(
+            "blacklist_domains",
+            sa.Column("id", sa.Integer(), nullable=False),
+            sa.Column("domain", sa.String(length=255), nullable=False),
+            sa.Column("source", sa.String(length=50), nullable=True),
+            sa.Column("source_url", sa.String(length=512), nullable=True),
+            sa.Column("added_by", sa.String(length=100), nullable=True),
+            sa.Column("notes", sa.Text(), nullable=True),
+            sa.Column("active", sa.Integer(), nullable=True, default=1),
+            sa.Column("created_at", sa.DateTime(), nullable=False),
+            sa.Column("updated_at", sa.DateTime(), nullable=True),
+            sa.PrimaryKeyConstraint("id"),
+            sa.UniqueConstraint("domain"),
+        )
+
+        # Index on domain for fast lookups
+        op.create_index("ix_blacklist_domains_domain", "blacklist_domains", ["domain"])
+    else:
+        # Table already exists; skip creation to allow idempotent upgrades
+        print("Skipping creation of 'blacklist_domains' because it already exists")
+
+
+def downgrade() -> None:
+    """Drop blacklist_domains table."""
+    conn = op.get_bind()
+    inspector = inspect(conn)
+    if inspector.has_table("blacklist_domains"):
+        # Drop index first if exists
+        try:
+            op.drop_index("ix_blacklist_domains_domain", table_name="blacklist_domains")
+        except Exception:
+            pass
+        op.drop_table("blacklist_domains")
+    else:
+        print("'blacklist_domains' does not exist, skipping downgrade for this table")

+ 9 - 3
database/database.py

@@ -24,6 +24,7 @@ from database.models import (
     Notification,
     SystemMetrics,
 )
+from database.models.models import BlacklistDomain
 from database.models.models import create_dynamic_models
 
 _engine = None
@@ -215,6 +216,7 @@ def create_dynamic_tables(engine, date_suffix: str = None):
     DeniedLog.__table__.create(engine, checkfirst=True)
     SystemMetrics.__table__.create(engine, checkfirst=True)
     Notification.__table__.create(engine, checkfirst=True)  # Add notifications table
+    BlacklistDomain.__table__.create(engine, checkfirst=True)
 
     user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
 
@@ -226,9 +228,12 @@ def create_dynamic_tables(engine, date_suffix: str = None):
         logger.info(
             f"Creating dynamic tables for date suffix '{date_suffix}': {user_table_name}, {log_table_name}"
         )
-        DynamicBase = declarative_base()
-
-        DynamicBase.metadata.create_all(engine, checkfirst=True)
+        # Use create_dynamic_models to define and create the per-day user/log tables
+        try:
+            create_dynamic_models(engine, user_table_name, log_table_name)
+        except Exception as e:
+            logger.error(f"Error creating dynamic user/log tables: {e}")
+            raise
 
 
 def get_dynamic_table_names(date_suffix: str = None) -> tuple[str, str]:
@@ -319,6 +324,7 @@ def migrate_database():
                     and inspector.has_table("system_metrics")
                     and inspector.has_table("notifications")
                     and inspector.has_table("admin_users")
+                    and inspector.has_table("blacklist_domains")
                 )
 
                 if core_tables_exist:

+ 14 - 0
database/models/models.py

@@ -89,6 +89,20 @@ class Notification(Base):
     count = Column(Integer, default=1)
 
 
+class BlacklistDomain(Base):
+    __tablename__ = "blacklist_domains"
+
+    id = Column(Integer, primary_key=True, autoincrement=True)
+    domain = Column(String(255), nullable=False, unique=True, index=True)
+    source = Column(String(50), nullable=True)  # e.g. 'file', 'url', 'custom'
+    source_url = Column(String(512), nullable=True)
+    added_by = Column(String(100), nullable=True)
+    notes = Column(Text, nullable=True)
+    active = Column(Integer, default=1)
+    created_at = Column(DateTime, default=datetime.now, nullable=False)
+    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
+
+
 class AdminUser(Base):
     __tablename__ = "admin_users"
 

+ 11 - 3
routes/admin_routes.py

@@ -26,6 +26,8 @@ from services.blacklist_service import (
     save_custom_list,
     test_pihole_connection,
 )
+from database.database import get_session
+from database.models.models import BlacklistDomain
 from services.config_service import save_config as service_save_config
 from services.db_admin_service import delete_table_data as service_delete_table_data
 from services.db_info_service import get_tables_info as service_get_tables_info
@@ -248,8 +250,14 @@ def manage_http_access():
 def manage_blacklist():
     """Render the blacklist management UI."""
     env_vars = load_env_vars()
-    # Provide current blacklist domains to the template
-    blacklist = env_vars.get("BLACKLIST_DOMAINS", "")
+    # Provide current blacklist domains to the template — now read from DB
+    session = get_session()
+    try:
+        rows = session.query(BlacklistDomain).filter(BlacklistDomain.active == 1).order_by(BlacklistDomain.domain).all()
+        blacklist = ",".join([r.domain for r in rows])
+    finally:
+        session.close()
+
     return render_template(
         "admin/blacklist.html", env_vars=env_vars, blacklist=blacklist
     )
@@ -309,7 +317,7 @@ def blacklist_import():
 
     # Merge with existing and save
     try:
-        merge_and_save_blacklist(env_vars, domains)
+        merge_and_save_blacklist(domains)
         flash("Blacklist actualizada exitosamente", "success")
     except Exception as e:
         logger.exception("Error guardando BLACKLIST_DOMAINS")

+ 92 - 15
services/blacklist_service.py

@@ -1,7 +1,9 @@
 import requests
+from datetime import datetime
 from loguru import logger
 
-from services.admin_helpers import load_env_vars, save_env_vars
+from database.database import get_session
+from database.models.models import BlacklistDomain
 
 
 def test_pihole_connection(host: str, token: str | None = None) -> tuple[bool, str]:
@@ -72,19 +74,94 @@ def import_domains_from_url(url: str) -> tuple[bool, set, str]:
         return False, domains, str(e)
 
 
-def merge_and_save_blacklist(existing_env: dict, new_domains: set) -> None:
-    existing = [
-        d.strip()
-        for d in existing_env.get("BLACKLIST_DOMAINS", "").split(",")
-        if d.strip()
-    ]
-    merged = set(existing)
-    merged.update(new_domains)
-    existing_env["BLACKLIST_DOMAINS"] = ",".join(sorted(merged))
-    save_env_vars(existing_env)
+def merge_and_save_blacklist(new_domains: set, source: str = "import", source_url: str | None = None, added_by: str | None = None) -> None:
+    """Merge given domains into the `blacklist_domains` table.
 
+    - new_domains: set of domain strings
+    - source: string describing origin ('file', 'url', 'custom', ...)
+    - source_url: optional url if source is 'url'
+    - added_by: optional username who added the entries
+    """
+    if not new_domains:
+        return
 
-def save_custom_list(items: list) -> None:
-    env_vars = load_env_vars()
-    env_vars["BLACKLIST_DOMAINS"] = ",".join(sorted(set(items)))
-    save_env_vars(env_vars)
+    session = get_session()
+    try:
+        now = datetime.now()
+        for domain in new_domains:
+            domain = domain.strip()
+            if not domain:
+                continue
+            existing = (
+                session.query(BlacklistDomain).filter(BlacklistDomain.domain == domain).one_or_none()
+            )
+            if existing:
+                # reactivate and update metadata if necessary
+                existing.active = 1
+                existing.source = source or existing.source
+                if source_url:
+                    existing.source_url = source_url
+                if added_by:
+                    existing.added_by = added_by
+                existing.updated_at = now
+            else:
+                record = BlacklistDomain(
+                    domain=domain,
+                    source=source,
+                    source_url=source_url,
+                    added_by=added_by,
+                    active=1,
+                    created_at=now,
+                    updated_at=now,
+                )
+                session.add(record)
+        session.commit()
+    except Exception as e:
+        logger.exception("Error guardando blacklist en DB")
+        session.rollback()
+        raise
+    finally:
+        session.close()
+
+
+def save_custom_list(items: list, added_by: str | None = None) -> None:
+    """Replace existing 'custom' source blacklist entries with `items`.
+
+    This keeps other sources intact.
+    """
+    session = get_session()
+    try:
+        # Deactivate previous custom entries
+        session.query(BlacklistDomain).filter(BlacklistDomain.source == "custom").update({"active": 0})
+
+        now = datetime.now()
+        for d in sorted(set(items)):
+            domain = d.strip()
+            if not domain:
+                continue
+            existing = (
+                session.query(BlacklistDomain).filter(BlacklistDomain.domain == domain).one_or_none()
+            )
+            if existing:
+                existing.active = 1
+                existing.source = "custom"
+                if added_by:
+                    existing.added_by = added_by
+                existing.updated_at = now
+            else:
+                record = BlacklistDomain(
+                    domain=domain,
+                    source="custom",
+                    added_by=added_by,
+                    active=1,
+                    created_at=now,
+                    updated_at=now,
+                )
+                session.add(record)
+        session.commit()
+    except Exception as e:
+        logger.exception("Error guardando lista personalizada en DB")
+        session.rollback()
+        raise
+    finally:
+        session.close()