Update modules/auth/auth.py
Browse files- modules/auth/auth.py +189 -119
modules/auth/auth.py
CHANGED
@@ -1,119 +1,189 @@
|
|
1 |
-
import os
|
2 |
-
|
3 |
-
from azure.cosmos
|
4 |
-
import
|
5 |
-
import
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
create_student_user,
|
12 |
-
update_student_user,
|
13 |
-
delete_student_user
|
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 |
-
def authenticate_user(username, password):
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
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 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
def
|
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 |
+
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 += '='
|
27 |
+
try:
|
28 |
+
base64.b64decode(key)
|
29 |
+
return key
|
30 |
+
except:
|
31 |
+
raise ValueError("La clave proporcionada no es v谩lida")
|
32 |
+
|
33 |
+
# Verificar las variables de entorno
|
34 |
+
endpoint = os.getenv("COSMOS_ENDPOINT")
|
35 |
+
key = os.getenv("COSMOS_KEY")
|
36 |
+
|
37 |
+
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 |
+
]
|