AIdeaText commited on
Commit
7846ae2
verified
1 Parent(s): f6412a2

Update modules/auth/auth.py

Browse files
Files changed (1) hide show
  1. modules/auth/auth.py +39 -109
modules/auth/auth.py CHANGED
@@ -1,5 +1,4 @@
1
  import os
2
- import streamlit as st
3
  from azure.cosmos import CosmosClient, exceptions
4
  from azure.cosmos.exceptions import CosmosHttpResponseError
5
  import bcrypt
@@ -8,19 +7,18 @@ from ..database.sql_db import (
8
  get_user,
9
  get_student_user,
10
  get_admin_user,
 
11
  create_student_user,
12
  update_student_user,
13
- delete_student_user,
14
- record_login,
15
- record_logout
16
  )
 
17
  import logging
18
- from datetime import datetime, timezone
19
 
20
  logger = logging.getLogger(__name__)
21
 
 
22
  def clean_and_validate_key(key):
23
- """Limpia y valida la clave de CosmosDB"""
24
  key = key.strip()
25
  while len(key) % 4 != 0:
26
  key += '='
@@ -38,152 +36,84 @@ if not endpoint or not key:
38
  raise ValueError("Las variables de entorno COSMOS_ENDPOINT y COSMOS_KEY deben estar configuradas")
39
 
40
  key = clean_and_validate_key(key)
 
 
41
 
42
  def authenticate_user(username, password):
43
- """
44
- Autentica un usuario y registra el inicio de sesi贸n
45
- """
46
  try:
47
- # Primero intentar obtener usuario general
48
  user_item = get_user(username)
49
-
50
- if not user_item:
51
- logger.warning(f"Usuario no encontrado: {username}")
52
- return False, None
53
-
54
- if verify_password(user_item['password'], password):
55
  logger.info(f"Usuario autenticado: {username}, Rol: {user_item['role']}")
56
-
57
- # Registrar la sesi贸n
58
- try:
59
- session_id = record_login(username)
60
- if session_id:
61
- st.session_state.session_id = session_id
62
- st.session_state.login_time = datetime.now(timezone.utc).isoformat()
63
- except Exception as e:
64
- logger.error(f"Error al registrar inicio de sesi贸n: {str(e)}")
65
- # Continuar aunque falle el registro de sesi贸n
66
-
67
  return True, user_item['role']
68
-
69
- logger.warning(f"Contrase帽a incorrecta para usuario: {username}")
70
  return False, None
71
-
72
  except Exception as e:
73
  logger.error(f"Error durante la autenticaci贸n del usuario: {str(e)}")
74
  return False, None
75
 
 
 
 
76
  def authenticate_student(username, password):
77
- """Autentica un estudiante"""
78
- success, role = authenticate_user(username, password)
79
- if success and role == 'Estudiante':
80
- return True, role
81
- return False, None
82
 
83
- def authenticate_admin(username, password):
84
- """Autentica un administrador"""
85
- success, role = authenticate_user(username, password)
86
- if success and role == 'Administrador':
87
- return True, role
88
- return False, None
89
 
 
90
  def register_student(username, password, additional_info=None):
91
- """Registra un nuevo estudiante"""
92
  try:
93
  if get_student_user(username):
94
- logger.warning(f"Estudiante ya existe: {username}")
95
- return False
96
 
97
- hashed_password = hash_password(password)
98
-
99
- # Asegurarse que additional_info tenga el rol correcto
100
- if not additional_info:
101
- additional_info = {}
102
- additional_info['role'] = 'Estudiante'
103
-
104
- success = create_student_user(username, hashed_password, additional_info)
105
  if success:
106
  logger.info(f"Nuevo estudiante registrado: {username}")
107
  return True
108
-
109
- logger.error(f"Error al crear estudiante: {username}")
110
- return False
111
-
112
  except Exception as e:
113
  logger.error(f"Error al registrar estudiante: {str(e)}")
114
  return False
115
 
116
  def update_student_info(username, new_info):
117
- """Actualiza la informaci贸n de un estudiante"""
118
  try:
119
- if 'password' in new_info:
120
- new_info['password'] = hash_password(new_info['password'])
121
-
122
  success = update_student_user(username, new_info)
123
  if success:
124
- logger.info(f"Informaci贸n actualizada: {username}")
125
  return True
126
-
127
- logger.error(f"Error al actualizar: {username}")
128
- return False
129
-
130
  except Exception as e:
131
- logger.error(f"Error en actualizaci贸n: {str(e)}")
132
  return False
133
 
134
  def delete_student(username):
135
- """Elimina un estudiante"""
136
  try:
137
  success = delete_student_user(username)
138
  if success:
139
  logger.info(f"Estudiante eliminado: {username}")
140
  return True
141
-
142
- logger.error(f"Error al eliminar: {username}")
143
- return False
144
-
145
  except Exception as e:
146
- logger.error(f"Error en eliminaci贸n: {str(e)}")
147
  return False
148
 
149
- def logout():
150
- """Cierra la sesi贸n del usuario"""
151
- try:
152
- if 'session_id' in st.session_state and 'username' in st.session_state:
153
- record_logout(
154
- st.session_state.username,
155
- st.session_state.session_id
156
- )
157
- logger.info(f"Sesi贸n cerrada: {st.session_state.username}")
158
-
159
- st.session_state.clear()
160
-
161
- except Exception as e:
162
- logger.error(f"Error en logout: {str(e)}")
163
- st.session_state.clear()
164
 
165
  def hash_password(password):
166
- """Hashea una contrase帽a"""
167
- return bcrypt.hashpw(
168
- password.encode('utf-8'),
169
- bcrypt.gensalt()
170
- ).decode('utf-8')
171
 
172
  def verify_password(stored_password, provided_password):
173
- """Verifica una contrase帽a"""
174
- return bcrypt.checkpw(
175
- provided_password.encode('utf-8'),
176
- stored_password.encode('utf-8')
177
- )
178
-
179
- __all__ = [
180
- 'authenticate_user',
181
- 'authenticate_admin',
182
- 'authenticate_student',
183
- 'register_student',
184
- 'update_student_info',
185
- 'delete_student',
186
- 'logout',
187
- 'hash_password',
188
- 'verify_password'
189
- ]
 
1
  import os
 
2
  from azure.cosmos import CosmosClient, exceptions
3
  from azure.cosmos.exceptions import CosmosHttpResponseError
4
  import bcrypt
 
7
  get_user,
8
  get_student_user,
9
  get_admin_user,
10
+ get_teacher_user,
11
  create_student_user,
12
  update_student_user,
13
+ delete_student_user
 
 
14
  )
15
+
16
  import logging
 
17
 
18
  logger = logging.getLogger(__name__)
19
 
20
+ # ... (c贸digo de inicializaci贸n)
21
  def clean_and_validate_key(key):
 
22
  key = key.strip()
23
  while len(key) % 4 != 0:
24
  key += '='
 
36
  raise ValueError("Las variables de entorno COSMOS_ENDPOINT y COSMOS_KEY deben estar configuradas")
37
 
38
  key = clean_and_validate_key(key)
39
+ ####################################################
40
+
41
 
42
  def authenticate_user(username, password):
 
 
 
43
  try:
 
44
  user_item = get_user(username)
45
+ if user_item and verify_password(user_item['password'], password):
 
 
 
 
 
46
  logger.info(f"Usuario autenticado: {username}, Rol: {user_item['role']}")
 
 
 
 
 
 
 
 
 
 
 
47
  return True, user_item['role']
48
+ logger.warning(f"Autenticaci贸n fallida para el usuario: {username}")
 
49
  return False, None
 
50
  except Exception as e:
51
  logger.error(f"Error durante la autenticaci贸n del usuario: {str(e)}")
52
  return False, None
53
 
54
+ def authenticate_admin(username, password):
55
+ return authenticate_user(username, password)
56
+
57
  def authenticate_student(username, password):
58
+ return authenticate_user(username, password)
 
 
 
 
59
 
60
+ def authenticate_teacher(username, password):
61
+ return authenticate_user(username, password)
 
 
 
 
62
 
63
+ ############################
64
  def register_student(username, password, additional_info=None):
 
65
  try:
66
  if get_student_user(username):
67
+ logger.warning(f"Intento de registro de estudiante existente: {username}")
68
+ return False # El estudiante ya existe
69
 
70
+ success = create_student_user(username, password, additional_info)
 
 
 
 
 
 
 
71
  if success:
72
  logger.info(f"Nuevo estudiante registrado: {username}")
73
  return True
74
+ else:
75
+ logger.error(f"Error al registrar nuevo estudiante: {username}")
76
+ return False
 
77
  except Exception as e:
78
  logger.error(f"Error al registrar estudiante: {str(e)}")
79
  return False
80
 
81
  def update_student_info(username, new_info):
 
82
  try:
 
 
 
83
  success = update_student_user(username, new_info)
84
  if success:
85
+ logger.info(f"Informaci贸n del estudiante actualizada: {username}")
86
  return True
87
+ else:
88
+ logger.error(f"Error al actualizar informaci贸n del estudiante: {username}")
89
+ return False
 
90
  except Exception as e:
91
+ logger.error(f"Error al actualizar informaci贸n del estudiante: {str(e)}")
92
  return False
93
 
94
  def delete_student(username):
 
95
  try:
96
  success = delete_student_user(username)
97
  if success:
98
  logger.info(f"Estudiante eliminado: {username}")
99
  return True
100
+ else:
101
+ logger.error(f"Error al eliminar estudiante: {username}")
102
+ return False
 
103
  except Exception as e:
104
+ logger.error(f"Error al eliminar estudiante: {str(e)}")
105
  return False
106
 
107
+
108
+ # ... (funciones de hash y verificaci贸n de contrase帽a)
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
  def hash_password(password):
111
+ """Hash a password for storing."""
112
+ return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
113
+
114
+ ##################################################################################33
 
115
 
116
  def verify_password(stored_password, provided_password):
117
+ """Verify a stored password against one provided by user"""
118
+ return bcrypt.checkpw(provided_password.encode('utf-8'), stored_password.encode('utf-8'))
119
+ #############################################################################