Update modules/auth/auth.py
Browse files- modules/auth/auth.py +70 -58
modules/auth/auth.py
CHANGED
@@ -4,6 +4,16 @@ from azure.cosmos import CosmosClient, exceptions
|
|
4 |
from azure.cosmos.exceptions import CosmosHttpResponseError
|
5 |
import bcrypt
|
6 |
import base64
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
import logging
|
8 |
from datetime import datetime, timezone
|
9 |
|
@@ -34,140 +44,142 @@ def authenticate_user(username, password):
|
|
34 |
Autentica un usuario y registra el inicio de sesión
|
35 |
"""
|
36 |
try:
|
|
|
37 |
user_item = get_user(username)
|
38 |
-
|
39 |
-
|
|
|
|
|
40 |
|
41 |
-
|
42 |
-
|
43 |
-
if session_id:
|
44 |
-
st.session_state.session_id = session_id
|
45 |
-
st.session_state.login_time = datetime.now(timezone.utc).isoformat()
|
46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
return True, user_item['role']
|
48 |
|
49 |
-
logger.warning(f"
|
50 |
return False, None
|
|
|
51 |
except Exception as e:
|
52 |
logger.error(f"Error durante la autenticación del usuario: {str(e)}")
|
53 |
return False, None
|
54 |
|
55 |
-
def authenticate_admin(username, password):
|
56 |
-
"""Autentica un administrador"""
|
57 |
-
return authenticate_user(username, password)
|
58 |
-
|
59 |
def authenticate_student(username, password):
|
60 |
"""Autentica un estudiante"""
|
61 |
-
|
|
|
|
|
|
|
62 |
|
63 |
-
def
|
64 |
-
"""Autentica un
|
65 |
-
|
|
|
|
|
|
|
66 |
|
67 |
def register_student(username, password, additional_info=None):
|
68 |
-
"""
|
69 |
-
Registra un nuevo estudiante
|
70 |
-
"""
|
71 |
try:
|
72 |
if get_student_user(username):
|
73 |
-
logger.warning(f"
|
74 |
return False
|
75 |
|
76 |
-
# Hash de la contraseña antes de almacenar
|
77 |
hashed_password = hash_password(password)
|
78 |
-
success = create_student_user(username, hashed_password, additional_info)
|
79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
if success:
|
81 |
logger.info(f"Nuevo estudiante registrado: {username}")
|
82 |
return True
|
83 |
-
|
84 |
-
|
85 |
-
|
|
|
86 |
except Exception as e:
|
87 |
logger.error(f"Error al registrar estudiante: {str(e)}")
|
88 |
return False
|
89 |
|
90 |
def update_student_info(username, new_info):
|
91 |
-
"""
|
92 |
-
Actualiza la información de un estudiante
|
93 |
-
"""
|
94 |
try:
|
95 |
-
# Si hay contraseña en new_info, hashearla
|
96 |
if 'password' in new_info:
|
97 |
new_info['password'] = hash_password(new_info['password'])
|
98 |
|
99 |
success = update_student_user(username, new_info)
|
100 |
if success:
|
101 |
-
logger.info(f"Información
|
102 |
return True
|
103 |
-
|
104 |
-
|
105 |
-
|
|
|
106 |
except Exception as e:
|
107 |
-
logger.error(f"Error
|
108 |
return False
|
109 |
|
110 |
def delete_student(username):
|
111 |
-
"""
|
112 |
-
Elimina un estudiante
|
113 |
-
"""
|
114 |
try:
|
115 |
success = delete_student_user(username)
|
116 |
if success:
|
117 |
logger.info(f"Estudiante eliminado: {username}")
|
118 |
return True
|
119 |
-
|
120 |
-
|
121 |
-
|
|
|
122 |
except Exception as e:
|
123 |
-
logger.error(f"Error
|
124 |
return False
|
125 |
|
126 |
def logout():
|
127 |
-
"""
|
128 |
-
Cierra la sesión del usuario y registra el tiempo
|
129 |
-
"""
|
130 |
try:
|
131 |
if 'session_id' in st.session_state and 'username' in st.session_state:
|
132 |
-
# Registrar el cierre de sesión
|
133 |
record_logout(
|
134 |
st.session_state.username,
|
135 |
st.session_state.session_id
|
136 |
)
|
137 |
-
logger.info(f"Sesión cerrada
|
138 |
-
|
139 |
-
# Limpiar el estado de la sesión
|
140 |
st.session_state.clear()
|
141 |
|
142 |
except Exception as e:
|
143 |
-
logger.error(f"Error
|
144 |
-
# Asegurar que la sesión se limpie incluso si hay error
|
145 |
st.session_state.clear()
|
146 |
|
147 |
def hash_password(password):
|
148 |
-
"""
|
149 |
-
Hashea una contraseña para almacenamiento
|
150 |
-
"""
|
151 |
return bcrypt.hashpw(
|
152 |
password.encode('utf-8'),
|
153 |
bcrypt.gensalt()
|
154 |
).decode('utf-8')
|
155 |
|
156 |
def verify_password(stored_password, provided_password):
|
157 |
-
"""
|
158 |
-
Verifica una contraseña almacenada contra una proporcionada
|
159 |
-
"""
|
160 |
return bcrypt.checkpw(
|
161 |
provided_password.encode('utf-8'),
|
162 |
stored_password.encode('utf-8')
|
163 |
)
|
164 |
|
165 |
-
# Asegurarse de exportar todas las funciones necesarias
|
166 |
__all__ = [
|
167 |
'authenticate_user',
|
168 |
'authenticate_admin',
|
169 |
'authenticate_student',
|
170 |
-
'authenticate_teacher',
|
171 |
'register_student',
|
172 |
'update_student_info',
|
173 |
'delete_student',
|
|
|
4 |
from azure.cosmos.exceptions import CosmosHttpResponseError
|
5 |
import bcrypt
|
6 |
import base64
|
7 |
+
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 |
|
|
|
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',
|