notifications.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. import hashlib
  2. import os
  3. import shutil
  4. import subprocess # nosec B404
  5. import threading
  6. from contextlib import contextmanager
  7. from datetime import datetime, timedelta
  8. from typing import Any
  9. from flask_babel import gettext as _
  10. from flask_babel import ngettext
  11. from loguru import logger
  12. from sqlalchemy import and_, desc, func
  13. from sqlalchemy.orm import Session
  14. from database.database import Notification, get_session
  15. # Import Telegram integration (optional - fails gracefully if not configured)
  16. try:
  17. from services.notifications.telegram_integration import send_telegram_notification
  18. TELEGRAM_AVAILABLE = True
  19. except Exception as e:
  20. logger.debug(f"Telegram integration not available: {e}")
  21. TELEGRAM_AVAILABLE = False
  22. send_telegram_notification = None
  23. # Configuration constants
  24. CLEANUP_KEEP_COUNT = 100
  25. DEFAULT_DEDUPLICATE_HOURS = 1
  26. # Notification thresholds
  27. FAILED_AUTH_THRESHOLD = 15
  28. DENIED_REQUESTS_THRESHOLD = 20
  29. SUSPICIOUS_IP_THRESHOLD = 6000
  30. CRITICAL_IP_THRESHOLD = 20000
  31. MAX_IPS_TO_REPORT = 5
  32. # User activity thresholds
  33. HIGH_ACTIVITY_THRESHOLD = 100
  34. HIGH_USAGE_GB_THRESHOLD = 20.0
  35. MAX_USERS_TO_REPORT = 3
  36. # System health thresholds
  37. SQUID_LOG_SIZE_WARNING_MB = 500
  38. SQUID_LOG_STALE_HOURS = 24
  39. DISK_CRITICAL_GB = 1
  40. DISK_WARNING_GB = 5
  41. # Monitor intervals (in minutes)
  42. CHECK_COMMITS_INTERVAL = 30
  43. CHECK_SYSTEM_INTERVAL = 5
  44. CHECK_SQUID_LOG_INTERVAL = 10
  45. CHECK_SECURITY_INTERVAL = 3
  46. CHECK_USER_ACTIVITY_INTERVAL = 15
  47. # Global variable for Socket.IO
  48. socketio = None
  49. # Global stop event for notification monitor
  50. _monitor_stop_event = None
  51. _monitor_thread = None
  52. def set_socketio_instance(sio):
  53. global socketio
  54. socketio = sio
  55. @contextmanager
  56. def get_db_session():
  57. """Context manager for database sessions"""
  58. db = get_session()
  59. try:
  60. yield db
  61. db.commit()
  62. except Exception:
  63. db.rollback()
  64. raise
  65. finally:
  66. db.close()
  67. def stop_notification_monitor():
  68. """Stop the notification monitor thread"""
  69. global _monitor_stop_event, _monitor_thread
  70. if _monitor_stop_event:
  71. _monitor_stop_event.set()
  72. if _monitor_thread and _monitor_thread.is_alive():
  73. _monitor_thread.join(timeout=5)
  74. logger.info("Notification monitor stopped")
  75. def _generate_message_hash(message: str, source: str, notification_type: str) -> str:
  76. """Generate SHA256 hash for deduplication"""
  77. content = f"{source}:{notification_type}:{message}"
  78. return hashlib.sha256(content.encode()).hexdigest()
  79. def _check_duplicate_notification(
  80. db: Session, message_hash: str, hours: int = 24
  81. ) -> Notification | None:
  82. """Check if a similar notification exists in the last N hours"""
  83. time_threshold = datetime.now() - timedelta(hours=hours)
  84. return (
  85. db.query(Notification)
  86. .filter(
  87. and_(
  88. Notification.message_hash == message_hash,
  89. Notification.created_at >= time_threshold,
  90. )
  91. )
  92. .first()
  93. )
  94. def set_commit_notifications(has_updates, messages):
  95. """Keep for compatibility"""
  96. # Convert commits to system notifications
  97. if has_updates and messages:
  98. for msg in messages:
  99. add_notification(
  100. "info",
  101. _("Commit: %(message)s", message=msg),
  102. "fa-code-branch",
  103. "git",
  104. )
  105. def get_commit_notifications() -> dict[str, Any]:
  106. """Keep for compatibility with existing code"""
  107. with get_db_session() as db:
  108. git_notifications = (
  109. db.query(Notification).filter(Notification.source == "git").all()
  110. )
  111. commit_prefix = _("Commit: ")
  112. return {
  113. "has_updates": len(git_notifications) > 0,
  114. "commits": [
  115. n.message.replace(commit_prefix, "", 1)
  116. if n.message.startswith(commit_prefix)
  117. else n.message
  118. for n in git_notifications
  119. ],
  120. }
  121. def add_notification(
  122. notification_type: str,
  123. message: str,
  124. icon: str | None = None,
  125. source: str = "system",
  126. deduplicate_hours: int = DEFAULT_DEDUPLICATE_HOURS,
  127. send_telegram: bool = True,
  128. ) -> dict[str, Any] | None:
  129. """Adds a notification to the database and emits via Socket.IO if configured
  130. Args:
  131. notification_type: Type of notification ('info', 'warning', 'error', 'success')
  132. message: Notification message
  133. icon: FontAwesome icon class (optional)
  134. source: Source of the notification ('squid', 'system', 'security', 'users', 'git')
  135. deduplicate_hours: Hours to check for duplicate notifications
  136. send_telegram: Send notification to Telegram (default: True)
  137. Returns:
  138. Dictionary with notification data or None if it was a duplicate
  139. """
  140. with get_db_session() as db:
  141. message_hash = _generate_message_hash(message, source, notification_type)
  142. # Check for duplicates
  143. existing = _check_duplicate_notification(
  144. db, message_hash, hours=deduplicate_hours
  145. )
  146. if existing:
  147. # Update existing notification count and timestamp
  148. existing.count += 1
  149. existing.updated_at = datetime.now()
  150. existing.read = 0 # Mark as unread again
  151. # Create dict before closing session
  152. notification_dict = _notification_to_dict(existing)
  153. # Emit update via Socket.IO
  154. if socketio:
  155. unread_count = _get_unread_count(db)
  156. socketio.emit(
  157. "notification_updated",
  158. {
  159. "notification": notification_dict,
  160. "unread_count": unread_count,
  161. },
  162. )
  163. return notification_dict
  164. # Create new notification
  165. notification = Notification(
  166. type=notification_type,
  167. message=message,
  168. message_hash=message_hash,
  169. icon=icon or get_default_icon(notification_type),
  170. source=source,
  171. read=0,
  172. count=1,
  173. created_at=datetime.now(),
  174. )
  175. db.add(notification)
  176. db.flush() # Flush to get ID without committing
  177. db.refresh(notification)
  178. # Create dict before cleanup
  179. notification_dict = _notification_to_dict(notification)
  180. # Clean old notifications (keep last N)
  181. _cleanup_old_notifications(db, keep_count=CLEANUP_KEEP_COUNT)
  182. # Emit via Socket.IO if configured
  183. if socketio:
  184. unread_count = _get_unread_count(db)
  185. socketio.emit(
  186. "new_notification",
  187. {
  188. "notification": notification_dict,
  189. "unread_count": unread_count,
  190. },
  191. )
  192. # Send to Telegram if enabled and requested
  193. if send_telegram and TELEGRAM_AVAILABLE and send_telegram_notification:
  194. try:
  195. send_telegram_notification(
  196. notification_type=notification_type, message=message, source=source
  197. )
  198. except Exception as e:
  199. logger.error(f"Failed to send Telegram notification: {e}")
  200. return notification_dict
  201. def _notification_to_dict(notification: Notification) -> dict:
  202. """Convert Notification object to dictionary"""
  203. return {
  204. "id": notification.id,
  205. "type": notification.type,
  206. "message": notification.message,
  207. "icon": notification.icon,
  208. "timestamp": notification.created_at.isoformat(),
  209. "time": _format_time_ago(notification.created_at),
  210. "read": bool(notification.read),
  211. "source": notification.source,
  212. "count": notification.count,
  213. }
  214. def _format_time_ago(timestamp: datetime) -> str:
  215. """Format timestamp as 'hace X tiempo'"""
  216. now = datetime.now()
  217. diff = now - timestamp
  218. minutes = int(diff.total_seconds() / 60)
  219. hours = int(diff.total_seconds() / 3600)
  220. days = int(diff.total_seconds() / 86400)
  221. if minutes < 1:
  222. return _("Hace unos momentos")
  223. elif minutes < 60:
  224. return ngettext(
  225. "Hace {count} minuto",
  226. "Hace {count} minutos",
  227. minutes,
  228. ).format(count=minutes)
  229. elif hours < 24:
  230. return ngettext(
  231. "Hace {count} hora",
  232. "Hace {count} horas",
  233. hours,
  234. ).format(count=hours)
  235. else:
  236. return ngettext(
  237. "Hace {count} día",
  238. "Hace {count} días",
  239. days,
  240. ).format(count=days)
  241. def _get_unread_count(db: Session) -> int:
  242. """Get count of unread notifications"""
  243. return db.query(func.count(Notification.id)).filter(Notification.read == 0).scalar()
  244. def _cleanup_old_notifications(db: Session, keep_count: int = CLEANUP_KEEP_COUNT):
  245. """Remove old notifications, keeping only the most recent ones"""
  246. total_count = db.query(func.count(Notification.id)).scalar()
  247. if total_count > keep_count:
  248. # Get IDs of notifications to keep
  249. keep_ids_query = (
  250. db.query(Notification.id)
  251. .order_by(desc(Notification.created_at))
  252. .limit(keep_count)
  253. .subquery()
  254. )
  255. # Delete old notifications in one query
  256. deleted = (
  257. db.query(Notification)
  258. .filter(Notification.id.notin_(keep_ids_query))
  259. .delete(synchronize_session=False)
  260. )
  261. if deleted > 0:
  262. logger.info(f"Cleaned up {deleted} old notifications")
  263. def get_default_icon(notification_type):
  264. icons = {
  265. "info": "fa-info-circle",
  266. "warning": "fa-exclamation-triangle",
  267. "error": "fa-times-circle",
  268. "success": "fa-check-circle",
  269. }
  270. return icons.get(notification_type, "fa-bell")
  271. def get_all_notifications(
  272. limit: int = 10, page: int = 1, per_page: int = 20
  273. ) -> dict[str, Any]:
  274. """Gets all system notifications with pagination support from database"""
  275. with get_db_session() as db:
  276. # Get total count
  277. total_notifications = db.query(func.count(Notification.id)).scalar() or 0
  278. # Get unread count
  279. unread_count = (
  280. db.query(func.count(Notification.id))
  281. .filter(Notification.read == 0)
  282. .scalar()
  283. or 0
  284. )
  285. # Calculate pagination
  286. start_index = (page - 1) * per_page
  287. # Get paginated notifications
  288. notifications = (
  289. db.query(Notification)
  290. .order_by(desc(Notification.created_at))
  291. .offset(start_index)
  292. .limit(per_page)
  293. .all()
  294. )
  295. # Convert to dict
  296. notifications_list = [_notification_to_dict(n) for n in notifications]
  297. # Calculate pagination metadata
  298. total_pages = (
  299. (total_notifications + per_page - 1) // per_page
  300. if total_notifications > 0
  301. else 1
  302. )
  303. return {
  304. "unread_count": int(unread_count),
  305. "notifications": notifications_list,
  306. "pagination": {
  307. "current_page": page,
  308. "per_page": per_page,
  309. "total_pages": total_pages,
  310. "total_notifications": int(total_notifications),
  311. "has_prev": page > 1,
  312. "has_next": page < total_pages,
  313. },
  314. }
  315. def mark_notifications_read(notification_ids: list[int]) -> int:
  316. with get_db_session() as db:
  317. updated = (
  318. db.query(Notification)
  319. .filter(Notification.id.in_(notification_ids))
  320. .update(
  321. {"read": 1, "updated_at": datetime.now()}, synchronize_session=False
  322. )
  323. )
  324. logger.info(f"Marked {updated} notifications as read")
  325. return updated
  326. def delete_notification(notification_id: int) -> bool:
  327. with get_db_session() as db:
  328. deleted = (
  329. db.query(Notification)
  330. .filter(Notification.id == notification_id)
  331. .delete(synchronize_session=False)
  332. )
  333. if deleted:
  334. logger.info(f"Deleted notification {notification_id}")
  335. return deleted > 0
  336. def delete_all_notifications() -> int:
  337. with get_db_session() as db:
  338. deleted = db.query(Notification).delete(synchronize_session=False)
  339. logger.info(f"Deleted all {deleted} notifications")
  340. return deleted
  341. def check_squid_log_health():
  342. """Checks Squid logs health"""
  343. try:
  344. log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
  345. if not os.path.exists(log_file):
  346. add_notification(
  347. "error",
  348. _(
  349. "Archivo de log de Squid no encontrado: %(log_file)s",
  350. log_file=log_file,
  351. ),
  352. "fa-file-exclamation",
  353. "squid",
  354. )
  355. return
  356. stat_info = os.stat(log_file)
  357. file_size_mb = stat_info.st_size / (1024 * 1024)
  358. # Check file size
  359. if file_size_mb > SQUID_LOG_SIZE_WARNING_MB:
  360. add_notification(
  361. "warning",
  362. _("Log de Squid muy grande: %(size).1fMB", size=file_size_mb),
  363. "fa-file-alt",
  364. "squid",
  365. )
  366. # Check last modification
  367. last_modified = datetime.fromtimestamp(stat_info.st_mtime)
  368. hours_since_update = (datetime.now() - last_modified).total_seconds() / 3600
  369. if hours_since_update > SQUID_LOG_STALE_HOURS:
  370. add_notification(
  371. "warning",
  372. _(
  373. "Log de Squid no actualizado por más de %(hours)d h",
  374. hours=int(hours_since_update),
  375. ),
  376. "fa-clock",
  377. "squid",
  378. )
  379. except OSError as e:
  380. logger.error(f"Error accessing Squid log file: {e}")
  381. except Exception as e:
  382. logger.error(f"Error checking Squid log health: {e}")
  383. def check_system_health():
  384. """Checks general system health"""
  385. try:
  386. # Check disk usage
  387. disk_usage = os.statvfs("/")
  388. free_disk_gb = (disk_usage.f_bavail * disk_usage.f_frsize) / (1024**3)
  389. if free_disk_gb < DISK_CRITICAL_GB:
  390. add_notification(
  391. "error",
  392. _(
  393. "Espacio en disco crítico: %(free).1fGB libres",
  394. free=free_disk_gb,
  395. ),
  396. "fa-hdd",
  397. "system",
  398. )
  399. elif free_disk_gb < DISK_WARNING_GB:
  400. add_notification(
  401. "warning",
  402. _(
  403. "Espacio en disco bajo: %(free).1fGB libres",
  404. free=free_disk_gb,
  405. ),
  406. "fa-hdd",
  407. "system",
  408. )
  409. except OSError as e:
  410. logger.error(f"Error checking disk usage: {e}")
  411. except Exception as e:
  412. logger.error(f"Error checking system health: {e}")
  413. # Function for commits
  414. def has_remote_commits_with_messages(
  415. repo_path: str, branch: str = "main"
  416. ) -> tuple[bool, list[str]]:
  417. git_dir = os.path.join(repo_path, ".git")
  418. if not os.path.isdir(git_dir):
  419. logger.warning(f"Not a valid Git repository: {repo_path}")
  420. return False, []
  421. try:
  422. # Configurar proxy si existe la variable de entorno
  423. env = os.environ.copy()
  424. http_proxy = env.get("HTTP_PROXY", "")
  425. if http_proxy:
  426. env["http_proxy"] = http_proxy
  427. env["https_proxy"] = http_proxy
  428. git_bin = shutil.which("git")
  429. if git_bin is None:
  430. logger.warning("'git' executable not found in PATH")
  431. return False, []
  432. subprocess.run( # nosec B603 # noqa: S603
  433. [git_bin, "fetch"],
  434. cwd=repo_path,
  435. check=True,
  436. stdout=subprocess.DEVNULL,
  437. stderr=subprocess.DEVNULL,
  438. env=env,
  439. )
  440. result = subprocess.run( # nosec B603 # noqa: S603
  441. [
  442. git_bin,
  443. "rev-list",
  444. "--left-right",
  445. "--count",
  446. f"origin/{branch}...{branch}",
  447. ],
  448. cwd=repo_path,
  449. capture_output=True,
  450. text=True,
  451. check=True,
  452. env=env,
  453. )
  454. ahead_behind = result.stdout.strip().split()
  455. remote_ahead = int(ahead_behind[0])
  456. if remote_ahead > 0:
  457. log_result = subprocess.run( # nosec B603 # noqa: S603
  458. [git_bin, "log", f"{branch}..origin/{branch}", "--pretty=format:%s"],
  459. cwd=repo_path,
  460. capture_output=True,
  461. text=True,
  462. check=True,
  463. env=env,
  464. )
  465. commit_messages = (
  466. log_result.stdout.strip().split("\n")
  467. if log_result.stdout.strip()
  468. else []
  469. )
  470. return True, commit_messages
  471. return False, []
  472. except subprocess.CalledProcessError as e:
  473. logger.error(f"Error executing git commands: {e.stderr}")
  474. return False, []
  475. except Exception as e:
  476. logger.error(f"Unexpected error checking git commits: {e}")
  477. return False, []
  478. # Thread for periodic checks
  479. def start_notification_monitor():
  480. """Starts the notification monitor in background with graceful shutdown support"""
  481. global _monitor_stop_event, _monitor_thread
  482. _monitor_stop_event = threading.Event()
  483. def monitor_loop():
  484. check_count = 0
  485. cycle_interval = 60 # 1 minute between cycles for better granularity
  486. logger.info("Notification monitor started")
  487. while not _monitor_stop_event.is_set():
  488. try:
  489. # Check commits every N minutes
  490. if check_count % CHECK_COMMITS_INTERVAL == 0:
  491. current_file_dir = os.path.dirname(os.path.abspath(__file__))
  492. repo_path = os.path.dirname(current_file_dir)
  493. if os.path.exists(os.path.join(repo_path, ".git")):
  494. has_updates, messages = has_remote_commits_with_messages(
  495. repo_path
  496. )
  497. set_commit_notifications(has_updates, messages)
  498. # System health checks at different intervals
  499. if check_count % CHECK_SYSTEM_INTERVAL == 0:
  500. check_system_health()
  501. if check_count % CHECK_SQUID_LOG_INTERVAL == 0:
  502. check_squid_log_health()
  503. if check_count % CHECK_SECURITY_INTERVAL == 0:
  504. check_security_events()
  505. if check_count % CHECK_USER_ACTIVITY_INTERVAL == 0:
  506. check_user_activity()
  507. check_count = (check_count + 1) % 1000 # Reset to prevent overflow
  508. except Exception as e:
  509. logger.error(f"Error in notification monitor: {e}", exc_info=True)
  510. _monitor_stop_event.wait(timeout=cycle_interval)
  511. _monitor_thread = threading.Thread(
  512. target=monitor_loop, daemon=True, name="NotificationMonitor"
  513. )
  514. _monitor_thread.start()
  515. return _monitor_stop_event # Return the event for potential external control
  516. # Specific functions for Squid that can be called from other parts
  517. def notify_squid_restart_success():
  518. """Notify successful Squid restart"""
  519. add_notification(
  520. "success",
  521. _("Squid reiniciado exitosamente"),
  522. "fa-sync-alt",
  523. "squid",
  524. )
  525. def notify_squid_restart_failed(error_message: str = ""):
  526. """Notify failed Squid restart"""
  527. message = _("Error al reiniciar Squid")
  528. if error_message:
  529. message = _(
  530. "Error al reiniciar Squid: %(error)s",
  531. error=error_message,
  532. )
  533. add_notification("error", message, "fa-exclamation-triangle", "squid")
  534. def notify_squid_config_error(error_message: str):
  535. """Notify Squid configuration error"""
  536. add_notification(
  537. "error",
  538. _(
  539. "Error de configuración de Squid: %(error)s",
  540. error=error_message,
  541. ),
  542. "fa-cog",
  543. "squid",
  544. )
  545. def notify_squid_high_usage(warning_message: str):
  546. """Notify high Squid resource usage"""
  547. add_notification("warning", warning_message, "fa-chart-line", "squid")
  548. def check_security_events():
  549. """Checks security events from the database"""
  550. try:
  551. from services.analytics.auditoria_service import (
  552. # find_suspicious_activity,
  553. get_denied_requests,
  554. get_failed_auth_attempts,
  555. )
  556. with get_db_session() as db:
  557. # 1. Failed authentication attempts
  558. failed_auth_count = get_failed_auth_attempts(db, hours=1)
  559. if failed_auth_count > FAILED_AUTH_THRESHOLD:
  560. add_notification(
  561. "warning",
  562. _(
  563. "%(count)d intentos de autenticación fallidos en la última hora",
  564. count=failed_auth_count,
  565. ),
  566. "fa-shield-alt",
  567. "security",
  568. )
  569. # 2. Denied requests
  570. denied_count = get_denied_requests(db, hours=1)
  571. if denied_count > DENIED_REQUESTS_THRESHOLD:
  572. add_notification(
  573. "warning",
  574. _(
  575. "%(count)d solicitudes denegadas en la última hora",
  576. count=denied_count,
  577. ),
  578. "fa-ban",
  579. "security",
  580. )
  581. # # 3. Suspicious IPs (many requests in short time)
  582. # suspicious_ips = find_suspicious_activity(db, threshold=100, hours=1)
  583. #
  584. # if not suspicious_ips:
  585. # return
  586. #
  587. # # Limitar cantidad de notificaciones y ordenar por severidad
  588. # reported_count = 0
  589. # for ip, count in suspicious_ips:
  590. # if reported_count >= MAX_IPS_TO_REPORT:
  591. # # Si hay más IPs, notificar con resumen
  592. # remaining = len(suspicious_ips) - MAX_IPS_TO_REPORT
  593. # add_notification(
  594. # "info",
  595. # f"Hay {remaining} IP(s) adicionales con actividad sospechosa",
  596. # "fa-info-circle",
  597. # "security",
  598. # )
  599. # break
  600. #
  601. # # Verificar nivel crítico primero
  602. # if count > CRITICAL_IP_THRESHOLD:
  603. # add_notification(
  604. # "error",
  605. # f"Actividad crítica desde IP {ip}: {count:,} solicitudes/hora",
  606. # "fa-exclamation-triangle",
  607. # "security",
  608. # )
  609. # reported_count += 1
  610. # elif count > SUSPICIOUS_IP_THRESHOLD:
  611. # add_notification(
  612. # "warning",
  613. # f"Actividad sospechosa desde IP {ip}: {count:,} solicitudes/hora",
  614. # "fa-user-secret",
  615. # "security",
  616. # )
  617. # reported_count += 1
  618. except ImportError as e:
  619. logger.error(f"Error importing auditoria_service modules: {e}")
  620. except Exception as e:
  621. logger.error(f"Error checking security events: {e}", exc_info=True)
  622. def check_user_activity():
  623. """Checks user activity from the database"""
  624. try:
  625. from services.analytics.auditoria_service import (
  626. get_active_users_count,
  627. get_high_usage_users,
  628. )
  629. with get_db_session() as db:
  630. # 1. Active users in the last hour
  631. active_users = get_active_users_count(db, hours=1)
  632. if active_users > HIGH_ACTIVITY_THRESHOLD:
  633. add_notification(
  634. "info",
  635. _(
  636. "Alta actividad: %(count)d usuarios conectados en la última hora",
  637. count=active_users,
  638. ),
  639. "fa-users",
  640. "users",
  641. )
  642. elif active_users == 0:
  643. add_notification(
  644. "warning",
  645. _("No hay usuarios activos en la última hora"),
  646. "fa-users",
  647. "users",
  648. )
  649. # 2. Users with high data consumption
  650. high_usage_users = get_high_usage_users(db, hours=24, threshold_mb=100)
  651. # Limitar a top N usuarios
  652. high_usage_gb = HIGH_USAGE_GB_THRESHOLD * 1024
  653. for user, usage_mb in high_usage_users[:MAX_USERS_TO_REPORT]:
  654. # Solo notificar si supera el umbral alto
  655. if usage_mb > high_usage_gb:
  656. add_notification(
  657. "warning",
  658. _(
  659. "El usuario %(user)s consumió %(usage)s MB en 24h",
  660. user=user,
  661. usage=f"{usage_mb:,.0f}",
  662. ),
  663. "fa-chart-line",
  664. "users",
  665. )
  666. except ImportError as e:
  667. logger.error(f"Error importing auditoria_service modules: {e}")
  668. except Exception as e:
  669. logger.error(f"Error checking user activity: {e}", exc_info=True)