notifications.py 25 KB

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