AIdeaText commited on
Commit
ad7e4c8
verified
1 Parent(s): ead6ddd

Update modules/auth/auth.py

Browse files
Files changed (1) hide show
  1. modules/auth/auth.py +165 -128
modules/auth/auth.py CHANGED
@@ -1,52 +1,163 @@
1
- #/modules/auth/auth.py
 
2
  import gradio as gr
3
  import os
4
- from azure.cosmos import CosmosClient, exceptions
5
- from azure.cosmos.exceptions import CosmosHttpResponseError
6
  import bcrypt
7
  import base64
 
 
 
 
8
  from ..database.sql_db import (
9
  get_user,
10
  get_student_user,
11
- get_admin_user,
12
  create_student_user,
13
  update_student_user,
14
  delete_student_user,
15
  record_login,
16
- record_logout
17
  )
18
 
19
- import logging
20
 
21
- from datetime import datetime, timezone
 
 
22
 
23
- logger = logging.getLogger(__name__)
 
24
 
 
25
  def clean_and_validate_key(key):
26
- """Limpia y valida la clave de CosmosDB"""
27
  key = key.strip()
28
  while len(key) % 4 != 0:
29
- key += '='
30
  try:
31
  base64.b64decode(key)
32
  return key
33
- except:
34
- raise ValueError("La clave proporcionada no es v谩lida")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- # Verificar las variables de entorno
37
- endpoint = os.getenv("COSMOS_ENDPOINT")
38
- key = os.getenv("COSMOS_KEY")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- if not endpoint or not key:
41
- raise ValueError("Las variables de entorno COSMOS_ENDPOINT y COSMOS_KEY deben estar configuradas")
 
42
 
43
- key = clean_and_validate_key(key)
 
 
44
 
 
 
 
45
 
 
 
 
46
 
47
- ##################################################################
48
  def create_auth_interface():
49
- """Crea la interfaz de autenticaci贸n."""
 
 
50
  with gr.Blocks() as auth_interface:
51
  gr.Markdown("# Login")
52
  username = gr.Textbox(label="Usuario")
@@ -61,120 +172,46 @@ def create_auth_interface():
61
  login_btn.click(fn=handle_login, inputs=[username, password], outputs=message)
62
  return auth_interface
63
 
64
- ######################################################################################
65
- def authenticate_student(username, password):
66
- """Autentica un estudiante"""
67
- success, role = authenticate_user(username, password)
68
- if success and role == 'Estudiante':
69
- return True, role
70
- return False, None
71
 
72
- def authenticate_admin(username, password):
73
- """Autentica un administrador"""
74
- success, role = authenticate_user(username, password)
75
- if success and role == 'Administrador':
76
- return True, role
77
- return False, None
 
78
 
79
- def register_student(username, password, additional_info=None):
80
- """Registra un nuevo estudiante"""
81
- try:
82
- if get_student_user(username):
83
- logger.warning(f"Estudiante ya existe: {username}")
84
- return False
85
 
86
- hashed_password = hash_password(password)
87
-
88
- # Asegurarse que additional_info tenga el rol correcto
89
- if not additional_info:
90
- additional_info = {}
91
- additional_info['role'] = 'Estudiante'
92
-
93
- success = create_student_user(username, hashed_password, additional_info)
94
- if success:
95
- logger.info(f"Nuevo estudiante registrado: {username}")
96
- return True
97
-
98
- logger.error(f"Error al crear estudiante: {username}")
99
- return False
100
-
101
- except Exception as e:
102
- logger.error(f"Error al registrar estudiante: {str(e)}")
103
- return False
104
 
105
- def update_student_info(username, new_info):
106
- """Actualiza la informaci贸n de un estudiante"""
107
- try:
108
- if 'password' in new_info:
109
- new_info['password'] = hash_password(new_info['password'])
110
-
111
- success = update_student_user(username, new_info)
112
- if success:
113
- logger.info(f"Informaci贸n actualizada: {username}")
114
- return True
115
-
116
- logger.error(f"Error al actualizar: {username}")
117
- return False
118
-
119
- except Exception as e:
120
- logger.error(f"Error en actualizaci贸n: {str(e)}")
121
- return False
122
 
123
- def delete_student(username):
124
- """Elimina un estudiante"""
125
- try:
126
- success = delete_student_user(username)
127
- if success:
128
- logger.info(f"Estudiante eliminado: {username}")
129
- return True
130
-
131
- logger.error(f"Error al eliminar: {username}")
132
- return False
133
-
134
- except Exception as e:
135
- logger.error(f"Error en eliminaci贸n: {str(e)}")
136
- return False
137
 
138
- def logout():
139
- """Cierra la sesi贸n del usuario"""
140
- try:
141
- if 'session_id' in st.session_state and 'username' in st.session_state:
142
- success = record_logout(
143
- st.session_state.username,
144
- st.session_state.session_id
145
- )
146
- if success:
147
- logger.info(f"Sesi贸n cerrada: {st.session_state.username}")
148
- else:
149
- logger.warning(f"Error al registrar cierre de sesi贸n: {st.session_state.username}")
150
-
151
- except Exception as e:
152
- logger.error(f"Error en logout: {str(e)}")
153
- finally:
154
- st.session_state.clear()
155
-
156
- def hash_password(password):
157
- """Hashea una contrase帽a"""
158
- return bcrypt.hashpw(
159
- password.encode('utf-8'),
160
- bcrypt.gensalt()
161
- ).decode('utf-8')
162
-
163
- def verify_password(stored_password, provided_password):
164
- """Verifica una contrase帽a"""
165
- return bcrypt.checkpw(
166
- provided_password.encode('utf-8'),
167
- stored_password.encode('utf-8')
168
- )
169
 
170
  __all__ = [
171
- 'create_auth_interface', # por 'authenticate_user',
172
- 'authenticate_admin',
173
- 'authenticate_student',
174
- 'register_student',
175
- 'update_student_info',
176
- 'delete_student',
177
- 'logout',
178
- 'hash_password',
179
- 'verify_password'
 
180
  ]
 
1
+ # modules/auth/auth.py
2
+
3
  import gradio as gr
4
  import os
5
+ import logging
 
6
  import bcrypt
7
  import base64
8
+ from azure.cosmos import CosmosClient
9
+ from azure.cosmos.exceptions import CosmosHttpResponseError
10
+ from datetime import datetime, timezone
11
+
12
  from ..database.sql_db import (
13
  get_user,
14
  get_student_user,
 
15
  create_student_user,
16
  update_student_user,
17
  delete_student_user,
18
  record_login,
19
+ record_logout,
20
  )
21
 
22
+ logger = logging.getLogger(__name__)
23
 
24
+ # Verificar las variables de entorno necesarias
25
+ COSMOS_ENDPOINT = os.getenv("COSMOS_ENDPOINT")
26
+ COSMOS_KEY = os.getenv("COSMOS_KEY")
27
 
28
+ if not COSMOS_ENDPOINT or not COSMOS_KEY:
29
+ raise ValueError("Las variables de entorno COSMOS_ENDPOINT y COSMOS_KEY no est谩n configuradas.")
30
 
31
+ # Validar y limpiar la clave de Cosmos DB
32
  def clean_and_validate_key(key):
 
33
  key = key.strip()
34
  while len(key) % 4 != 0:
35
+ key += "="
36
  try:
37
  base64.b64decode(key)
38
  return key
39
+ except Exception:
40
+ raise ValueError("La clave proporcionada no es v谩lida.")
41
+
42
+ COSMOS_KEY = clean_and_validate_key(COSMOS_KEY)
43
+ cosmos_client = CosmosClient(COSMOS_ENDPOINT, COSMOS_KEY)
44
+
45
+ ########################################
46
+ # 脥NDICE DE FUNCIONES (Referencia consolidada)
47
+ ########################################
48
+ # Autenticaci贸n
49
+ # - authenticate_user
50
+ # - authenticate_student
51
+ # - authenticate_admin
52
+
53
+ # Manejo de contrase帽as
54
+ # - hash_password
55
+ # - verify_password
56
+
57
+ # Manejo de usuarios
58
+ # - register_student
59
+ # - update_student_info
60
+ # - delete_student
61
+
62
+ # Interfaz de Gradio
63
+ # - create_auth_interface
64
+ # - create_user_page
65
+
66
+ ########################################
67
+ # Funciones de Autenticaci贸n
68
+ ########################################
69
+
70
+ def authenticate_user(username: str, password: str) -> tuple[bool, str | None]:
71
+ """
72
+ Autentica un usuario utilizando la base de datos.
73
+ """
74
+ try:
75
+ user = get_user(username)
76
+ if user and verify_password(user["password"], password):
77
+ logger.info(f"Usuario autenticado: {username}, Rol: {user['role']}")
78
+ return True, user["role"]
79
+ logger.warning(f"Credenciales incorrectas para el usuario: {username}")
80
+ return False, None
81
+ except Exception as e:
82
+ logger.error(f"Error autenticando al usuario {username}: {str(e)}")
83
+ return False, None
84
+
85
+ def authenticate_student(username, password):
86
+ """Autentica a un estudiante."""
87
+ success, role = authenticate_user(username, password)
88
+ return (success, role) if role == "Estudiante" else (False, None)
89
+
90
+ def authenticate_admin(username, password):
91
+ """Autentica a un administrador."""
92
+ success, role = authenticate_user(username, password)
93
+ return (success, role) if role == "Administrador" else (False, None)
94
+
95
+ ########################################
96
+ # Registro y Manejo de Usuarios
97
+ ########################################
98
+
99
+ def register_student(username: str, password: str, additional_info=None) -> bool:
100
+ """
101
+ Registra un nuevo estudiante.
102
+ """
103
+ try:
104
+ if get_student_user(username):
105
+ logger.warning(f"El estudiante {username} ya existe.")
106
+ return False
107
+
108
+ hashed_password = hash_password(password)
109
+ additional_info = additional_info or {}
110
+ additional_info["role"] = "Estudiante"
111
+
112
+ create_student_user(username, hashed_password, additional_info)
113
+ logger.info(f"Estudiante registrado: {username}")
114
+ return True
115
+ except Exception as e:
116
+ logger.error(f"Error registrando al estudiante {username}: {str(e)}")
117
+ return False
118
 
119
+ def update_student_info(username: str, new_info: dict) -> bool:
120
+ """
121
+ Actualiza la informaci贸n de un estudiante.
122
+ """
123
+ try:
124
+ if "password" in new_info:
125
+ new_info["password"] = hash_password(new_info["password"])
126
+ return update_student_user(username, new_info)
127
+ except Exception as e:
128
+ logger.error(f"Error actualizando informaci贸n del estudiante {username}: {str(e)}")
129
+ return False
130
+
131
+ def delete_student(username: str) -> bool:
132
+ """
133
+ Elimina un estudiante de la base de datos.
134
+ """
135
+ try:
136
+ return delete_student_user(username)
137
+ except Exception as e:
138
+ logger.error(f"Error al eliminar estudiante {username}: {str(e)}")
139
+ return False
140
 
141
+ ########################################
142
+ # Manejo de Contrase帽as
143
+ ########################################
144
 
145
+ def hash_password(password: str) -> str:
146
+ """Hashea una contrase帽a utilizando bcrypt."""
147
+ return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
148
 
149
+ def verify_password(stored_password: str, provided_password: str) -> bool:
150
+ """Verifica que una contrase帽a coincida con su hash."""
151
+ return bcrypt.checkpw(provided_password.encode("utf-8"), stored_password.encode("utf-8"))
152
 
153
+ ########################################
154
+ # Interfaz Gradio para Login
155
+ ########################################
156
 
 
157
  def create_auth_interface():
158
+ """
159
+ Crea la interfaz de autenticaci贸n.
160
+ """
161
  with gr.Blocks() as auth_interface:
162
  gr.Markdown("# Login")
163
  username = gr.Textbox(label="Usuario")
 
172
  login_btn.click(fn=handle_login, inputs=[username, password], outputs=message)
173
  return auth_interface
174
 
175
+ ########################################
176
+ # P谩gina de Usuario
177
+ ########################################
 
 
 
 
178
 
179
+ def create_user_page():
180
+ """
181
+ Crea una p谩gina de usuario simple tras el inicio de sesi贸n.
182
+ """
183
+ with gr.Blocks() as user_page:
184
+ gr.Markdown("# Bienvenido a la P谩gina de Usuario")
185
+ gr.Markdown("Esta p谩gina est谩 disponible despu茅s de un inicio de sesi贸n exitoso.")
186
 
187
+ username = gr.Textbox(label="Usuario", interactive=False)
188
+ role = gr.Textbox(label="Rol", interactive=False)
 
 
 
 
189
 
190
+ def load_user_info():
191
+ return "UsuarioPrueba", "Estudiante" # Simula datos de sesi贸n
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
+ user_page.load(fn=load_user_info, inputs=[], outputs=[username, role])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
+ gr.Button("Cerrar Sesi贸n").click(
196
+ fn=lambda: "Sesi贸n cerrada",
197
+ inputs=[],
198
+ outputs=[user_page]
199
+ )
200
+ return user_page
 
 
 
 
 
 
 
 
201
 
202
+ ########################################
203
+ # Exportar Funciones
204
+ ########################################
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
  __all__ = [
207
+ "create_auth_interface",
208
+ "create_user_page",
209
+ "register_student",
210
+ "authenticate_user",
211
+ "authenticate_student",
212
+ "authenticate_admin",
213
+ "update_student_info",
214
+ "delete_student",
215
+ "hash_password",
216
+ "verify_password",
217
  ]