Spaces:
Running
Running
Update modules/database/sql_db.py
Browse files- modules/database/sql_db.py +54 -18
modules/database/sql_db.py
CHANGED
|
@@ -70,12 +70,14 @@ def create_admin_user(username, password, additional_info=None):
|
|
| 70 |
|
| 71 |
############-- Funciones de control del tiempo de sesi贸n ##################
|
| 72 |
|
|
|
|
| 73 |
|
| 74 |
def record_login(username):
|
| 75 |
-
"""Registra el inicio de sesi贸n"""
|
| 76 |
try:
|
| 77 |
container = get_container("users_sessions")
|
| 78 |
if not container:
|
|
|
|
| 79 |
return None
|
| 80 |
|
| 81 |
session_id = str(uuid.uuid4())
|
|
@@ -84,38 +86,48 @@ def record_login(username):
|
|
| 84 |
"type": "session",
|
| 85 |
"username": username,
|
| 86 |
"loginTime": datetime.now(timezone.utc).isoformat(),
|
| 87 |
-
"additional_info": {}
|
|
|
|
|
|
|
| 88 |
}
|
| 89 |
|
| 90 |
-
|
|
|
|
| 91 |
body=session_doc,
|
| 92 |
-
|
| 93 |
)
|
| 94 |
-
logger.info(f"
|
| 95 |
return session_id
|
| 96 |
except Exception as e:
|
| 97 |
logger.error(f"Error registrando login: {str(e)}")
|
| 98 |
return None
|
| 99 |
|
| 100 |
|
|
|
|
| 101 |
|
| 102 |
def record_logout(username, session_id):
|
| 103 |
-
"""Registra el cierre de sesi贸n"""
|
| 104 |
try:
|
| 105 |
container = get_container("users_sessions")
|
| 106 |
if not container:
|
|
|
|
| 107 |
return False
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
items = list(container.query_items(
|
| 113 |
query=query,
|
| 114 |
parameters=params,
|
| 115 |
-
|
| 116 |
))
|
| 117 |
|
| 118 |
if not items:
|
|
|
|
| 119 |
return False
|
| 120 |
|
| 121 |
session = items[0]
|
|
@@ -128,21 +140,25 @@ def record_logout(username, session_id):
|
|
| 128 |
"sessionDuration": duration
|
| 129 |
})
|
| 130 |
|
|
|
|
| 131 |
container.upsert_item(
|
| 132 |
-
body=session
|
| 133 |
-
partition_key=username
|
| 134 |
)
|
|
|
|
| 135 |
return True
|
| 136 |
except Exception as e:
|
| 137 |
logger.error(f"Error registrando logout: {str(e)}")
|
| 138 |
return False
|
| 139 |
|
| 140 |
|
|
|
|
|
|
|
| 141 |
def get_recent_sessions(limit=10):
|
| 142 |
-
"""Obtiene sesiones recientes"""
|
| 143 |
try:
|
| 144 |
container = get_container("users_sessions")
|
| 145 |
if not container:
|
|
|
|
| 146 |
return []
|
| 147 |
|
| 148 |
query = """
|
|
@@ -153,15 +169,35 @@ def get_recent_sessions(limit=10):
|
|
| 153 |
OFFSET 0 LIMIT @limit
|
| 154 |
"""
|
| 155 |
|
| 156 |
-
|
| 157 |
query=query,
|
| 158 |
parameters=[{"name": "@limit", "value": limit}],
|
| 159 |
enable_cross_partition_query=True
|
| 160 |
))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
except Exception as e:
|
| 162 |
-
logger.error(f"Error obteniendo sesiones: {str(e)}")
|
| 163 |
return []
|
| 164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
def get_user_total_time(username):
|
| 166 |
"""Obtiene el tiempo total que un usuario ha pasado en la plataforma"""
|
| 167 |
try:
|
|
@@ -174,19 +210,19 @@ def get_user_total_time(username):
|
|
| 174 |
FROM c
|
| 175 |
WHERE c.type = 'session'
|
| 176 |
AND c.username = @username
|
| 177 |
-
AND c.
|
| 178 |
"""
|
| 179 |
|
| 180 |
result = list(container.query_items(
|
| 181 |
query=query,
|
| 182 |
parameters=[{"name": "@username", "value": username}],
|
| 183 |
-
|
| 184 |
))
|
| 185 |
|
| 186 |
-
return result[0] if result else 0
|
| 187 |
except Exception as e:
|
| 188 |
logger.error(f"Error obteniendo tiempo total: {str(e)}")
|
| 189 |
-
return
|
| 190 |
|
| 191 |
###########################################################
|
| 192 |
def update_student_user(username, new_info):
|
|
|
|
| 70 |
|
| 71 |
############-- Funciones de control del tiempo de sesi贸n ##################
|
| 72 |
|
| 73 |
+
###########################################################
|
| 74 |
|
| 75 |
def record_login(username):
|
| 76 |
+
"""Registra el inicio de sesi贸n de un usuario"""
|
| 77 |
try:
|
| 78 |
container = get_container("users_sessions")
|
| 79 |
if not container:
|
| 80 |
+
logger.error("No se pudo obtener el contenedor users_sessions")
|
| 81 |
return None
|
| 82 |
|
| 83 |
session_id = str(uuid.uuid4())
|
|
|
|
| 86 |
"type": "session",
|
| 87 |
"username": username,
|
| 88 |
"loginTime": datetime.now(timezone.utc).isoformat(),
|
| 89 |
+
"additional_info": {},
|
| 90 |
+
# El campo para partition key debe estar en el documento
|
| 91 |
+
"partitionKey": username
|
| 92 |
}
|
| 93 |
|
| 94 |
+
# Crear el documento usando options
|
| 95 |
+
result = container.create_item(
|
| 96 |
body=session_doc,
|
| 97 |
+
enable_cross_partition_query=True
|
| 98 |
)
|
| 99 |
+
logger.info(f"Sesi贸n {session_id} registrada para {username}")
|
| 100 |
return session_id
|
| 101 |
except Exception as e:
|
| 102 |
logger.error(f"Error registrando login: {str(e)}")
|
| 103 |
return None
|
| 104 |
|
| 105 |
|
| 106 |
+
###########################################################
|
| 107 |
|
| 108 |
def record_logout(username, session_id):
|
| 109 |
+
"""Registra el cierre de sesi贸n y calcula la duraci贸n"""
|
| 110 |
try:
|
| 111 |
container = get_container("users_sessions")
|
| 112 |
if not container:
|
| 113 |
+
logger.error("No se pudo obtener el contenedor users_sessions")
|
| 114 |
return False
|
| 115 |
|
| 116 |
+
# Obtener la sesi贸n actual
|
| 117 |
+
query = "SELECT * FROM c WHERE c.id = @id AND c.username = @username"
|
| 118 |
+
params = [
|
| 119 |
+
{"name": "@id", "value": session_id},
|
| 120 |
+
{"name": "@username", "value": username}
|
| 121 |
+
]
|
| 122 |
|
| 123 |
items = list(container.query_items(
|
| 124 |
query=query,
|
| 125 |
parameters=params,
|
| 126 |
+
enable_cross_partition_query=True
|
| 127 |
))
|
| 128 |
|
| 129 |
if not items:
|
| 130 |
+
logger.warning(f"Sesi贸n no encontrada: {session_id}")
|
| 131 |
return False
|
| 132 |
|
| 133 |
session = items[0]
|
|
|
|
| 140 |
"sessionDuration": duration
|
| 141 |
})
|
| 142 |
|
| 143 |
+
# Actualizar el documento
|
| 144 |
container.upsert_item(
|
| 145 |
+
body=session
|
|
|
|
| 146 |
)
|
| 147 |
+
logger.info(f"Sesi贸n {session_id} cerrada para {username}, duraci贸n: {duration}s")
|
| 148 |
return True
|
| 149 |
except Exception as e:
|
| 150 |
logger.error(f"Error registrando logout: {str(e)}")
|
| 151 |
return False
|
| 152 |
|
| 153 |
|
| 154 |
+
###########################################################
|
| 155 |
+
|
| 156 |
def get_recent_sessions(limit=10):
|
| 157 |
+
"""Obtiene las sesiones m谩s recientes"""
|
| 158 |
try:
|
| 159 |
container = get_container("users_sessions")
|
| 160 |
if not container:
|
| 161 |
+
logger.error("No se pudo obtener el contenedor users_sessions")
|
| 162 |
return []
|
| 163 |
|
| 164 |
query = """
|
|
|
|
| 169 |
OFFSET 0 LIMIT @limit
|
| 170 |
"""
|
| 171 |
|
| 172 |
+
sessions = list(container.query_items(
|
| 173 |
query=query,
|
| 174 |
parameters=[{"name": "@limit", "value": limit}],
|
| 175 |
enable_cross_partition_query=True
|
| 176 |
))
|
| 177 |
+
|
| 178 |
+
# Validar y limpiar los datos
|
| 179 |
+
clean_sessions = []
|
| 180 |
+
for session in sessions:
|
| 181 |
+
try:
|
| 182 |
+
clean_sessions.append({
|
| 183 |
+
"username": session["username"],
|
| 184 |
+
"loginTime": session["loginTime"],
|
| 185 |
+
"logoutTime": session.get("logoutTime", "Activo"),
|
| 186 |
+
"sessionDuration": session.get("sessionDuration", 0)
|
| 187 |
+
})
|
| 188 |
+
except KeyError as e:
|
| 189 |
+
logger.warning(f"Sesi贸n con datos incompletos: {e}")
|
| 190 |
+
continue
|
| 191 |
+
|
| 192 |
+
return clean_sessions
|
| 193 |
except Exception as e:
|
| 194 |
+
logger.error(f"Error obteniendo sesiones recientes: {str(e)}")
|
| 195 |
return []
|
| 196 |
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
###########################################################
|
| 200 |
+
|
| 201 |
def get_user_total_time(username):
|
| 202 |
"""Obtiene el tiempo total que un usuario ha pasado en la plataforma"""
|
| 203 |
try:
|
|
|
|
| 210 |
FROM c
|
| 211 |
WHERE c.type = 'session'
|
| 212 |
AND c.username = @username
|
| 213 |
+
AND IS_DEFINED(c.sessionDuration)
|
| 214 |
"""
|
| 215 |
|
| 216 |
result = list(container.query_items(
|
| 217 |
query=query,
|
| 218 |
parameters=[{"name": "@username", "value": username}],
|
| 219 |
+
enable_cross_partition_query=True
|
| 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):
|