Update modules/auth/auth.py
Browse files- modules/auth/auth.py +177 -119
modules/auth/auth.py
CHANGED
@@ -1,119 +1,177 @@
|
|
1 |
-
import os
|
2 |
-
|
3 |
-
from azure.cosmos
|
4 |
-
import
|
5 |
-
import
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
)
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
return True, user_item['role']
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
return authenticate_user(username, password)
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
logger.
|
102 |
-
return
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
def
|
111 |
-
"""
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
6 |
+
import base64
|
7 |
+
import logging
|
8 |
+
from datetime import datetime, timezone
|
9 |
+
|
10 |
+
logger = logging.getLogger(__name__)
|
11 |
+
|
12 |
+
def clean_and_validate_key(key):
|
13 |
+
"""Limpia y valida la clave de CosmosDB"""
|
14 |
+
key = key.strip()
|
15 |
+
while len(key) % 4 != 0:
|
16 |
+
key += '='
|
17 |
+
try:
|
18 |
+
base64.b64decode(key)
|
19 |
+
return key
|
20 |
+
except:
|
21 |
+
raise ValueError("La clave proporcionada no es v谩lida")
|
22 |
+
|
23 |
+
# Verificar las variables de entorno
|
24 |
+
endpoint = os.getenv("COSMOS_ENDPOINT")
|
25 |
+
key = os.getenv("COSMOS_KEY")
|
26 |
+
|
27 |
+
if not endpoint or not key:
|
28 |
+
raise ValueError("Las variables de entorno COSMOS_ENDPOINT y COSMOS_KEY deben estar configuradas")
|
29 |
+
|
30 |
+
key = clean_and_validate_key(key)
|
31 |
+
|
32 |
+
def authenticate_user(username, password):
|
33 |
+
"""
|
34 |
+
Autentica un usuario y registra el inicio de sesi贸n
|
35 |
+
"""
|
36 |
+
try:
|
37 |
+
user_item = get_user(username)
|
38 |
+
if user_item and verify_password(user_item['password'], password):
|
39 |
+
logger.info(f"Usuario autenticado: {username}, Rol: {user_item['role']}")
|
40 |
+
|
41 |
+
# Registrar inicio de sesi贸n
|
42 |
+
session_id = record_login(username)
|
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"Autenticaci贸n fallida para el usuario: {username}")
|
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 |
+
return authenticate_user(username, password)
|
62 |
+
|
63 |
+
def authenticate_teacher(username, password):
|
64 |
+
"""Autentica un profesor"""
|
65 |
+
return authenticate_user(username, password)
|
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"Intento de registro de estudiante existente: {username}")
|
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 |
+
else:
|
84 |
+
logger.error(f"Error al registrar nuevo estudiante: {username}")
|
85 |
+
return False
|
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 del estudiante actualizada: {username}")
|
102 |
+
return True
|
103 |
+
else:
|
104 |
+
logger.error(f"Error al actualizar informaci贸n del estudiante: {username}")
|
105 |
+
return False
|
106 |
+
except Exception as e:
|
107 |
+
logger.error(f"Error al actualizar informaci贸n del estudiante: {str(e)}")
|
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 |
+
else:
|
120 |
+
logger.error(f"Error al eliminar estudiante: {username}")
|
121 |
+
return False
|
122 |
+
except Exception as e:
|
123 |
+
logger.error(f"Error al eliminar estudiante: {str(e)}")
|
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 para el usuario: {st.session_state.username}")
|
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 durante el logout: {str(e)}")
|
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',
|
174 |
+
'logout',
|
175 |
+
'hash_password',
|
176 |
+
'verify_password'
|
177 |
+
]
|