database.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. import logging
  2. import os
  3. import re
  4. from datetime import date, datetime
  5. from typing import Any
  6. from urllib.parse import urlparse
  7. from sqlalchemy import (
  8. BigInteger,
  9. Column,
  10. DateTime,
  11. Integer,
  12. String,
  13. Text,
  14. create_engine,
  15. func,
  16. inspect,
  17. text,
  18. )
  19. from sqlalchemy.ext.declarative import declared_attr
  20. from sqlalchemy.orm import declarative_base, sessionmaker
  21. from config import Config
  22. logging.basicConfig(
  23. level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
  24. )
  25. logger = logging.getLogger(__name__)
  26. Base = declarative_base()
  27. _engine = None
  28. _Session = None
  29. dynamic_model_cache: dict[str, Any] = {}
  30. def get_table_suffix() -> str:
  31. return date.today().strftime("%Y%m%d")
  32. class DailyBase(Base):
  33. __abstract__ = True
  34. @declared_attr
  35. def __tablename__(cls):
  36. return None
  37. class User(DailyBase):
  38. __tablename__ = "user_base"
  39. id = Column(Integer, primary_key=True)
  40. username = Column(String(255), nullable=False)
  41. ip = Column(String(255), nullable=False)
  42. created_at = Column(DateTime, default=datetime.now)
  43. class Log(DailyBase):
  44. __tablename__ = "log_base"
  45. id = Column(Integer, primary_key=True)
  46. user_id = Column(Integer, nullable=False)
  47. url = Column(Text, nullable=False)
  48. response = Column(Integer, nullable=False)
  49. request_count = Column(Integer, default=1)
  50. data_transmitted = Column(BigInteger, default=0)
  51. created_at = Column(DateTime, default=datetime.now)
  52. class LogMetadata(Base):
  53. __tablename__ = "log_metadata"
  54. id = Column(Integer, primary_key=True)
  55. last_position = Column(BigInteger, default=0)
  56. last_inode = Column(BigInteger, default=0)
  57. updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
  58. class DeniedLog(Base):
  59. __tablename__ = "denied_logs"
  60. id = Column(Integer, primary_key=True)
  61. username = Column(String(255), nullable=False)
  62. ip = Column(String(255), nullable=False)
  63. url = Column(Text, nullable=False)
  64. method = Column(String(255), nullable=False)
  65. status = Column(String(255), nullable=False)
  66. response = Column(Integer, nullable=True)
  67. data_transmitted = Column(BigInteger, default=0)
  68. created_at = Column(DateTime, default=datetime.now)
  69. class SystemMetrics(Base):
  70. __tablename__ = "system_metrics"
  71. id = Column(Integer, primary_key=True)
  72. timestamp = Column(DateTime, default=datetime.now, nullable=False)
  73. cpu_usage = Column(String(255), nullable=False) # Ejemplo: "25.5%"
  74. ram_usage_bytes = Column(BigInteger, nullable=False)
  75. swap_usage_bytes = Column(BigInteger, nullable=False)
  76. net_sent_bytes_sec = Column(BigInteger, nullable=False)
  77. net_recv_bytes_sec = Column(BigInteger, nullable=False)
  78. created_at = Column(DateTime, default=datetime.now)
  79. class Notification(Base):
  80. __tablename__ = "notifications"
  81. id = Column(Integer, primary_key=True, autoincrement=True)
  82. type = Column(String(50), nullable=False) # 'info', 'warning', 'error', 'success'
  83. message = Column(Text, nullable=False)
  84. message_hash = Column(
  85. String(64), nullable=False, index=True
  86. ) # SHA256 hash for deduplication
  87. icon = Column(String(100), nullable=True)
  88. source = Column(
  89. String(50), nullable=False, index=True
  90. ) # 'squid', 'system', 'security', 'users', 'git'
  91. read = Column(Integer, default=0) # 0 = unread, 1 = read
  92. created_at = Column(DateTime, default=datetime.now, nullable=False, index=True)
  93. updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
  94. expires_at = Column(DateTime, nullable=True) # Optional expiration date
  95. count = Column(
  96. Integer, default=1
  97. ) # Number of times this notification was triggered
  98. class AdminUser(Base):
  99. """Model for admin users with encrypted passwords."""
  100. __tablename__ = "admin_users"
  101. id = Column(Integer, primary_key=True, autoincrement=True)
  102. username = Column(String(100), nullable=False, unique=True, index=True)
  103. password_hash = Column(String(255), nullable=False) # bcrypt hash
  104. salt = Column(String(64), nullable=False) # Salt used for hashing
  105. role = Column(String(50), nullable=False, default="admin")
  106. is_active = Column(Integer, default=1) # 1 = active, 0 = inactive
  107. last_login = Column(DateTime, nullable=True)
  108. created_at = Column(DateTime, default=datetime.now, nullable=False)
  109. updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
  110. def get_database_url() -> str:
  111. db_type = Config.DATABASE_TYPE
  112. conn_str = Config.DATABASE_STRING_CONNECTION
  113. if db_type == "SQLITE":
  114. if not conn_str.startswith("sqlite:///"):
  115. return f"sqlite:///{conn_str}"
  116. return conn_str
  117. elif db_type in ("MYSQL", "MARIADB"):
  118. # Ejemplo: mysql+pymysql://user:password@host/dbname
  119. # El usuario debe poner el string completo en el .env
  120. if (
  121. conn_str.startswith("mysql://")
  122. or conn_str.startswith("mariadb://")
  123. or conn_str.startswith("mysql+pymysql://")
  124. ):
  125. return conn_str
  126. raise ValueError(
  127. "DATABASE_STRING_CONNECTION must start with 'mysql://' or 'mariadb://'."
  128. )
  129. elif db_type in ("POSTGRESQL", "POSTGRES"):
  130. # Ejemplo: postgresql://user:password@host:port/dbname
  131. # o postgresql+psycopg2://user:password@host:port/dbname
  132. if (
  133. conn_str.startswith("postgresql://")
  134. or conn_str.startswith("postgres://")
  135. or conn_str.startswith("postgresql+psycopg2://")
  136. or conn_str.startswith("postgresql+psycopg://")
  137. ):
  138. return conn_str
  139. raise ValueError(
  140. "DATABASE_STRING_CONNECTION must start with 'postgresql://', 'postgres://', 'postgresql+psycopg2://', or 'postgresql+psycopg://'."
  141. )
  142. else:
  143. raise ValueError(f"Database type not supported: {db_type}")
  144. def create_database_if_not_exists():
  145. db_type = Config.DATABASE_TYPE
  146. if db_type == "SQLITE":
  147. # SQLite crea el archivo automáticamente, no necesitamos hacer nada
  148. logger.info("SQLite database will be created automatically if it doesn't exist")
  149. return
  150. elif db_type in ("MYSQL", "MARIADB"):
  151. try:
  152. conn_str = os.getenv("DATABASE_STRING_CONNECTION", "")
  153. parsed_url = urlparse(conn_str)
  154. database_name = parsed_url.path.lstrip("/")
  155. if not database_name:
  156. logger.warning("No database name found in connection string")
  157. return
  158. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/"
  159. server_engine = create_engine(server_url, echo=False)
  160. with server_engine.connect() as conn:
  161. # Verificar si la base de datos existe
  162. result = conn.execute(
  163. text(
  164. f"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{database_name}'"
  165. )
  166. )
  167. if not result.fetchone():
  168. conn.execute(
  169. text(
  170. f"CREATE DATABASE IF NOT EXISTS `{database_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
  171. )
  172. )
  173. conn.commit()
  174. logger.info(f"Database '{database_name}' created successfully")
  175. else:
  176. logger.info(f"Database '{database_name}' already exists")
  177. server_engine.dispose()
  178. except Exception as e:
  179. logger.error(f"Error creating MySQL/MariaDB database: {e}")
  180. raise
  181. elif db_type in ("POSTGRESQL", "POSTGRES"):
  182. try:
  183. conn_str = os.getenv("DATABASE_STRING_CONNECTION", "")
  184. parsed_url = urlparse(conn_str)
  185. database_name = parsed_url.path.lstrip("/")
  186. if not database_name:
  187. logger.warning("No database name found in PostgreSQL connection string")
  188. return
  189. # Crear URL para conectarse a la base de datos 'postgres' (default)
  190. server_url = f"{parsed_url.scheme}://{parsed_url.netloc}/postgres"
  191. # Crear engine con autocommit para evitar transacciones automáticas
  192. server_engine = create_engine(
  193. server_url, echo=False, isolation_level="AUTOCOMMIT"
  194. )
  195. try:
  196. with server_engine.connect() as conn:
  197. # Verificar si la base de datos existe
  198. result = conn.execute(
  199. text(
  200. f"SELECT 1 FROM pg_database WHERE datname = '{database_name}'"
  201. )
  202. )
  203. if not result.fetchone():
  204. # La base de datos no existe, crearla
  205. # Usar una versión más simple que sea compatible con la mayoría de configuraciones
  206. try:
  207. # Primero intentar con template0 para evitar problemas de collation
  208. conn.execute(
  209. text(
  210. f"CREATE DATABASE \"{database_name}\" WITH ENCODING = 'UTF8' TEMPLATE = template0"
  211. )
  212. )
  213. logger.info(
  214. f"PostgreSQL database '{database_name}' created successfully with template0"
  215. )
  216. except Exception:
  217. # Si falla con template0, intentar sin especificar collation
  218. try:
  219. conn.execute(
  220. text(
  221. f"CREATE DATABASE \"{database_name}\" WITH ENCODING = 'UTF8'"
  222. )
  223. )
  224. logger.info(
  225. f"PostgreSQL database '{database_name}' created successfully without collation"
  226. )
  227. except Exception:
  228. # Como último recurso, crear la base de datos sin especificar encoding
  229. conn.execute(text(f'CREATE DATABASE "{database_name}"'))
  230. logger.info(
  231. f"PostgreSQL database '{database_name}' created successfully with default settings"
  232. )
  233. else:
  234. logger.info(
  235. f"PostgreSQL database '{database_name}' already exists"
  236. )
  237. finally:
  238. server_engine.dispose()
  239. except Exception as e:
  240. logger.error(f"Error creating PostgreSQL database: {e}")
  241. raise
  242. def get_engine():
  243. global _engine
  244. if _engine is not None:
  245. return _engine
  246. create_database_if_not_exists()
  247. db_url = get_database_url()
  248. _engine = create_engine(db_url, echo=False, future=True)
  249. return _engine
  250. def get_session():
  251. global _Session
  252. engine = get_engine()
  253. if _Session is None:
  254. create_dynamic_tables(engine)
  255. _Session = sessionmaker(bind=engine)
  256. return _Session()
  257. def table_exists(engine, table_name: str) -> bool:
  258. inspector = inspect(engine)
  259. return inspector.has_table(table_name)
  260. def create_dynamic_tables(engine, date_suffix: str = None):
  261. LogMetadata.__table__.create(engine, checkfirst=True)
  262. DeniedLog.__table__.create(engine, checkfirst=True)
  263. SystemMetrics.__table__.create(engine, checkfirst=True)
  264. Notification.__table__.create(engine, checkfirst=True) # Add notifications table
  265. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  266. creation_logger = logging.getLogger(f"CreateTable_{date_suffix or 'today'}")
  267. creation_logger.propagate = False # Evita que el log suba al logger raíz
  268. if not creation_logger.handlers:
  269. handler = logging.StreamHandler()
  270. formatter = logging.Formatter(
  271. "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
  272. )
  273. handler.setFormatter(formatter)
  274. creation_logger.addHandler(handler)
  275. if not table_exists(engine, user_table_name) or not table_exists(
  276. engine, log_table_name
  277. ):
  278. creation_logger.info(
  279. f"Creating dynamic tables for date suffix '{date_suffix}': {user_table_name}, {log_table_name}"
  280. )
  281. DynamicBase = declarative_base()
  282. class DynamicUser(DynamicBase):
  283. __tablename__ = user_table_name
  284. id = Column(Integer, primary_key=True)
  285. username = Column(String(255), nullable=False)
  286. ip = Column(String(255), nullable=False)
  287. created_at = Column(DateTime, default=datetime.now)
  288. class DynamicLog(DynamicBase):
  289. __tablename__ = log_table_name
  290. id = Column(Integer, primary_key=True)
  291. user_id = Column(Integer, nullable=False)
  292. url = Column(Text, nullable=False)
  293. response = Column(Integer, nullable=False)
  294. request_count = Column(Integer, default=1)
  295. data_transmitted = Column(BigInteger, default=0)
  296. created_at = Column(DateTime, default=datetime.now)
  297. DynamicBase.metadata.create_all(engine, checkfirst=True)
  298. def get_dynamic_table_names(date_suffix: str = None) -> tuple[str, str]:
  299. if date_suffix is None:
  300. date_suffix = get_table_suffix()
  301. return f"user_{date_suffix}", f"log_{date_suffix}"
  302. def get_dynamic_models(date_suffix: str):
  303. cache_key = f"user_log_{date_suffix}"
  304. if cache_key in dynamic_model_cache:
  305. return dynamic_model_cache[cache_key]
  306. engine = get_engine()
  307. user_table_name, log_table_name = get_dynamic_table_names(date_suffix)
  308. user_exists = table_exists(engine, user_table_name)
  309. log_exists = table_exists(engine, log_table_name)
  310. if not user_exists or not log_exists:
  311. logger.warning(
  312. f"User/log tables for date suffix '{date_suffix}' do not exist. Attempting to recreate..."
  313. )
  314. create_dynamic_tables(engine, date_suffix=date_suffix)
  315. user_exists = table_exists(engine, user_table_name)
  316. log_exists = table_exists(engine, log_table_name)
  317. if not user_exists or not log_exists:
  318. logger.error(
  319. f"User/log tables for date suffix '{date_suffix}' could not be created or found."
  320. )
  321. return None, None
  322. DynamicBase = declarative_base()
  323. class DynamicUser(DynamicBase):
  324. __tablename__ = user_table_name
  325. id = Column(Integer, primary_key=True, autoincrement=True)
  326. username = Column(String(255), nullable=False)
  327. ip = Column(String(255), nullable=False)
  328. created_at = Column(DateTime, default=datetime.now)
  329. class DynamicLog(DynamicBase):
  330. __tablename__ = log_table_name
  331. id = Column(Integer, primary_key=True, autoincrement=True)
  332. user_id = Column(Integer, nullable=False)
  333. url = Column(Text, nullable=False)
  334. response = Column(Integer, nullable=False)
  335. request_count = Column(Integer, default=1)
  336. data_transmitted = Column(BigInteger, default=0)
  337. created_at = Column(DateTime, default=datetime.now)
  338. dynamic_model_cache[cache_key] = (DynamicUser, DynamicLog)
  339. return DynamicUser, DynamicLog
  340. def get_concat_function(column, separator=", "):
  341. db_type = Config.DATABASE_TYPE
  342. if db_type in ("POSTGRESQL", "POSTGRES"):
  343. # PostgreSQL usa STRING_AGG
  344. return func.string_agg(column, separator)
  345. else:
  346. # MySQL, MariaDB y SQLite usan GROUP_CONCAT
  347. if separator != ", ":
  348. # Si hay separador personalizado, usarlo
  349. return func.group_concat(column, separator)
  350. else:
  351. # Separador por defecto
  352. return func.group_concat(column)
  353. def migrate_database():
  354. engine = get_engine()
  355. db_type = Config.DATABASE_TYPE
  356. inspector = inspect(engine)
  357. original_level = logger.level
  358. logger.setLevel(logging.DEBUG)
  359. try:
  360. with engine.connect() as conn:
  361. # Ensure admin_users table exists for authentication
  362. if not inspector.has_table("admin_users"):
  363. logger.info("Creating admin_users table (missing)")
  364. AdminUser.__table__.create(bind=engine, checkfirst=True)
  365. conn.commit()
  366. # Refresh inspector after table creation
  367. inspector = inspect(engine)
  368. # Create default admin user if table was just created
  369. _create_default_admin_user(conn, engine)
  370. # Check if admin user exists, create if not
  371. try:
  372. session = get_session()
  373. existing_admin = (
  374. session.query(AdminUser).filter_by(username="admin").first()
  375. )
  376. if not existing_admin:
  377. logger.info("Admin user not found, creating default admin user")
  378. _create_default_admin_user(conn, engine)
  379. else:
  380. logger.info("Admin user already exists")
  381. session.close()
  382. except Exception as e:
  383. logger.warning(f"Could not check/create admin user: {e}")
  384. # Define expected schema for all tables
  385. expected_schemas = {
  386. "user_base": {
  387. "username": {"type": "VARCHAR(255)", "nullable": False},
  388. "ip": {"type": "VARCHAR(255)", "nullable": False},
  389. },
  390. "log_base": {"url": {"type": "TEXT", "nullable": False}},
  391. "denied_logs": {
  392. "username": {"type": "VARCHAR(255)", "nullable": False},
  393. "ip": {"type": "VARCHAR(255)", "nullable": False},
  394. "url": {"type": "TEXT", "nullable": False},
  395. "method": {"type": "VARCHAR(255)", "nullable": False},
  396. "status": {"type": "VARCHAR(255)", "nullable": False},
  397. },
  398. "system_metrics": {
  399. "cpu_usage": {"type": "VARCHAR(255)", "nullable": False}
  400. },
  401. }
  402. for table_name, expected_columns in expected_schemas.items():
  403. if not inspector.has_table(table_name):
  404. logger.info(f"Table {table_name} doesn't exist, skipping migration")
  405. continue
  406. logger.info(f"Checking schema for table: {table_name}")
  407. current_columns = inspector.get_columns(table_name)
  408. for column_name, expected_spec in expected_columns.items():
  409. # Find current column info
  410. current_column = next(
  411. (col for col in current_columns if col["name"] == column_name),
  412. None,
  413. )
  414. if not current_column:
  415. logger.warning(
  416. f"Column {column_name} not found in {table_name}"
  417. )
  418. continue
  419. logger.info(
  420. f"Checking {table_name}.{column_name}: current type = {current_column['type']}"
  421. )
  422. # Check if migration is needed
  423. needs_migration = _column_needs_migration(
  424. current_column, expected_spec, db_type
  425. )
  426. if needs_migration:
  427. logger.info(
  428. f"Migrating {table_name}.{column_name} to {expected_spec['type']}"
  429. )
  430. _migrate_column(
  431. conn, table_name, column_name, expected_spec, db_type
  432. )
  433. else:
  434. logger.info(
  435. f"No migration needed for {table_name}.{column_name}"
  436. )
  437. # Also check dynamic tables (user_YYYYMMDD, log_YYYYMMDD)
  438. _migrate_dynamic_tables(conn, inspector, db_type)
  439. conn.commit()
  440. logger.info("Database migration completed successfully")
  441. except Exception as e:
  442. logger.warning(
  443. f"Migration warning (this might be expected if already migrated): {e}"
  444. )
  445. finally:
  446. logger.setLevel(original_level)
  447. def _column_needs_migration(current_column, expected_spec, db_type):
  448. current_type = str(current_column["type"]).upper()
  449. expected_type = expected_spec["type"].upper()
  450. logger.debug(
  451. f"Checking migration: current='{current_type}' vs expected='{expected_type}'"
  452. )
  453. # Normalize type representations across different databases
  454. if db_type in ("MYSQL", "MARIADB"):
  455. # MySQL type mapping
  456. if "VARCHAR(255)" in expected_type and (
  457. "VARCHAR" in current_type or "CHAR" in current_type
  458. ):
  459. # Extract current length
  460. import re
  461. match = re.search(r"VARCHAR\((\d+)\)", current_type)
  462. if match:
  463. current_length = int(match.group(1))
  464. logger.debug(
  465. f"MySQL VARCHAR: current length={current_length}, expected=255"
  466. )
  467. return current_length != 255 # Changed from < to != for exact match
  468. else:
  469. # If no length found, assume it needs migration
  470. return True
  471. elif "TEXT" in expected_type and "TEXT" not in current_type:
  472. return True
  473. elif db_type in ("POSTGRESQL", "POSTGRES"):
  474. # PostgreSQL type mapping
  475. if "VARCHAR(255)" in expected_type:
  476. if "CHARACTER VARYING" in current_type or "VARCHAR" in current_type:
  477. import re
  478. match = re.search(
  479. r"(?:CHARACTER VARYING|VARCHAR)\((\d+)\)", current_type
  480. )
  481. if match:
  482. current_length = int(match.group(1))
  483. logger.debug(
  484. f"PostgreSQL VARCHAR: current length={current_length}, expected=255"
  485. )
  486. return current_length != 255 # Changed from < to != for exact match
  487. # If no length specified, it might need migration
  488. return "(" not in current_type
  489. else:
  490. # Different type entirely, needs migration
  491. return True
  492. elif "TEXT" in expected_type and "TEXT" not in current_type:
  493. return True
  494. elif db_type == "SQLITE":
  495. # SQLite is more flexible with types, but let's still check for obvious differences
  496. if "VARCHAR(255)" in expected_type and (
  497. "VARCHAR" in current_type or "CHAR" in current_type
  498. ):
  499. import re
  500. match = re.search(r"VARCHAR\((\d+)\)", current_type)
  501. if match:
  502. current_length = int(match.group(1))
  503. logger.debug(
  504. f"SQLite VARCHAR: current length={current_length}, expected=255"
  505. )
  506. return current_length != 255
  507. # For SQLite, generally don't migrate unless there's a significant type difference
  508. return False
  509. return False
  510. def _migrate_column(conn, table_name, column_name, expected_spec, db_type):
  511. try:
  512. if db_type in ("MYSQL", "MARIADB"):
  513. nullable_clause = "" if expected_spec["nullable"] else "NOT NULL"
  514. sql = f"ALTER TABLE {table_name} MODIFY COLUMN {column_name} {expected_spec['type']} {nullable_clause}"
  515. conn.execute(text(sql))
  516. logger.info(
  517. f"Migrated {table_name}.{column_name} to {expected_spec['type']}"
  518. )
  519. elif db_type in ("POSTGRESQL", "POSTGRES"):
  520. sql = f"ALTER TABLE {table_name} ALTER COLUMN {column_name} TYPE {expected_spec['type']}"
  521. conn.execute(text(sql))
  522. logger.info(
  523. f"Migrated {table_name}.{column_name} to {expected_spec['type']}"
  524. )
  525. elif db_type == "SQLITE":
  526. logger.info(
  527. f"SQLite migration skipped for {table_name}.{column_name} (flexible typing)"
  528. )
  529. except Exception as e:
  530. logger.error(f"Failed to migrate {table_name}.{column_name}: {e}")
  531. def _migrate_dynamic_tables(conn, inspector, db_type):
  532. # Get all table names that match the dynamic pattern
  533. all_tables = inspector.get_table_names()
  534. user_tables = [t for t in all_tables if re.match(r"user_\d{8}$", t)]
  535. logger.info(f"Found {len(user_tables)} dynamic user tables: {user_tables}")
  536. # Define expected schema for dynamic tables
  537. user_schema = {
  538. "username": {"type": "VARCHAR(255)", "nullable": False},
  539. "ip": {
  540. "type": "VARCHAR(255)",
  541. "nullable": False,
  542. },
  543. }
  544. # Migrate user tables
  545. for table_name in user_tables:
  546. logger.info(f"Checking dynamic table: {table_name}")
  547. current_columns = inspector.get_columns(table_name)
  548. for column_name, expected_spec in user_schema.items():
  549. current_column = next(
  550. (col for col in current_columns if col["name"] == column_name), None
  551. )
  552. if current_column:
  553. logger.info(
  554. f"Checking {table_name}.{column_name}: current type = {current_column['type']}"
  555. )
  556. if _column_needs_migration(current_column, expected_spec, db_type):
  557. logger.info(
  558. f"Migrating dynamic table {table_name}.{column_name} to {expected_spec['type']}"
  559. )
  560. _migrate_column(
  561. conn, table_name, column_name, expected_spec, db_type
  562. )
  563. else:
  564. logger.info(f"No migration needed for {table_name}.{column_name}")
  565. def _create_default_admin_user(conn, engine):
  566. """Create the default admin user using FIRST_PASSWORD from environment."""
  567. try:
  568. import bcrypt
  569. # Get FIRST_PASSWORD from environment
  570. first_password = Config.FIRST_PASSWORD
  571. if not first_password:
  572. logger.warning(
  573. "FIRST_PASSWORD not set in .env file. Skipping admin user creation."
  574. )
  575. logger.warning(
  576. "Set FIRST_PASSWORD in your .env file to create the admin user."
  577. )
  578. return
  579. # Hash the password
  580. salt = bcrypt.gensalt()
  581. password_hash = bcrypt.hashpw(first_password.encode("utf-8"), salt)
  582. # Insert admin user
  583. from sqlalchemy import text
  584. insert_query = text("""
  585. INSERT INTO admin_users (username, password_hash, salt, role, is_active, created_at, updated_at)
  586. VALUES (:username, :password_hash, :salt, :role, :is_active, :created_at, :updated_at)
  587. """)
  588. from datetime import datetime
  589. now = datetime.now()
  590. conn.execute(
  591. insert_query,
  592. {
  593. "username": "admin",
  594. "password_hash": password_hash.decode("utf-8"),
  595. "salt": salt.decode("utf-8"),
  596. "role": "admin",
  597. "is_active": 1,
  598. "created_at": now,
  599. "updated_at": now,
  600. },
  601. )
  602. conn.commit()
  603. logger.info("✓ Default admin user created successfully with FIRST_PASSWORD")
  604. except ImportError:
  605. logger.error("bcrypt module not available. Cannot create admin user.")
  606. except Exception as e:
  607. logger.error(f"Error creating default admin user: {e}")
  608. conn.rollback()