iatoolkit 0.11.0__py3-none-any.whl → 0.66.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. iatoolkit/base_company.py +11 -3
  2. iatoolkit/common/routes.py +92 -52
  3. iatoolkit/common/session_manager.py +0 -1
  4. iatoolkit/common/util.py +17 -27
  5. iatoolkit/iatoolkit.py +91 -47
  6. iatoolkit/infra/llm_client.py +7 -8
  7. iatoolkit/infra/openai_adapter.py +1 -1
  8. iatoolkit/infra/redis_session_manager.py +48 -2
  9. iatoolkit/locales/en.yaml +144 -0
  10. iatoolkit/locales/es.yaml +140 -0
  11. iatoolkit/repositories/database_manager.py +17 -2
  12. iatoolkit/repositories/models.py +31 -4
  13. iatoolkit/repositories/profile_repo.py +7 -2
  14. iatoolkit/services/auth_service.py +193 -0
  15. iatoolkit/services/branding_service.py +59 -18
  16. iatoolkit/services/dispatcher_service.py +10 -40
  17. iatoolkit/services/excel_service.py +15 -15
  18. iatoolkit/services/help_content_service.py +30 -0
  19. iatoolkit/services/history_service.py +2 -11
  20. iatoolkit/services/i18n_service.py +104 -0
  21. iatoolkit/services/jwt_service.py +15 -24
  22. iatoolkit/services/language_service.py +77 -0
  23. iatoolkit/services/onboarding_service.py +43 -0
  24. iatoolkit/services/profile_service.py +148 -75
  25. iatoolkit/services/query_service.py +124 -81
  26. iatoolkit/services/tasks_service.py +1 -1
  27. iatoolkit/services/user_feedback_service.py +68 -32
  28. iatoolkit/services/user_session_context_service.py +112 -54
  29. iatoolkit/static/images/fernando.jpeg +0 -0
  30. iatoolkit/static/js/chat_feedback_button.js +80 -0
  31. iatoolkit/static/js/chat_help_content.js +124 -0
  32. iatoolkit/static/js/chat_history_button.js +112 -0
  33. iatoolkit/static/js/chat_logout_button.js +36 -0
  34. iatoolkit/static/js/chat_main.js +148 -220
  35. iatoolkit/static/js/chat_onboarding_button.js +97 -0
  36. iatoolkit/static/js/chat_prompt_manager.js +94 -0
  37. iatoolkit/static/js/chat_reload_button.js +35 -0
  38. iatoolkit/static/styles/chat_iatoolkit.css +367 -199
  39. iatoolkit/static/styles/chat_modal.css +98 -76
  40. iatoolkit/static/styles/chat_public.css +107 -0
  41. iatoolkit/static/styles/landing_page.css +182 -0
  42. iatoolkit/static/styles/onboarding.css +169 -0
  43. iatoolkit/system_prompts/query_main.prompt +3 -12
  44. iatoolkit/templates/_company_header.html +20 -0
  45. iatoolkit/templates/_login_widget.html +42 -0
  46. iatoolkit/templates/base.html +40 -20
  47. iatoolkit/templates/change_password.html +57 -36
  48. iatoolkit/templates/chat.html +169 -83
  49. iatoolkit/templates/chat_modals.html +134 -68
  50. iatoolkit/templates/error.html +44 -8
  51. iatoolkit/templates/forgot_password.html +40 -23
  52. iatoolkit/templates/index.html +145 -0
  53. iatoolkit/templates/login_simulation.html +34 -0
  54. iatoolkit/templates/onboarding_shell.html +104 -0
  55. iatoolkit/templates/signup.html +63 -65
  56. iatoolkit/views/base_login_view.py +92 -0
  57. iatoolkit/views/change_password_view.py +56 -30
  58. iatoolkit/views/external_login_view.py +61 -28
  59. iatoolkit/views/{file_store_view.py → file_store_api_view.py} +9 -2
  60. iatoolkit/views/forgot_password_view.py +27 -19
  61. iatoolkit/views/help_content_api_view.py +54 -0
  62. iatoolkit/views/history_api_view.py +56 -0
  63. iatoolkit/views/home_view.py +50 -23
  64. iatoolkit/views/index_view.py +14 -0
  65. iatoolkit/views/init_context_api_view.py +73 -0
  66. iatoolkit/views/llmquery_api_view.py +57 -0
  67. iatoolkit/views/login_simulation_view.py +81 -0
  68. iatoolkit/views/login_view.py +130 -37
  69. iatoolkit/views/logout_api_view.py +49 -0
  70. iatoolkit/views/profile_api_view.py +46 -0
  71. iatoolkit/views/{prompt_view.py → prompt_api_view.py} +10 -10
  72. iatoolkit/views/signup_view.py +42 -35
  73. iatoolkit/views/{tasks_view.py → tasks_api_view.py} +10 -36
  74. iatoolkit/views/tasks_review_api_view.py +55 -0
  75. iatoolkit/views/user_feedback_api_view.py +60 -0
  76. iatoolkit/views/verify_user_view.py +35 -28
  77. {iatoolkit-0.11.0.dist-info → iatoolkit-0.66.2.dist-info}/METADATA +2 -2
  78. iatoolkit-0.66.2.dist-info/RECORD +119 -0
  79. iatoolkit/common/auth.py +0 -200
  80. iatoolkit/static/images/arrow_up.png +0 -0
  81. iatoolkit/static/images/diagrama_iatoolkit.jpg +0 -0
  82. iatoolkit/static/images/logo_clinica.png +0 -0
  83. iatoolkit/static/images/logo_iatoolkit.png +0 -0
  84. iatoolkit/static/images/logo_maxxa.png +0 -0
  85. iatoolkit/static/images/logo_notaria.png +0 -0
  86. iatoolkit/static/images/logo_tarjeta.png +0 -0
  87. iatoolkit/static/images/logo_umayor.png +0 -0
  88. iatoolkit/static/images/upload.png +0 -0
  89. iatoolkit/static/js/chat_feedback.js +0 -115
  90. iatoolkit/static/js/chat_history.js +0 -117
  91. iatoolkit/static/styles/chat_info.css +0 -53
  92. iatoolkit/templates/header.html +0 -31
  93. iatoolkit/templates/home.html +0 -199
  94. iatoolkit/templates/login.html +0 -43
  95. iatoolkit/templates/test.html +0 -9
  96. iatoolkit/views/chat_token_request_view.py +0 -98
  97. iatoolkit/views/chat_view.py +0 -58
  98. iatoolkit/views/download_file_view.py +0 -58
  99. iatoolkit/views/external_chat_login_view.py +0 -95
  100. iatoolkit/views/history_view.py +0 -57
  101. iatoolkit/views/llmquery_view.py +0 -65
  102. iatoolkit/views/tasks_review_view.py +0 -83
  103. iatoolkit/views/user_feedback_view.py +0 -74
  104. iatoolkit-0.11.0.dist-info/RECORD +0 -110
  105. {iatoolkit-0.11.0.dist-info → iatoolkit-0.66.2.dist-info}/WHEEL +0 -0
  106. {iatoolkit-0.11.0.dist-info → iatoolkit-0.66.2.dist-info}/top_level.txt +0 -0
@@ -37,9 +37,14 @@ class RedisSessionManager:
37
37
  return cls._client
38
38
 
39
39
  @classmethod
40
- def set(cls, key: str, value: str, ex: int = None):
40
+ def set(cls, key: str, value: str, **kwargs):
41
+ """
42
+ Método set flexible que pasa argumentos opcionales (como ex, nx)
43
+ directamente al cliente de redis.
44
+ """
41
45
  client = cls._get_client()
42
- result = client.set(key, value, ex=ex)
46
+ # Pasa todos los argumentos de palabra clave adicionales al cliente real
47
+ result = client.set(key, value, **kwargs)
43
48
  return result
44
49
 
45
50
  @classmethod
@@ -49,12 +54,53 @@ class RedisSessionManager:
49
54
  result = value if value is not None else default
50
55
  return result
51
56
 
57
+ @classmethod
58
+ def hset(cls, key: str, field: str, value: str):
59
+ """
60
+ Establece un campo en un Hash de Redis.
61
+ """
62
+ client = cls._get_client()
63
+ return client.hset(key, field, value)
64
+
65
+ @classmethod
66
+ def hget(cls, key: str, field: str):
67
+ """
68
+ Obtiene el valor de un campo de un Hash de Redis.
69
+ Devuelve None si la clave o el campo no existen.
70
+ """
71
+ client = cls._get_client()
72
+ return client.hget(key, field)
73
+
74
+ @classmethod
75
+ def hdel(cls, key: str, *fields):
76
+ """
77
+ Elimina uno o más campos de un Hash de Redis.
78
+ """
79
+ client = cls._get_client()
80
+ return client.hdel(key, *fields)
81
+
82
+ @classmethod
83
+ def pipeline(cls):
84
+ """
85
+ Inicia una transacción (pipeline) de Redis.
86
+ """
87
+ client = cls._get_client()
88
+ return client.pipeline()
89
+
90
+
52
91
  @classmethod
53
92
  def remove(cls, key: str):
54
93
  client = cls._get_client()
55
94
  result = client.delete(key)
56
95
  return result
57
96
 
97
+ @classmethod
98
+ def exists(cls, key: str) -> bool:
99
+ """Verifica si una clave existe en Redis."""
100
+ client = cls._get_client()
101
+ # El comando EXISTS de Redis devuelve un entero (0 o 1). Lo convertimos a booleano.
102
+ return bool(client.exists(key))
103
+
58
104
  @classmethod
59
105
  def set_json(cls, key: str, value: dict, ex: int = None):
60
106
  json_str = json.dumps(value)
@@ -0,0 +1,144 @@
1
+ # Language: English
2
+ ui:
3
+ login_widget:
4
+ title: "Sign In"
5
+ welcome_message: "Enter your credentials or register to access Sample Company’s AI platform."
6
+ email_placeholder: "Email address"
7
+ password_placeholder: "Password"
8
+ login_button: "Login"
9
+ forgot_password_link: "Forgot your password?"
10
+ no_account_prompt: "Don't have an account?"
11
+ signup_link: "Sign Up"
12
+
13
+ signup:
14
+ title: "Create an Account"
15
+ subtitle: "Start your journey with us today."
16
+ first_name_label: "First Name"
17
+ last_name_label: "Last Name"
18
+ email_label: "Email Address"
19
+ password_label: "Password"
20
+ confirm_password_label: "Confirm Password"
21
+ signup_button: "Create Account"
22
+ already_have_account: "Already have an account?"
23
+ login_link: "Log In"
24
+ disclaimer: "🔒We value your privacy. Your data will be used exclusively for the operation of the platform."
25
+
26
+ forgot_password:
27
+ title: "Recover Password"
28
+ subtitle: "Enter your email address and we will send you a link to reset your password."
29
+ submit_button: "Send Recovery Link"
30
+ back_to_login: "Back to Login"
31
+
32
+ change_password:
33
+ title: "Create New Password"
34
+ subtitle: "You are changing the password for <strong>{email}</strong>."
35
+ temp_code_label: "Temporary Code"
36
+ temp_code_placeholder: "Check your email"
37
+ new_password_label: "New Password"
38
+ password_instructions: "Must contain at least 8 characters, an uppercase letter, a lowercase letter, a number, and a special character."
39
+ confirm_password_label: "Confirm New Password"
40
+ save_button: "Save Password"
41
+ back_to_home: "Back to home"
42
+
43
+ chat:
44
+ welcome_message: "Hello! How can I help you today?"
45
+ input_placeholder: "Type your query here..."
46
+ prompts_available: "Available prompts"
47
+
48
+ tooltips:
49
+ history: "History of my queries"
50
+ reload_context: "Force Context Reload"
51
+ feedback: "Your feedback is very important"
52
+ usage_guide: "Usage Guide"
53
+ onboarding: "How to ask better questions"
54
+ logout: "Log out"
55
+ use_prompt_assistant: "Use Prompt Assistant"
56
+ attach_files: "Attach files"
57
+ view_attached_files: "View attached files"
58
+ send: "Send"
59
+ stop: "Stop"
60
+
61
+ modals:
62
+ files_title: "Uploaded Files"
63
+ feedback_title: "Your Opinion is Important"
64
+ feedback_prompt: "How useful was the assistant's response?"
65
+ feedback_comment_label: "Your feedback helps us improve:"
66
+ feedback_comment_placeholder: "Write your opinion, suggestions, or comments here..."
67
+ history_title: "Query History"
68
+ history_table_date: "Date"
69
+ history_table_query: "Query"
70
+ loading_history: "Loading history..."
71
+ no_history_found: "No query history found."
72
+ help_title: "AI Assistant User Guide"
73
+
74
+ buttons:
75
+ cancel: "Close"
76
+ send: "Send"
77
+ stop: "Stop"
78
+
79
+ errors:
80
+ auth:
81
+ invalid_password: "The provided password is incorrect."
82
+ user_not_found: "A user with that email address was not found."
83
+ invalid_or_expired_token: "Invalid or expired token."
84
+ session_creation_failed: "Could not create user session."
85
+ authentication_required: "Authentication required. No session cookie or API Key provided."
86
+ invalid_api_key: "Invalid or inactive API Key."
87
+ no_user_identifier_api: "No user_identifier provided for API call."
88
+ templates:
89
+ company_not_found: "Company not found."
90
+ home_template_not_found: "The home page template for the company '{company_name}' is not configured."
91
+ template_not_found: "Template not found: '{template_name}'."
92
+
93
+ processing_error: "An error occurred while processing the custom home page template: {error}"
94
+ general:
95
+ unexpected_error: "An unexpected error has occurred. Please contact support."
96
+ unsupported_language: "The selected language is not supported."
97
+ signup:
98
+ company_not_found: "The company {company_name} does not exist."
99
+ incorrect_password_for_existing_user: "The password for the user {email} is incorrect."
100
+ user_already_registered: "The user with email '{email}' already exists in this company."
101
+ password_mismatch: "The passwords do not match. Please try again."
102
+ change_password:
103
+ token_expired: "The password change link has expired. Please request a new one."
104
+ password_mismatch: "The passwords do not match. Please try again."
105
+ invalid_temp_code: "The temporary code is not valid. Please check it or request a new one."
106
+ forgot_password:
107
+ user_not_registered: "The user with email {email} is not registered."
108
+ verification:
109
+ token_expired: "The verification link has expired. Please contact support if you need a new one."
110
+ user_not_found: "The user you are trying to verify does not exist."
111
+ validation:
112
+ password_too_short: "Password must be at least 8 characters long."
113
+ password_no_uppercase: "Password must contain at least one uppercase letter."
114
+ password_no_lowercase: "Password must contain at least one lowercase letter."
115
+ password_no_digit: "Password must contain at least one number."
116
+ password_no_special_char: "Password must contain at least one special character."
117
+
118
+ api_responses:
119
+ context_reloaded_success: "The context has been successfully reloaded."
120
+
121
+ flash_messages:
122
+ password_changed_success: "Your password has been successfully reset. You can now log in."
123
+ login_required: "Please log in to continue."
124
+ signup_success: "Registration successful. Please check your email to verify your account."
125
+ user_associated_success: "Existing user successfully associated with the new company."
126
+ account_verified_success: "Your account has been successfully verified. Welcome!"
127
+ forgot_password_success: "If your email is registered, you will receive a link to reset your password."
128
+
129
+ # Keys specifically for JavaScript
130
+ js_messages:
131
+ feedback_sent_success_title: "Feedback Sent"
132
+ feedback_sent_success_body: "Thank you for your feedback!"
133
+ feedback_sent_error: "Could not send feedback, please try again."
134
+ feedback_rating_error: "Please rate the assistant using the stars."
135
+ feedback_comment_error: "Please write your comment before sending."
136
+ context_reloaded: "Context has been reloaded."
137
+ error_loading_history: "An error occurred while loading the history."
138
+ request_aborted: "The response generation has been stopped."
139
+ processing_error: "An error occurred while processing the request."
140
+ server_comm_error: "Server communication error ({status}). Please try again later."
141
+ network_error: "A network error occurred. Please try again in a few moments."
142
+ unknown_server_error: "Unknown server error."
143
+ loading: "Loading..."
144
+ reload_init: "init reloading context in background..."
@@ -0,0 +1,140 @@
1
+ # locales/es.yaml
2
+ ui:
3
+ login_widget:
4
+ title: "Iniciar Sesión"
5
+ welcome_message: "Ingresa tus credenciales o registrate para acceder a la plataforma IA de Sample Company."
6
+ email_placeholder: "Correo electrónico"
7
+ login_button: "Acceder"
8
+ forgot_password_link: "¿Olvidaste tu contraseña?"
9
+ no_account_prompt: "¿No tienes una cuenta?"
10
+ signup_link: "Regístrate"
11
+
12
+ signup:
13
+ title: "Crear una Cuenta"
14
+ subtitle: "Comienza tu viaje con nosotros hoy."
15
+ first_name_label: "Nombre"
16
+ last_name_label: "Apellido"
17
+ email_label: "Correo Electrónico"
18
+ password_label: "Contraseña"
19
+ confirm_password_label: "Confirmar Contraseña"
20
+ signup_button: "Crear Cuenta"
21
+ already_have_account: "¿Ya tienes una cuenta?"
22
+ login_link: "Inicia Sesión"
23
+ disclaimer: "🔒 Valoramos tu privacidad. Tus datos se usarán exclusivamente para el funcionamiento de la plataforma."
24
+
25
+ forgot_password:
26
+ title: "Recuperar Contraseña"
27
+ subtitle: "Ingresa tu correo electrónico y te enviaremos un enlace para restablecer tu contraseña."
28
+ submit_button: "Enviar Enlace de Recuperación"
29
+ back_to_login: "Volver a Iniciar Sesión"
30
+
31
+ change_password:
32
+ title: "Crear Nueva Contraseña"
33
+ subtitle: "Estás cambiando la contraseña para <strong>{email}</strong>."
34
+ temp_code_label: "Código Temporal"
35
+ temp_code_placeholder: "Revisa tu correo electrónico"
36
+ new_password_label: "Nueva Contraseña"
37
+ password_instructions: "Debe contener al menos 8 caracteres, mayúscula, minúscula, número y un carácter especial."
38
+ confirm_password_label: "Confirmar Nueva Contraseña"
39
+ save_button: "Guardar Contraseña"
40
+ back_to_home: "Volver al inicio"
41
+
42
+ chat:
43
+ welcome_message: "¡Hola! ¿En qué te puedo ayudar hoy?"
44
+ input_placeholder: "Escribe tu consulta aquí..."
45
+ prompts_available: "Prompts disponibles"
46
+
47
+ tooltips:
48
+ history: "Historial con mis consultas"
49
+ reload_context: "Forzar Recarga de Contexto"
50
+ feedback: "Tu feedback es muy importante"
51
+ usage_guide: "Guía de Uso"
52
+ onboarding: "Cómo preguntar mejor"
53
+ logout: "Cerrar sesión"
54
+ use_prompt_assistant: "Usar Asistente de Prompts"
55
+ attach_files: "Adjuntar archivos"
56
+ view_attached_files: "Ver archivos adjuntos"
57
+ modals:
58
+ files_title: "Archivos Cargados"
59
+ feedback_title: "Tu Opinión es Importante"
60
+ feedback_prompt: "¿Qué tan útil fue la respuesta del asistente?"
61
+ feedback_comment_label: "Tu comentario nos ayuda a mejorar:"
62
+ feedback_comment_placeholder: "Escribe aquí tu opinión, sugerencias o comentarios..."
63
+ history_title: "Historial de Consultas"
64
+ history_table_date: "Fecha"
65
+ history_table_query: "Consulta"
66
+ loading_history: "Cargando historial..."
67
+ no_history_found: "No se encontró historial de consultas."
68
+ help_title: "Guía de uso del Asistente IA"
69
+
70
+ buttons:
71
+ cancel: "Cerrar"
72
+ send: "Enviar"
73
+ stop: "Detener"
74
+
75
+ errors:
76
+ auth:
77
+ invalid_password: "La contraseña proporcionada es incorrecta."
78
+ user_not_found: "No se encontró un usuario con ese correo."
79
+ invalid_or_expired_token: "Token inválido o expirado."
80
+ session_creation_failed: "No se pudo crear la sesión del usuario."
81
+ authentication_required: "Autenticación requerida. No se proporcionó cookie de sesión o clave de API."
82
+ invalid_api_key: "Clave de API inválida o inactiva."
83
+ no_user_identifier_api: "No se proporcionó user_identifier para la llamada a la API."
84
+ templates:
85
+ company_not_found: "Empresa no encontrada."
86
+ home_template_not_found: "La plantilla de la página de inicio para la empresa '{company_name}' no está configurada."
87
+ template_not_found: "No se encontro el template: '{template_name}'."
88
+ processing_error: "Ocurrió un error al procesar la plantilla personalizada de la página de inicio: {error}"
89
+
90
+ general:
91
+ unexpected_error: "Ha ocurrido un error inesperado. Por favor, contacta a soporte."
92
+ unsupported_language: "El idioma seleccionado no es válido."
93
+ signup:
94
+ company_not_found: "La empresa {company_name} no existe."
95
+ incorrect_password_for_existing_user: "La contraseña para el usuario {email} es incorrecta."
96
+ user_already_registered: "El usuario con email '{email}' ya existe en esta empresa."
97
+ password_mismatch: "Las contraseñas no coinciden. Por favor, inténtalo de nuevo."
98
+ change_password:
99
+ token_expired: "El enlace de cambio de contraseña ha expirado. Por favor, solicita uno nuevo."
100
+ password_mismatch: "Las contraseñas no coinciden. Por favor, inténtalo nuevamente."
101
+ invalid_temp_code: "El código temporal no es válido. Por favor, verifica o solicita uno nuevo."
102
+ forgot_password:
103
+ user_not_registered: "El usuario con correo {email} no está registrado."
104
+ verification:
105
+ token_expired: "El enlace de verificación ha expirado. Por favor, contacta a soporte si necesitas uno nuevo."
106
+ user_not_found: "El usuario que intentas verificar no existe."
107
+ validation:
108
+ password_too_short: "La contraseña debe tener al menos 8 caracteres."
109
+ password_no_uppercase: "La contraseña debe tener al menos una letra mayúscula."
110
+ password_no_lowercase: "La contraseña debe tener al menos una letra minúscula."
111
+ password_no_digit: "La contraseña debe tener al menos un número."
112
+ password_no_special_char: "La contraseña debe tener al menos un carácter especial."
113
+
114
+ api_responses:
115
+ context_reloaded_success: "El contexto se ha recargado con éxito."
116
+
117
+ flash_messages:
118
+ password_changed_success: "Tu contraseña ha sido restablecida exitosamente. Ahora puedes iniciar sesión."
119
+ signup_success: "Registro exitoso. Por favor, revisa tu correo para verificar tu cuenta."
120
+ user_associated_success: "Usuario existente asociado exitosamente a la nueva empresa."
121
+ account_verified_success: "Tu cuenta ha sido verificada exitosamente. ¡Bienvenido!"
122
+ forgot_password_success: "Si tu correo está registrado, recibirás un enlace para restablecer tu contraseña."
123
+
124
+ # Claves específicas para JavaScript
125
+ js_messages:
126
+ feedback_sent_success_title: "Feedback Enviado"
127
+ feedback_sent_success_body: "¡Gracias por tu comentario!"
128
+ feedback_sent_error: "No se pudo enviar el feedback, por favor intente nuevamente."
129
+ feedback_rating_error: "Por favor, califica al asistente con las estrellas."
130
+ feedback_comment_error: "Por favor, escribe tu comentario antes de enviar."
131
+ context_reloaded: "El contexto ha sido recargado."
132
+ error_loading_history: "Ocurrió un error al cargar el historial."
133
+ request_aborted: "La generación de la respuesta ha sido detenida."
134
+ processing_error: "Ocurrió un error al procesar la solicitud."
135
+ server_comm_error: "Error de comunicación con el servidor ({status}). Por favor, intente de nuevo más tarde."
136
+ network_error: "Ocurrió un error de red. Por favor, inténtalo de nuevo en unos momentos."
137
+ unknown_server_error: "Error desconocido del servidor."
138
+ loading: "Cargando..."
139
+ reload_init: "Iniciando recarga de contexto en segundo plano..."
140
+
@@ -21,8 +21,23 @@ class DatabaseManager:
21
21
  :param echo: Si True, habilita logs de SQL.
22
22
  """
23
23
  self.url = make_url(database_url)
24
- self._engine = create_engine(database_url, echo=False)
25
- self.SessionFactory = sessionmaker(bind=self._engine)
24
+ if database_url.startswith('sqlite'): # for tests
25
+ self._engine = create_engine(database_url, echo=False)
26
+ else:
27
+ self._engine = create_engine(
28
+ database_url,
29
+ echo=False,
30
+ pool_size=2, # per worker
31
+ max_overflow=3,
32
+ pool_timeout=30,
33
+ pool_recycle=1800,
34
+ pool_pre_ping=True,
35
+ future=True,
36
+ )
37
+ self.SessionFactory = sessionmaker(bind=self._engine,
38
+ autoflush=False,
39
+ autocommit=False,
40
+ expire_on_commit=False)
26
41
  self.scoped_session = scoped_session(self.SessionFactory)
27
42
 
28
43
  # REGISTRAR pgvector para cada nueva conexión solo en postgres
@@ -3,9 +3,10 @@
3
3
  #
4
4
  # IAToolkit is open source software.
5
5
 
6
- from sqlalchemy import Column, Integer, String, DateTime, Enum, Text, JSON, Boolean, ForeignKey, Table
6
+ from sqlalchemy import Column, Integer, BigInteger, String, DateTime, Enum, Text, JSON, Boolean, ForeignKey, Table
7
7
  from sqlalchemy.orm import DeclarativeBase
8
8
  from sqlalchemy.orm import relationship, class_mapper, declarative_base
9
+ from sqlalchemy.sql import func
9
10
  from datetime import datetime
10
11
  from pgvector.sqlalchemy import Vector
11
12
  from enum import Enum as PyEnum
@@ -52,13 +53,15 @@ class Company(Base):
52
53
  id = Column(Integer, primary_key=True)
53
54
  short_name = Column(String(20), nullable=False, unique=True, index=True)
54
55
  name = Column(String(256), nullable=False)
56
+ default_language = Column(String(5), nullable=False, default='es')
55
57
 
56
58
  # encrypted api-key
57
59
  openai_api_key = Column(String, nullable=True)
58
60
  gemini_api_key = Column(String, nullable=True)
59
61
 
60
62
  branding = Column(JSON, nullable=True)
61
- parameters = Column(JSON, nullable=True, default={})
63
+ onboarding_cards = Column(JSON, nullable=True)
64
+ parameters = Column(JSON, nullable=True)
62
65
  created_at = Column(DateTime, default=datetime.now)
63
66
  allow_jwt = Column(Boolean, default=True, nullable=True)
64
67
 
@@ -105,6 +108,7 @@ class User(Base):
105
108
  created_at = Column(DateTime, default=datetime.now)
106
109
  password = Column(String, nullable=False)
107
110
  verified = Column(Boolean, nullable=False, default=False)
111
+ preferred_language = Column(String(5), nullable=True)
108
112
  verification_url = Column(String, nullable=True)
109
113
  temp_code = Column(String, nullable=True)
110
114
 
@@ -264,8 +268,7 @@ class UserFeedback(Base):
264
268
  id = Column(Integer, primary_key=True)
265
269
  company_id = Column(Integer, ForeignKey('iat_companies.id',
266
270
  ondelete='CASCADE'), nullable=False)
267
- local_user_id = Column(Integer, default=0, nullable=True)
268
- external_user_id = Column(String(128), default='', nullable=True)
271
+ user_identifier = Column(String(128), default='', nullable=True)
269
272
  message = Column(Text, nullable=False)
270
273
  rating = Column(Integer, nullable=False)
271
274
  created_at = Column(DateTime, default=datetime.now)
@@ -307,3 +310,27 @@ class Prompt(Base):
307
310
 
308
311
  company = relationship("Company", back_populates="prompts")
309
312
  category = relationship("PromptCategory", back_populates="prompts")
313
+
314
+ class AccessLog(Base):
315
+ # Modelo ORM para registrar cada intento de acceso a la plataforma.
316
+ __tablename__ = 'iat_access_log'
317
+
318
+ id = Column(BigInteger, primary_key=True)
319
+
320
+ timestamp = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
321
+ company_short_name = Column(String(100), nullable=False, index=True)
322
+ user_identifier = Column(String(255), index=True)
323
+
324
+ # Cómo y el Resultado
325
+ auth_type = Column(String(20), nullable=False) # 'local', 'external_api', 'redeem_token', etc.
326
+ outcome = Column(String(10), nullable=False) # 'success' o 'failure'
327
+ reason_code = Column(String(50)) # Causa de fallo, ej: 'INVALID_CREDENTIALS'
328
+
329
+ # Contexto de la Petición
330
+ source_ip = Column(String(45), nullable=False)
331
+ user_agent_hash = Column(String(16)) # Hash corto del User-Agent
332
+ request_path = Column(String(255), nullable=False)
333
+
334
+ def __repr__(self):
335
+ return (f"<AccessLog(id={self.id}, company='{self.company_short_name}', "
336
+ f"user='{self.user_identifier}', outcome='{self.outcome}')>")
@@ -72,9 +72,14 @@ class ProfileRepo:
72
72
  def create_company(self, new_company: Company):
73
73
  company = self.session.query(Company).filter_by(name=new_company.name).first()
74
74
  if company:
75
- company.parameters = new_company.parameters
76
- company.branding = new_company.branding
75
+ if company.parameters != new_company.parameters:
76
+ company.parameters = new_company.parameters
77
+ if company.branding != new_company.branding:
78
+ company.branding = new_company.branding
79
+ if company.onboarding_cards != new_company.onboarding_cards:
80
+ company.onboarding_cards = new_company.onboarding_cards
77
81
  else:
82
+ # Si la compañía no existe, la añade a la sesión.
78
83
  self.session.add(new_company)
79
84
  company = new_company
80
85
 
@@ -0,0 +1,193 @@
1
+ # Copyright (c) 2024 Fernando Libedinsky
2
+ # Product: IAToolkit
3
+ #
4
+ # IAToolkit is open source software.
5
+
6
+ from flask import request
7
+ from injector import inject
8
+ from iatoolkit.services.profile_service import ProfileService
9
+ from iatoolkit.services.jwt_service import JWTService
10
+ from iatoolkit.services.i18n_service import I18nService
11
+ from iatoolkit.repositories.database_manager import DatabaseManager
12
+ from iatoolkit.repositories.models import AccessLog
13
+ from flask import request
14
+ import logging
15
+ import hashlib
16
+
17
+
18
+ class AuthService:
19
+ """
20
+ Centralized service for handling authentication for all incoming requests.
21
+ It determines the user's identity based on either a Flask session cookie or an API Key.
22
+ """
23
+
24
+ @inject
25
+ def __init__(self, profile_service: ProfileService,
26
+ jwt_service: JWTService,
27
+ db_manager: DatabaseManager,
28
+ i18n_service: I18nService
29
+ ):
30
+ self.profile_service = profile_service
31
+ self.jwt_service = jwt_service
32
+ self.db_manager = db_manager
33
+ self.i18n_service = i18n_service
34
+
35
+ def login_local_user(self, company_short_name: str, email: str, password: str) -> dict:
36
+ # try to autenticate a local user, register the event and return the result
37
+ auth_response = self.profile_service.login(
38
+ company_short_name=company_short_name,
39
+ email=email,
40
+ password=password,
41
+ )
42
+
43
+ if not auth_response.get('success'):
44
+ self.log_access(
45
+ company_short_name=company_short_name,
46
+ user_identifier=email,
47
+ auth_type='local',
48
+ outcome='failure',
49
+ reason_code='INVALID_CREDENTIALS',
50
+ )
51
+ else:
52
+ self.log_access(
53
+ company_short_name=company_short_name,
54
+ auth_type='local',
55
+ outcome='success',
56
+ user_identifier=auth_response.get('user_identifier')
57
+ )
58
+
59
+ return auth_response
60
+
61
+ def redeem_token_for_session(self, company_short_name: str, token: str) -> dict:
62
+ # redeem a token for a session, register the event and return the result
63
+ payload = self.jwt_service.validate_chat_jwt(token)
64
+
65
+ if not payload:
66
+ self.log_access(
67
+ company_short_name=company_short_name,
68
+ auth_type='redeem_token',
69
+ outcome='failure',
70
+ reason_code='JWT_INVALID'
71
+ )
72
+ return {'success': False, 'error': self.i18n_service.t('errors.auth.invalid_or_expired_token')}
73
+
74
+ # 2. if token is valid, extract the user_identifier
75
+ user_identifier = payload.get('user_identifier')
76
+ try:
77
+ # create the Flask session
78
+ self.profile_service.set_session_for_user(company_short_name, user_identifier)
79
+ self.log_access(
80
+ company_short_name=company_short_name,
81
+ auth_type='redeem_token',
82
+ outcome='success',
83
+ user_identifier=user_identifier
84
+ )
85
+ return {'success': True, 'user_identifier': user_identifier}
86
+ except Exception as e:
87
+ logging.error(f"Error al crear la sesión desde token para {user_identifier}: {e}")
88
+ self.log_access(
89
+ company_short_name=company_short_name,
90
+ auth_type='redeem_token',
91
+ outcome='failure',
92
+ reason_code='SESSION_CREATION_FAILED',
93
+ user_identifier=user_identifier
94
+ )
95
+ return {'success': False, 'error': self.i18n_service.t('errors.auth.session_creation_failed')}
96
+
97
+ def verify(self, anonymous: bool = False) -> dict:
98
+ """
99
+ Verifies the current request and identifies the user.
100
+ If anonymous is True the non-presence of use_identifier is ignored
101
+
102
+ Returns a dictionary with:
103
+ - success: bool
104
+ - user_identifier: str (if successful)
105
+ - company_short_name: str (if successful)
106
+ - error_message: str (on failure)
107
+ - status_code: int (on failure)
108
+ """
109
+ # --- Priority 1: Check for a valid Flask web session ---
110
+ session_info = self.profile_service.get_current_session_info()
111
+ if session_info and session_info.get('user_identifier'):
112
+ # User is authenticated via a web session cookie.
113
+ return {
114
+ "success": True,
115
+ "company_short_name": session_info['company_short_name'],
116
+ "user_identifier": session_info['user_identifier'],
117
+ }
118
+
119
+ # --- Priority 2: Check for a valid API Key in headers ---
120
+ api_key = None
121
+ auth = request.headers.get('Authorization', '')
122
+ if isinstance(auth, str) and auth.lower().startswith('bearer '):
123
+ api_key = auth.split(' ', 1)[1].strip()
124
+
125
+ if not api_key:
126
+ # --- Failure: No valid credentials found ---
127
+ logging.info(f"Authentication required. No session cookie or API Key provided.")
128
+ return {"success": False,
129
+ "error_message": self.i18n_service.t('errors.auth.authentication_required'),
130
+ "status_code": 401}
131
+
132
+ # check if the api-key is valid and active
133
+ api_key_entry = self.profile_service.get_active_api_key_entry(api_key)
134
+ if not api_key_entry:
135
+ logging.info(f"Invalid or inactive API Key {api_key}")
136
+ return {"success": False,
137
+ "error_message": self.i18n_service.t('errors.auth.invalid_api_key'),
138
+ "status_code": 402}
139
+
140
+ # get the company from the api_key_entry
141
+ company = api_key_entry.company
142
+
143
+ # For API calls, the external_user_id must be provided in the request.
144
+ data = request.get_json(silent=True) or {}
145
+ user_identifier = data.get('user_identifier', '')
146
+ if not anonymous and not user_identifier:
147
+ logging.info(f"No user_identifier provided for API call.")
148
+ return {"success": False,
149
+ "error_message": self.i18n_service.t('errors.auth.no_user_identifier_api'),
150
+ "status_code": 403}
151
+
152
+ return {
153
+ "success": True,
154
+ "company_short_name": company.short_name,
155
+ "user_identifier": user_identifier
156
+ }
157
+
158
+
159
+ def log_access(self,
160
+ company_short_name: str,
161
+ auth_type: str,
162
+ outcome: str,
163
+ user_identifier: str = None,
164
+ reason_code: str = None):
165
+ """
166
+ Registra un intento de acceso en la base de datos.
167
+ Es "best-effort" y no debe interrumpir el flujo de autenticación.
168
+ """
169
+ session = self.db_manager.scoped_session()
170
+ try:
171
+ # Capturar datos del contexto de la petición de Flask
172
+ source_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
173
+ path = request.path
174
+ ua = request.headers.get('User-Agent', '')
175
+ ua_hash = hashlib.sha256(ua.encode()).hexdigest()[:16] if ua else None
176
+
177
+ # Crear la entrada de log
178
+ log_entry = AccessLog(
179
+ company_short_name=company_short_name,
180
+ user_identifier=user_identifier,
181
+ auth_type=auth_type,
182
+ outcome=outcome,
183
+ reason_code=reason_code,
184
+ source_ip=source_ip,
185
+ user_agent_hash=ua_hash,
186
+ request_path=path,
187
+ )
188
+ session.add(log_entry)
189
+ session.commit()
190
+
191
+ except Exception as e:
192
+ logging.error(f"Fallo al escribir en AccessLog: {e}", exc_info=False)
193
+ session.rollback()