Spaces:
Running
Running
Update modules/database/sql_db.py
Browse files- modules/database/sql_db.py +26 -134
modules/database/sql_db.py
CHANGED
|
@@ -13,13 +13,11 @@ logger = logging.getLogger(__name__)
|
|
| 13 |
def get_user(username, role=None):
|
| 14 |
container = get_container("users")
|
| 15 |
try:
|
| 16 |
-
# Para una b煤squeda por id (que es el partition key), no necesitamos cross partition query
|
| 17 |
-
query = f"SELECT * FROM c WHERE c.id = '{username}'"
|
| 18 |
if role:
|
| 19 |
query += f" AND c.role = '{role}'"
|
| 20 |
items = list(container.query_items(
|
| 21 |
-
query=query
|
| 22 |
-
|
| 23 |
))
|
| 24 |
return items[0] if items else None
|
| 25 |
except Exception as e:
|
|
@@ -32,14 +30,14 @@ def get_user(username, role=None):
|
|
| 32 |
def get_admin_user(username):
|
| 33 |
return get_user(username, role='Administrador')
|
| 34 |
|
| 35 |
-
def get_student_user(username):
|
| 36 |
-
return get_user(username, role='Estudiante')
|
| 37 |
-
|
| 38 |
def get_teacher_user(username):
|
| 39 |
return get_user(username, role='Profesor')
|
| 40 |
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
def create_user(username, password, role, additional_info=None):
|
| 44 |
"""Crea un nuevo usuario"""
|
| 45 |
container = get_container("users")
|
|
@@ -48,95 +46,71 @@ def create_user(username, password, role, additional_info=None):
|
|
| 48 |
return False
|
| 49 |
|
| 50 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
user_data = {
|
| 52 |
-
'id': username,
|
| 53 |
'password': password,
|
|
|
|
| 54 |
'role': role,
|
| 55 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 56 |
'additional_info': additional_info or {}
|
|
|
|
|
|
|
| 57 |
}
|
| 58 |
|
| 59 |
container.create_item(
|
| 60 |
body=user_data,
|
| 61 |
-
partition_key=username
|
| 62 |
)
|
| 63 |
logger.info(f"Usuario {role} creado: {username}")
|
| 64 |
return True
|
| 65 |
|
| 66 |
-
except Exception as e:
|
| 67 |
logger.error(f"Error al crear usuario {role}: {str(e)}")
|
| 68 |
return False
|
| 69 |
|
| 70 |
-
|
| 71 |
def create_student_user(username, password, additional_info=None):
|
| 72 |
return create_user(username, password, 'Estudiante', additional_info)
|
| 73 |
|
| 74 |
-
def create_teacher_user(username, password, additional_info=None):
|
| 75 |
-
return create_user(username, password, 'Profesor', additional_info)
|
| 76 |
-
|
| 77 |
-
def create_admin_user(username, password, additional_info=None):
|
| 78 |
-
return create_user(username, password, 'Administrador', additional_info)
|
| 79 |
-
|
| 80 |
-
############-- Funciones de control del tiempo de sesi贸n ##################
|
| 81 |
-
|
| 82 |
-
###########################################################
|
| 83 |
-
|
| 84 |
-
def record_login(username):
|
| 85 |
-
"""Registra el inicio de sesi贸n de un usuario"""
|
| 86 |
-
try:
|
| 87 |
-
container = get_container("users_sessions")
|
| 88 |
-
if not container:
|
| 89 |
-
logger.error("No se pudo obtener el contenedor users_sessions")
|
| 90 |
-
return None
|
| 91 |
-
|
| 92 |
-
session_id = str(uuid.uuid4())
|
| 93 |
-
session_doc = {
|
| 94 |
-
"id": session_id,
|
| 95 |
-
"type": "session",
|
| 96 |
"username": username,
|
| 97 |
"loginTime": datetime.now(timezone.utc).isoformat(),
|
| 98 |
"additional_info": {},
|
|
|
|
| 99 |
"partitionKey": username
|
| 100 |
}
|
| 101 |
|
|
|
|
| 102 |
result = container.create_item(
|
| 103 |
body=session_doc # Solo el body
|
|
|
|
| 104 |
)
|
| 105 |
logger.info(f"Sesi贸n {session_id} registrada para {username}")
|
| 106 |
return session_id
|
| 107 |
-
except Exception as e:
|
| 108 |
logger.error(f"Error registrando login: {str(e)}")
|
| 109 |
return None
|
| 110 |
|
|
|
|
| 111 |
###########################################################
|
| 112 |
|
| 113 |
def record_logout(username, session_id):
|
| 114 |
-
"""Registra el cierre de sesi贸n y calcula la duraci贸n"""
|
| 115 |
-
try:
|
| 116 |
-
container = get_container("users_sessions")
|
| 117 |
-
if not container:
|
| 118 |
logger.error("No se pudo obtener el contenedor users_sessions")
|
| 119 |
return False
|
| 120 |
|
|
|
|
| 121 |
query = "SELECT * FROM c WHERE c.id = @id AND c.username = @username"
|
| 122 |
params = [
|
| 123 |
{"name": "@id", "value": session_id},
|
| 124 |
-
{"name": "@username", "value": username}
|
| 125 |
-
]
|
| 126 |
|
| 127 |
items = list(container.query_items(
|
| 128 |
query=query,
|
| 129 |
parameters=params # Removido enable_cross_partition_query
|
|
|
|
| 130 |
))
|
| 131 |
|
| 132 |
if not items:
|
| 133 |
-
logger.warning(f"Sesi贸n no encontrada: {session_id}")
|
| 134 |
-
return False
|
| 135 |
-
|
| 136 |
-
session = items[0]
|
| 137 |
-
login_time = datetime.fromisoformat(session['loginTime'].rstrip('Z'))
|
| 138 |
-
logout_time = datetime.now(timezone.utc)
|
| 139 |
-
duration = int((logout_time - login_time).total_seconds())
|
| 140 |
|
| 141 |
session.update({
|
| 142 |
"logoutTime": logout_time.isoformat(),
|
|
@@ -144,101 +118,31 @@ def record_logout(username, session_id):
|
|
| 144 |
"partitionKey": username # Asegurar que partitionKey est茅 presente
|
| 145 |
})
|
| 146 |
|
|
|
|
| 147 |
container.upsert_item(
|
| 148 |
body=session # Solo el body
|
| 149 |
)
|
| 150 |
logger.info(f"Sesi贸n {session_id} cerrada para {username}, duraci贸n: {duration}s")
|
| 151 |
return True
|
| 152 |
-
except Exception as e:
|
| 153 |
-
logger.error(f"Error registrando logout: {str(e)}")
|
| 154 |
-
return False
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
###########################################################
|
| 158 |
-
|
| 159 |
-
def get_recent_sessions(limit=10):
|
| 160 |
-
"""Obtiene las sesiones m谩s recientes"""
|
| 161 |
-
try:
|
| 162 |
-
container = get_container("users_sessions")
|
| 163 |
-
if not container:
|
| 164 |
-
logger.error("No se pudo obtener el contenedor users_sessions")
|
| 165 |
-
return []
|
| 166 |
-
|
| 167 |
-
query = """
|
| 168 |
-
SELECT c.username, c.loginTime, c.logoutTime, c.sessionDuration
|
| 169 |
-
FROM c
|
| 170 |
-
WHERE c.type = 'session'
|
| 171 |
-
ORDER BY c.loginTime DESC
|
| 172 |
-
OFFSET 0 LIMIT @limit
|
| 173 |
-
"""
|
| 174 |
|
| 175 |
sessions = list(container.query_items(
|
| 176 |
query=query,
|
| 177 |
parameters=[{"name": "@limit", "value": limit}] # Removido enable_cross_partition_query
|
|
|
|
| 178 |
))
|
| 179 |
|
|
|
|
| 180 |
clean_sessions = []
|
| 181 |
for session in sessions:
|
| 182 |
try:
|
| 183 |
-
clean_sessions.append({
|
| 184 |
-
"username": session["username"],
|
| 185 |
-
"loginTime": session["loginTime"],
|
| 186 |
-
"logoutTime": session.get("logoutTime", "Activo"),
|
| 187 |
-
"sessionDuration": session.get("sessionDuration", 0)
|
| 188 |
-
})
|
| 189 |
-
except KeyError as e:
|
| 190 |
-
logger.warning(f"Sesi贸n con datos incompletos: {e}")
|
| 191 |
-
continue
|
| 192 |
-
|
| 193 |
-
return clean_sessions
|
| 194 |
-
except Exception as e:
|
| 195 |
-
logger.error(f"Error obteniendo sesiones recientes: {str(e)}")
|
| 196 |
-
return []
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
###########################################################
|
| 201 |
-
|
| 202 |
-
def get_user_total_time(username):
|
| 203 |
-
"""Obtiene el tiempo total que un usuario ha pasado en la plataforma"""
|
| 204 |
-
try:
|
| 205 |
-
container = get_container("users_sessions")
|
| 206 |
-
if not container:
|
| 207 |
-
return None
|
| 208 |
-
|
| 209 |
-
query = """
|
| 210 |
-
SELECT VALUE SUM(c.sessionDuration)
|
| 211 |
-
FROM c
|
| 212 |
-
WHERE c.type = 'session'
|
| 213 |
-
AND c.username = @username
|
| 214 |
-
AND IS_DEFINED(c.sessionDuration)
|
| 215 |
-
"""
|
| 216 |
|
| 217 |
result = list(container.query_items(
|
| 218 |
query=query,
|
| 219 |
parameters=[{"name": "@username", "value": username}] # Removido enable_cross_partition_query
|
|
|
|
| 220 |
))
|
| 221 |
|
| 222 |
return result[0] if result and result[0] is not None else 0
|
| 223 |
-
except Exception as e:
|
| 224 |
-
logger.error(f"Error obteniendo tiempo total: {str(e)}")
|
| 225 |
-
return 0
|
| 226 |
-
|
| 227 |
-
###########################################################
|
| 228 |
-
def update_student_user(username, new_info):
|
| 229 |
-
user_container, _, _ = get_sql_containers()
|
| 230 |
-
try:
|
| 231 |
-
user = get_student_user(username)
|
| 232 |
-
if user:
|
| 233 |
-
user['additional_info'].update(new_info)
|
| 234 |
-
user_container.upsert_item(body=user)
|
| 235 |
-
logger.info(f"Informaci贸n del estudiante actualizada: {username}")
|
| 236 |
-
return True
|
| 237 |
-
else:
|
| 238 |
-
logger.warning(f"Intento de actualizar estudiante no existente: {username}")
|
| 239 |
-
return False
|
| 240 |
-
except Exception as e:
|
| 241 |
-
logger.error(f"Error al actualizar informaci贸n del estudiante {username}: {str(e)}")
|
| 242 |
return False
|
| 243 |
|
| 244 |
|
|
@@ -246,15 +150,6 @@ def update_student_user(username, new_info):
|
|
| 246 |
def delete_student_user(username):
|
| 247 |
user_container, _, _ = get_sql_containers()
|
| 248 |
try:
|
| 249 |
-
user = get_student_user(username)
|
| 250 |
-
if user:
|
| 251 |
-
user_container.delete_item(item=user['id'], partition_key=username)
|
| 252 |
-
logger.info(f"Estudiante eliminado: {username}")
|
| 253 |
-
return True
|
| 254 |
-
else:
|
| 255 |
-
logger.warning(f"Intento de eliminar estudiante no existente: {username}")
|
| 256 |
-
return False
|
| 257 |
-
except Exception as e:
|
| 258 |
logger.error(f"Error al eliminar estudiante {username}: {str(e)}")
|
| 259 |
return False
|
| 260 |
|
|
@@ -276,9 +171,6 @@ def store_application_request(name, lastname, email, institution, current_role,
|
|
| 276 |
application_request = {
|
| 277 |
"id": str(uuid.uuid4()),
|
| 278 |
"name": name,
|
| 279 |
-
"lastname": lastname,
|
| 280 |
-
"email": email,
|
| 281 |
-
"institution": institution,
|
| 282 |
"current_role": current_role,
|
| 283 |
"desired_role": desired_role,
|
| 284 |
"reason": reason,
|
|
|
|
| 13 |
def get_user(username, role=None):
|
| 14 |
container = get_container("users")
|
| 15 |
try:
|
|
|
|
|
|
|
| 16 |
if role:
|
| 17 |
query += f" AND c.role = '{role}'"
|
| 18 |
items = list(container.query_items(
|
| 19 |
+
query=query # Removido enable_cross_partition_query
|
| 20 |
+
|
| 21 |
))
|
| 22 |
return items[0] if items else None
|
| 23 |
except Exception as e:
|
|
|
|
| 30 |
def get_admin_user(username):
|
| 31 |
return get_user(username, role='Administrador')
|
| 32 |
|
|
|
|
|
|
|
|
|
|
| 33 |
def get_teacher_user(username):
|
| 34 |
return get_user(username, role='Profesor')
|
| 35 |
|
| 36 |
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
def create_user(username, password, role, additional_info=None):
|
| 42 |
"""Crea un nuevo usuario"""
|
| 43 |
container = get_container("users")
|
|
|
|
| 46 |
return False
|
| 47 |
|
| 48 |
try:
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
user_data = {
|
| 54 |
+
'id': username,
|
| 55 |
'password': password,
|
| 56 |
+
|
| 57 |
'role': role,
|
| 58 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 59 |
'additional_info': additional_info or {}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
}
|
| 63 |
|
| 64 |
container.create_item(
|
| 65 |
body=user_data,
|
| 66 |
+
partition_key=username
|
| 67 |
)
|
| 68 |
logger.info(f"Usuario {role} creado: {username}")
|
| 69 |
return True
|
| 70 |
|
|
|
|
| 71 |
logger.error(f"Error al crear usuario {role}: {str(e)}")
|
| 72 |
return False
|
| 73 |
|
| 74 |
+
|
| 75 |
def create_student_user(username, password, additional_info=None):
|
| 76 |
return create_user(username, password, 'Estudiante', additional_info)
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
"username": username,
|
| 79 |
"loginTime": datetime.now(timezone.utc).isoformat(),
|
| 80 |
"additional_info": {},
|
| 81 |
+
|
| 82 |
"partitionKey": username
|
| 83 |
}
|
| 84 |
|
| 85 |
+
|
| 86 |
result = container.create_item(
|
| 87 |
body=session_doc # Solo el body
|
| 88 |
+
|
| 89 |
)
|
| 90 |
logger.info(f"Sesi贸n {session_id} registrada para {username}")
|
| 91 |
return session_id
|
|
|
|
| 92 |
logger.error(f"Error registrando login: {str(e)}")
|
| 93 |
return None
|
| 94 |
|
| 95 |
+
|
| 96 |
###########################################################
|
| 97 |
|
| 98 |
def record_logout(username, session_id):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
logger.error("No se pudo obtener el contenedor users_sessions")
|
| 100 |
return False
|
| 101 |
|
| 102 |
+
|
| 103 |
query = "SELECT * FROM c WHERE c.id = @id AND c.username = @username"
|
| 104 |
params = [
|
| 105 |
{"name": "@id", "value": session_id},
|
|
|
|
|
|
|
| 106 |
|
| 107 |
items = list(container.query_items(
|
| 108 |
query=query,
|
| 109 |
parameters=params # Removido enable_cross_partition_query
|
| 110 |
+
|
| 111 |
))
|
| 112 |
|
| 113 |
if not items:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
session.update({
|
| 116 |
"logoutTime": logout_time.isoformat(),
|
|
|
|
| 118 |
"partitionKey": username # Asegurar que partitionKey est茅 presente
|
| 119 |
})
|
| 120 |
|
| 121 |
+
|
| 122 |
container.upsert_item(
|
| 123 |
body=session # Solo el body
|
| 124 |
)
|
| 125 |
logger.info(f"Sesi贸n {session_id} cerrada para {username}, duraci贸n: {duration}s")
|
| 126 |
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
sessions = list(container.query_items(
|
| 129 |
query=query,
|
| 130 |
parameters=[{"name": "@limit", "value": limit}] # Removido enable_cross_partition_query
|
| 131 |
+
|
| 132 |
))
|
| 133 |
|
| 134 |
+
|
| 135 |
clean_sessions = []
|
| 136 |
for session in sessions:
|
| 137 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
result = list(container.query_items(
|
| 140 |
query=query,
|
| 141 |
parameters=[{"name": "@username", "value": username}] # Removido enable_cross_partition_query
|
| 142 |
+
|
| 143 |
))
|
| 144 |
|
| 145 |
return result[0] if result and result[0] is not None else 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
return False
|
| 147 |
|
| 148 |
|
|
|
|
| 150 |
def delete_student_user(username):
|
| 151 |
user_container, _, _ = get_sql_containers()
|
| 152 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
logger.error(f"Error al eliminar estudiante {username}: {str(e)}")
|
| 154 |
return False
|
| 155 |
|
|
|
|
| 171 |
application_request = {
|
| 172 |
"id": str(uuid.uuid4()),
|
| 173 |
"name": name,
|
|
|
|
|
|
|
|
|
|
| 174 |
"current_role": current_role,
|
| 175 |
"desired_role": desired_role,
|
| 176 |
"reason": reason,
|