database.py 26 KB

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