AIdeaText commited on
Commit
1e34f1d
verified
1 Parent(s): b565515

Update modules/auth/auth.py

Browse files
Files changed (1) hide show
  1. modules/auth/auth.py +7 -192
modules/auth/auth.py CHANGED
@@ -1,217 +1,32 @@
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")
164
- password = gr.Textbox(label="Contrase帽a", type="password")
165
- login_btn = gr.Button("Iniciar Sesi贸n")
166
- message = gr.Markdown()
167
-
168
- def handle_login(user, pwd):
169
- success, role = authenticate_user(user, pwd)
170
- return f"Bienvenido, {user} ({role})" if success else "Credenciales incorrectas."
171
-
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
- ]
 
1
  # modules/auth/auth.py
2
 
 
3
  import os
4
  import logging
5
  import bcrypt
 
6
  from azure.cosmos import CosmosClient
7
+ from modules.database.sql_db import get_user
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  logger = logging.getLogger(__name__)
10
 
11
+ # Verificar las variables de entorno
12
  COSMOS_ENDPOINT = os.getenv("COSMOS_ENDPOINT")
13
  COSMOS_KEY = os.getenv("COSMOS_KEY")
 
14
  if not COSMOS_ENDPOINT or not COSMOS_KEY:
15
  raise ValueError("Las variables de entorno COSMOS_ENDPOINT y COSMOS_KEY no est谩n configuradas.")
16
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  cosmos_client = CosmosClient(COSMOS_ENDPOINT, COSMOS_KEY)
18
 
19
+ def authenticate_user(username: str, password: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  """
21
  Autentica un usuario utilizando la base de datos.
22
  """
23
  try:
24
  user = get_user(username)
25
+ if user and bcrypt.checkpw(password.encode("utf-8"), user["password"].encode("utf-8")):
26
+ logger.info(f"Usuario autenticado: {username}")
27
  return True, user["role"]
28
+ logger.warning(f"Credenciales incorrectas para: {username}")
29
  return False, None
30
  except Exception as e:
31
+ logger.error(f"Error autenticando a {username}: {e}")
32
  return False, None