database.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. import os
  2. import re
  3. import sqlite3
  4. import time
  5. import uuid
  6. from datetime import date, datetime
  7. from pathlib import Path
  8. from typing import Any
  9. from urllib.parse import unquote, urlparse
  10. from alembic.config import Config as AlembicConfig
  11. from alembic.runtime.migration import MigrationContext
  12. from loguru import logger
  13. from sqlalchemy import (
  14. Column,
  15. Integer,
  16. MetaData,
  17. Table,
  18. create_engine,
  19. event,
  20. func,
  21. inspect,
  22. text,
  23. )
  24. from sqlalchemy.exc import IntegrityError, OperationalError
  25. from sqlalchemy.orm import sessionmaker
  26. from alembic import command
  27. from config import Config
  28. from database.base import Base # noqa: F401
  29. from database.models import (
  30. AdminUser,
  31. DeniedLog,
  32. LogMetadata,
  33. Notification,
  34. SystemMetrics,
  35. )
  36. from database.models.models import BlacklistDomain, create_dynamic_models
  37. _engine = None
  38. _Session = None
  39. dynamic_model_cache: dict[str, Any] = {}
  40. # SQLite startup failures can be transient when another process is closing the
  41. # database or when its WAL files are being initialized. Keep this bounded so
  42. # a permanent filesystem/corruption problem fails clearly instead of hanging
  43. # application startup forever.
  44. SQLITE_MIGRATION_RETRY_DELAYS = (1.0, 2.0, 4.0)
  45. def _clean_connection_string(connection_string: str | None) -> str:
  46. """Remove whitespace and accidental outer quotes from a DB URL."""
  47. return str(connection_string or "").strip().strip("\"'").strip()
  48. def _parse_server_database_name(connection_string: str) -> tuple[Any, str]:
  49. """Parse and validate a database URL used for server-level creation."""
  50. cleaned_connection = _clean_connection_string(connection_string)
  51. parsed_url = urlparse(cleaned_connection)
  52. database_name = unquote(parsed_url.path.lstrip("/")).strip().strip("\"'")
  53. if not database_name:
  54. raise ValueError("No database name found in connection string")
  55. if not re.fullmatch(r"[A-Za-z0-9_$.-]+", database_name):
  56. raise ValueError(
  57. "Database name contains unsupported characters; use only letters, "
  58. "numbers, '.', '-', '_' or '$'."
  59. )
  60. return parsed_url, database_name
  61. def get_table_suffix() -> str:
  62. return date.today().strftime("%Y%m%d")
  63. def _normalize_sqlite_path(path_str: str) -> Path:
  64. path_str = path_str.strip()
  65. if path_str in ("", "."):
  66. raise ValueError(
  67. "DATABASE_STRING_CONNECTION for SQLITE must contain a database path"
  68. )
  69. if path_str == ":memory:" or path_str == "sqlite:///:memory:":
  70. return Path(":memory:")
  71. if path_str.startswith("sqlite:///"):
  72. path_str = path_str[len("sqlite:///") :]
  73. if not path_str:
  74. raise ValueError(
  75. "DATABASE_STRING_CONNECTION for SQLITE must contain a database path"
  76. )
  77. project_root = Path(__file__).resolve().parents[1]
  78. db_path = Path(path_str)
  79. if not db_path.is_absolute():
  80. db_path = project_root / db_path
  81. if path_str.endswith("/") or db_path.is_dir():
  82. db_path = db_path / "squidstats.db"
  83. return db_path
  84. def get_database_url() -> str:
  85. db_type = Config.DATABASE_TYPE
  86. conn_str = _clean_connection_string(Config.DATABASE_STRING_CONNECTION)
  87. if db_type == "SQLITE":
  88. db_path = _normalize_sqlite_path(conn_str)
  89. if str(db_path) == ":memory:":
  90. return "sqlite:///:memory:"
  91. return f"sqlite:///{db_path}"
  92. elif db_type in ("MYSQL", "MARIADB"):
  93. # Ejemplo: mysql+pymysql://user:password@host/dbname
  94. # El usuario debe poner el string completo en el .env
  95. if (
  96. conn_str.startswith("mysql://")
  97. or conn_str.startswith("mariadb://")
  98. or conn_str.startswith("mysql+pymysql://")
  99. ):
  100. return conn_str
  101. raise ValueError(
  102. "DATABASE_STRING_CONNECTION must start with 'mysql://' or 'mariadb://'."
  103. )
  104. elif db_type in ("POSTGRESQL", "POSTGRES"):
  105. # Ejemplo: postgresql://user:password@host:port/dbname
  106. # o postgresql+psycopg2://user:password@host:port/dbname
  107. if (
  108. conn_str.startswith("postgresql://")
  109. or conn_str.startswith("postgres://")
  110. or conn_str.startswith("postgresql+psycopg2://")
  111. or conn_str.startswith("postgresql+psycopg://")
  112. ):
  113. return conn_str
  114. raise ValueError(
  115. "DATABASE_STRING_CONNECTION must start with 'postgresql://', 'postgres://', 'postgresql+psycopg2://', or 'postgresql+psycopg://'."
  116. )
  117. else:
  118. raise ValueError(f"Database type not supported: {db_type}")
  119. def create_database_if_not_exists():
  120. db_type = Config.DATABASE_TYPE
  121. if db_type == "SQLITE":
  122. # SQLite crea el archivo automáticamente, no necesitamos hacer nada
  123. logger.info("SQLite database will be created automatically if it doesn't exist")
  124. return
  125. elif db_type in ("MYSQL", "MARIADB"):
  126. try:
  127. conn_str = _clean_connection_string(Config.DATABASE_STRING_CONNECTION)
  128. parsed_url, database_name = _parse_server_database_name(conn_str)
  129. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/"
  130. server_engine = create_engine(server_url, echo=False)
  131. try:
  132. with server_engine.connect() as conn:
  133. # Verificar si la base de datos existe
  134. result = conn.execute(
  135. text(
  136. "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = :dbname"
  137. ),
  138. {"dbname": database_name},
  139. )
  140. if not result.fetchone():
  141. # Database names cannot be bound as SQL parameters. The
  142. # name is strictly validated by _parse_server_database_name
  143. # before it reaches this statement.
  144. conn.execute(
  145. text(
  146. f"CREATE DATABASE IF NOT EXISTS `{database_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" # noqa: S608
  147. )
  148. )
  149. conn.commit()
  150. logger.info(f"Database '{database_name}' created successfully")
  151. else:
  152. logger.info(f"Database '{database_name}' already exists")
  153. finally:
  154. server_engine.dispose()
  155. except Exception as e:
  156. logger.error(f"Error creating MySQL/MariaDB database: {e}")
  157. raise
  158. elif db_type in ("POSTGRESQL", "POSTGRES"):
  159. try:
  160. conn_str = _clean_connection_string(Config.DATABASE_STRING_CONNECTION)
  161. parsed_url, database_name = _parse_server_database_name(conn_str)
  162. # Crear URL para conectarse a la base de datos 'postgres' (default)
  163. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/postgres"
  164. # Crear engine con autocommit para evitar transacciones automáticas
  165. server_engine = create_engine(
  166. server_url, echo=False, isolation_level="AUTOCOMMIT"
  167. )
  168. quoted_database_name = server_engine.dialect.identifier_preparer.quote(
  169. database_name
  170. )
  171. try:
  172. with server_engine.connect() as conn:
  173. # Verificar si la base de datos existe
  174. result = conn.execute(
  175. text("SELECT 1 FROM pg_database WHERE datname = :dbname"),
  176. {"dbname": database_name},
  177. )
  178. if not result.fetchone():
  179. # La base de datos no existe, crearla
  180. # Usar una versión más simple que sea compatible con la mayoría de configuraciones
  181. try:
  182. # Primero intentar con template0 para evitar problemas de collation
  183. conn.execute(
  184. text(
  185. f"CREATE DATABASE {quoted_database_name} WITH ENCODING = 'UTF8' TEMPLATE = template0" # noqa: S608
  186. )
  187. )
  188. logger.info(
  189. f"PostgreSQL database '{database_name}' created successfully with template0"
  190. )
  191. except Exception:
  192. # Si falla con template0, intentar sin especificar collation
  193. try:
  194. conn.execute(
  195. text(
  196. f"CREATE DATABASE {quoted_database_name} WITH ENCODING = 'UTF8'" # noqa: S608
  197. )
  198. )
  199. logger.info(
  200. f"PostgreSQL database '{database_name}' created successfully without collation"
  201. )
  202. except Exception:
  203. # Como último recurso, crear la base de datos sin especificar encoding
  204. conn.execute(
  205. text(f"CREATE DATABASE {quoted_database_name}") # noqa: S608
  206. )
  207. logger.info(
  208. f"PostgreSQL database '{database_name}' created successfully with default settings"
  209. )
  210. else:
  211. logger.info(
  212. f"PostgreSQL database '{database_name}' already exists"
  213. )
  214. finally:
  215. server_engine.dispose()
  216. except Exception as e:
  217. logger.error(f"Error creating PostgreSQL database: {e}")
  218. raise
  219. def get_engine():
  220. global _engine
  221. if _engine is not None:
  222. return _engine
  223. create_database_if_not_exists()
  224. db_url = get_database_url()
  225. db_type = Config.DATABASE_TYPE
  226. if db_type == "SQLITE":
  227. _engine = create_engine(
  228. db_url,
  229. echo=False,
  230. future=True,
  231. connect_args={"timeout": 30, "check_same_thread": False},
  232. )
  233. # Enable WAL journal mode and set synchronous=NORMAL for the connection.
  234. # WAL allows concurrent reads while a write is in progress and dramatically
  235. # reduces "database is locked" errors in multi-threaded apps.
  236. @event.listens_for(_engine, "connect")
  237. def set_sqlite_pragmas(dbapi_conn, _connection_record):
  238. cursor = dbapi_conn.cursor()
  239. cursor.execute("PRAGMA journal_mode=WAL")
  240. cursor.execute("PRAGMA synchronous=NORMAL")
  241. cursor.execute("PRAGMA busy_timeout=30000")
  242. cursor.close()
  243. else:
  244. _engine = create_engine(db_url, echo=False, future=True)
  245. return _engine
  246. def get_session():
  247. global _Session
  248. engine = get_engine()
  249. if _Session is None:
  250. create_dynamic_tables(engine)
  251. _Session = sessionmaker(bind=engine)
  252. return _Session()
  253. def table_exists(engine, table_name: str) -> bool:
  254. inspector = inspect(engine)
  255. return inspector.has_table(table_name)
  256. def create_dynamic_tables(engine, date_suffix: str = None):
  257. """Create every static table and the dynamic tables for one day.
  258. ``create_all(checkfirst=True)`` is intentionally used here in addition to
  259. Alembic. Alembic tracks *schema versions*, but a table can be deleted
  260. manually while the version remains at ``head``; in that case Alembic has
  261. no pending migration to run. SQLAlchemy creates only tables that are
  262. absent and leaves existing tables and their data untouched.
  263. """
  264. existing_tables = set(inspect(engine).get_table_names())
  265. # All models that inherit from database.base.Base are registered in this
  266. # metadata, including tables added in later migrations.
  267. Base.metadata.create_all(engine, checkfirst=True)
  268. LogMetadata.__table__.create(engine, checkfirst=True)
  269. DeniedLog.__table__.create(engine, checkfirst=True)
  270. SystemMetrics.__table__.create(engine, checkfirst=True)
  271. Notification.__table__.create(engine, checkfirst=True) # Add notifications table
  272. BlacklistDomain.__table__.create(engine, checkfirst=True)
  273. # New quota tables for the admin quota feature
  274. from database.models.models import QuotaEvent, QuotaGroup, QuotaRule, QuotaUser
  275. QuotaUser.__table__.create(engine, checkfirst=True)
  276. QuotaGroup.__table__.create(engine, checkfirst=True)
  277. QuotaRule.__table__.create(engine, checkfirst=True)
  278. QuotaEvent.__table__.create(engine, checkfirst=True)
  279. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  280. logger.info(f"CreateTable_{date_suffix or 'today'}")
  281. if not table_exists(engine, user_table_name) or not table_exists(
  282. engine, log_table_name
  283. ):
  284. logger.info(
  285. f"Creating dynamic tables for date suffix '{date_suffix}': {user_table_name}, {log_table_name}"
  286. )
  287. # Use create_dynamic_models to define and create the per-day user/log tables
  288. try:
  289. create_dynamic_models(engine, user_table_name, log_table_name)
  290. except Exception as e:
  291. logger.error(f"Error creating dynamic user/log tables: {e}")
  292. raise
  293. created_tables = sorted(
  294. set(inspect(engine).get_table_names()).difference(existing_tables)
  295. )
  296. if created_tables:
  297. logger.warning(
  298. "Database schema repair created missing tables: {}",
  299. ", ".join(created_tables),
  300. )
  301. def repair_database_schema(engine, date_suffix: str = None) -> list[str]:
  302. """Repair missing application tables without deleting or altering data.
  303. Returns the names of tables created during this repair. Rows that were
  304. previously deleted cannot be recovered by recreating an empty table; a
  305. database backup is required for data recovery.
  306. """
  307. before = set(inspect(engine).get_table_names())
  308. current_suffix = date_suffix or get_table_suffix()
  309. create_dynamic_tables(engine, date_suffix=current_suffix)
  310. # Keep historical user/log pairs consistent as well. If one side of a
  311. # known pair was removed, recreate only that side and preserve the other.
  312. known_suffixes = {current_suffix}
  313. for table_name in inspect(engine).get_table_names():
  314. if table_name.startswith(("user_", "log_")):
  315. _, suffix = table_name.split("_", 1)
  316. if suffix.isdigit() and len(suffix) == 8:
  317. known_suffixes.add(suffix)
  318. for historical_suffix in sorted(known_suffixes):
  319. user_table_name, log_table_name = get_dynamic_table_names(historical_suffix)
  320. current_tables = set(inspect(engine).get_table_names())
  321. if (
  322. user_table_name not in current_tables
  323. or log_table_name not in current_tables
  324. ):
  325. create_dynamic_tables(engine, date_suffix=historical_suffix)
  326. after = set(inspect(engine).get_table_names())
  327. created_tables = sorted(after.difference(before))
  328. missing_static_tables = set(Base.metadata.tables).difference(after)
  329. if missing_static_tables:
  330. raise RuntimeError(
  331. "Database schema repair could not create tables: "
  332. + ", ".join(sorted(missing_static_tables))
  333. )
  334. return created_tables
  335. def get_dynamic_table_names(date_suffix: str = None) -> tuple[str, str]:
  336. if date_suffix is None:
  337. date_suffix = get_table_suffix()
  338. return f"user_{date_suffix}", f"log_{date_suffix}"
  339. def get_dynamic_models(date_suffix: str):
  340. cache_key = f"user_log_{date_suffix}"
  341. if cache_key in dynamic_model_cache:
  342. return dynamic_model_cache[cache_key]
  343. engine = get_engine()
  344. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  345. user_exists = table_exists(engine, user_table_name)
  346. log_exists = table_exists(engine, log_table_name)
  347. if not user_exists or not log_exists:
  348. logger.warning(
  349. f"User/log tables for date suffix '{date_suffix}' do not exist. Attempting to recreate..."
  350. )
  351. create_dynamic_tables(engine, date_suffix=date_suffix)
  352. user_exists = table_exists(engine, user_table_name)
  353. log_exists = table_exists(engine, log_table_name)
  354. if not user_exists or not log_exists:
  355. logger.error(
  356. f"User/log tables for date suffix '{date_suffix}' could not be created or found."
  357. )
  358. return None, None
  359. DynamicUser, DynamicLog = create_dynamic_models(
  360. engine, user_table_name, log_table_name
  361. )
  362. dynamic_model_cache[cache_key] = (DynamicUser, DynamicLog)
  363. return DynamicUser, DynamicLog
  364. def _verify_sqlite_access(engine):
  365. """Verify that SQLite can read and write without changing user data.
  366. The write check is performed inside a transaction and rolled back. It
  367. exercises the main database file without leaving a sentinel table or
  368. changing application data behind. Full integrity checks are intentionally
  369. handled only by the manual administration action.
  370. """
  371. check_table = f"_squidstats_startup_check_{uuid.uuid4().hex}"
  372. check_table_definition = Table(
  373. check_table,
  374. MetaData(),
  375. Column("id", Integer, nullable=False),
  376. )
  377. logger.info("Checking SQLite database read/write access...")
  378. with engine.connect() as connection:
  379. # End any transaction opened implicitly by the read before acquiring
  380. # the write lock for the actual read/write capability check.
  381. connection.rollback()
  382. transaction_started = False
  383. try:
  384. connection.exec_driver_sql("BEGIN IMMEDIATE")
  385. transaction_started = True
  386. check_table_definition.create(connection)
  387. connection.execute(check_table_definition.insert().values(id=1))
  388. connection.rollback()
  389. transaction_started = False
  390. except Exception:
  391. if transaction_started:
  392. connection.rollback()
  393. raise
  394. logger.info("✓ SQLite database read/write check passed")
  395. def _is_transient_sqlite_error(error: Exception) -> bool:
  396. """Return whether an SQLite error is worth retrying during startup."""
  397. if Config.DATABASE_TYPE != "SQLITE":
  398. return False
  399. candidates = []
  400. current = error
  401. for _ in range(5):
  402. if current is None or current in candidates:
  403. break
  404. candidates.append(current)
  405. current = getattr(current, "orig", None) or getattr(current, "__cause__", None)
  406. is_sqlite_operational_error = any(
  407. isinstance(candidate, (OperationalError, sqlite3.OperationalError))
  408. for candidate in candidates
  409. )
  410. if not is_sqlite_operational_error:
  411. return False
  412. error_text = " ".join(str(candidate).lower() for candidate in candidates)
  413. transient_markers = (
  414. "database is locked",
  415. "database table is locked",
  416. "database schema is locked",
  417. "disk i/o error",
  418. "unable to open database file",
  419. "database or disk is full",
  420. )
  421. return any(marker in error_text for marker in transient_markers)
  422. def _dispose_database_engine_after_failure():
  423. """Close pooled connections before a migration retry."""
  424. if _engine is not None:
  425. _engine.dispose()
  426. def get_concat_function(column, separator=", "):
  427. db_type = Config.DATABASE_TYPE
  428. if db_type in ("POSTGRESQL", "POSTGRES"):
  429. # PostgreSQL usa STRING_AGG
  430. return func.string_agg(column, separator)
  431. else:
  432. # MySQL, MariaDB y SQLite usan GROUP_CONCAT
  433. if separator != ", ":
  434. # Si hay separador personalizado, usarlo
  435. return func.group_concat(column, separator)
  436. else:
  437. # Separador por defecto
  438. return func.group_concat(column)
  439. def migrate_database():
  440. """Run migrations with bounded retries for transient SQLite failures."""
  441. total_attempts = len(SQLITE_MIGRATION_RETRY_DELAYS) + 1
  442. for attempt in range(1, total_attempts + 1):
  443. try:
  444. _migrate_database_once()
  445. return
  446. except Exception as error:
  447. is_last_attempt = attempt == total_attempts
  448. if is_last_attempt or not _is_transient_sqlite_error(error):
  449. raise
  450. delay = SQLITE_MIGRATION_RETRY_DELAYS[attempt - 1]
  451. logger.warning(
  452. "Transient SQLite startup error on migration attempt {}/{}: {}. "
  453. "Retrying in {} seconds...",
  454. attempt,
  455. total_attempts,
  456. error,
  457. delay,
  458. )
  459. _dispose_database_engine_after_failure()
  460. time.sleep(delay)
  461. def _migrate_database_once():
  462. """Run one migration attempt, including the SQLite preflight checks."""
  463. try:
  464. # Get Alembic configuration
  465. alembic_ini_path = os.path.join(
  466. os.path.dirname(os.path.dirname(__file__)), "alembic.ini"
  467. )
  468. if not os.path.exists(alembic_ini_path):
  469. logger.warning("alembic.ini not found. Skipping Alembic migrations.")
  470. logger.warning(
  471. "Running model-based schema repair instead; "
  472. "please restore alembic.ini for future migrations."
  473. )
  474. engine = get_engine()
  475. if Config.DATABASE_TYPE == "SQLITE":
  476. _verify_sqlite_access(engine)
  477. repaired_tables = repair_database_schema(engine)
  478. if repaired_tables:
  479. logger.warning(
  480. "Startup database repair recreated: {}",
  481. ", ".join(repaired_tables),
  482. )
  483. _ensure_admin_user(engine)
  484. return
  485. alembic_cfg = AlembicConfig(alembic_ini_path)
  486. engine = get_engine()
  487. if Config.DATABASE_TYPE == "SQLITE":
  488. _verify_sqlite_access(engine)
  489. with engine.connect() as conn:
  490. context = MigrationContext.configure(conn)
  491. current_rev = context.get_current_revision()
  492. existing_tables = set(inspect(conn).get_table_names())
  493. # If the version table is missing but there is an existing schema,
  494. # preserve that schema and repair it before recording its migration
  495. # state. Running the initial migration against a partially existing
  496. # schema would try to recreate tables that are already there.
  497. application_tables = existing_tables.difference({"alembic_version"})
  498. if current_rev is None:
  499. logger.info("Database is not currently tracked by Alembic.")
  500. if application_tables:
  501. logger.info(
  502. "Existing schema detected without migration tracking; "
  503. "repairing missing tables before marking it as current."
  504. )
  505. repair_database_schema(engine)
  506. command.stamp(alembic_cfg, "head")
  507. logger.info("✓ Existing database marked as up-to-date with migrations.")
  508. else:
  509. logger.info("No existing schema found. Running initial migrations...")
  510. command.upgrade(alembic_cfg, "head")
  511. logger.info("✓ Database schema created successfully.")
  512. else:
  513. logger.info(f"Current database version: {current_rev}")
  514. logger.info("Checking for pending migrations...")
  515. command.upgrade(alembic_cfg, "head")
  516. logger.info("✓ Database migrations completed successfully.")
  517. # Alembic does not rerun a migration when a table is removed after the
  518. # migration reached head. Always perform this idempotent repair at
  519. # startup, including after an entirely new database was migrated.
  520. repaired_tables = repair_database_schema(engine)
  521. if repaired_tables:
  522. logger.warning(
  523. "Startup database repair recreated: {}",
  524. ", ".join(repaired_tables),
  525. )
  526. _ensure_admin_user(engine)
  527. except ImportError as e:
  528. logger.error(f"Alembic not installed: {e}")
  529. logger.error("Please install: pip install alembic")
  530. raise
  531. except Exception as e:
  532. logger.error(f"Migration error: {e}")
  533. logger.error(
  534. "If you have an existing database, please run: python manage_db.py init"
  535. )
  536. raise
  537. def _ensure_admin_user(engine):
  538. """Ensure admin user exists, create if not."""
  539. try:
  540. inspector = inspect(engine)
  541. if not inspector.has_table("admin_users"):
  542. logger.warning("admin_users table not found. Cannot create admin user.")
  543. return False
  544. Session = sessionmaker(bind=engine)
  545. session = Session()
  546. try:
  547. existing_admin = (
  548. session.query(AdminUser).filter_by(username="admin").first()
  549. )
  550. if not existing_admin:
  551. logger.info("Admin user not found, creating default admin user...")
  552. return _create_default_admin_user(session)
  553. return False
  554. finally:
  555. session.close()
  556. except IntegrityError:
  557. # Another process may have created the default user between the query
  558. # and the insert. The unique username constraint makes this harmless.
  559. logger.info("Admin user was created concurrently by another process.")
  560. return False
  561. except Exception as e:
  562. logger.warning(f"Could not check/create admin user: {e}")
  563. return False
  564. def _create_default_admin_user(session):
  565. """Create the default admin user using FIRST_PASSWORD from environment."""
  566. try:
  567. import bcrypt
  568. # Get FIRST_PASSWORD from environment
  569. first_password = Config.FIRST_PASSWORD
  570. if not first_password:
  571. logger.warning(
  572. "FIRST_PASSWORD not set in .env file. Skipping admin user creation."
  573. )
  574. logger.warning(
  575. "Set FIRST_PASSWORD in your .env file to create the admin user."
  576. )
  577. return False
  578. # Hash the password
  579. salt = bcrypt.gensalt()
  580. password_hash = bcrypt.hashpw(first_password.encode("utf-8"), salt)
  581. now = datetime.now()
  582. session.add(
  583. AdminUser(
  584. username="admin",
  585. password_hash=password_hash.decode("utf-8"),
  586. salt=salt.decode("utf-8"),
  587. role="admin",
  588. is_active=1,
  589. created_at=now,
  590. updated_at=now,
  591. )
  592. )
  593. session.commit()
  594. logger.info("✓ Default admin user created successfully with FIRST_PASSWORD")
  595. return True
  596. except ImportError:
  597. logger.error("bcrypt module not available. Cannot create admin user.")
  598. session.rollback()
  599. except IntegrityError:
  600. # Another process may have created the default user after the lookup.
  601. session.rollback()
  602. logger.info("Admin user was created concurrently by another process.")
  603. except Exception as e:
  604. logger.error(f"Error creating default admin user: {e}")
  605. session.rollback()
  606. return False