Spaces:
Sleeping
Sleeping
Update modules/database/sql_db.py
Browse files- modules/database/sql_db.py +17 -55
modules/database/sql_db.py
CHANGED
|
@@ -10,28 +10,18 @@ logger = logging.getLogger(__name__)
|
|
| 10 |
|
| 11 |
#########################################
|
| 12 |
def get_user(username, role=None):
|
| 13 |
-
"""Obtiene un usuario por su username"""
|
| 14 |
container = get_container("users")
|
| 15 |
try:
|
| 16 |
-
query = f"SELECT * FROM c WHERE c.id =
|
| 17 |
-
params = [{"name": "@username", "value": username}]
|
| 18 |
-
|
| 19 |
if role:
|
| 20 |
-
query += " AND c.role =
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
items = list(container.query_items(
|
| 24 |
-
query=query,
|
| 25 |
-
parameters=params,
|
| 26 |
-
enable_cross_partition_query=True
|
| 27 |
-
))
|
| 28 |
-
|
| 29 |
return items[0] if items else None
|
| 30 |
-
|
| 31 |
except Exception as e:
|
| 32 |
logger.error(f"Error al obtener usuario {username}: {str(e)}")
|
| 33 |
return None
|
| 34 |
|
|
|
|
| 35 |
#########################################
|
| 36 |
def get_admin_user(username):
|
| 37 |
return get_user(username, role='Administrador')
|
|
@@ -56,46 +46,26 @@ def create_user(username, password, role, additional_info=None):
|
|
| 56 |
return False
|
| 57 |
|
| 58 |
try:
|
| 59 |
-
# Verificar que no exista el usuario
|
| 60 |
-
existing_user = get_user(username)
|
| 61 |
-
if existing_user:
|
| 62 |
-
logger.warning(f"Usuario {username} ya existe")
|
| 63 |
-
return False
|
| 64 |
-
|
| 65 |
-
# Crear documento del usuario
|
| 66 |
user_data = {
|
| 67 |
'id': username,
|
| 68 |
-
'password': password,
|
| 69 |
'role': role,
|
| 70 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 71 |
-
'additional_info': additional_info or {}
|
|
|
|
| 72 |
}
|
| 73 |
|
| 74 |
-
# Crear
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
)
|
| 79 |
|
| 80 |
-
if result:
|
| 81 |
-
logger.info(f"Usuario {role} creado exitosamente: {username}")
|
| 82 |
-
return True
|
| 83 |
-
else:
|
| 84 |
-
logger.error(f"No se pudo crear el usuario {username}")
|
| 85 |
-
return False
|
| 86 |
-
|
| 87 |
except Exception as e:
|
| 88 |
-
logger.error(f"Error al crear usuario {role}
|
| 89 |
return False
|
| 90 |
|
| 91 |
#########################################
|
| 92 |
def create_student_user(username, password, additional_info=None):
|
| 93 |
-
"""Crea un nuevo usuario estudiante"""
|
| 94 |
-
# Verificar que la contrase帽a est茅 hasheada
|
| 95 |
-
if not password.startswith('$2b$'):
|
| 96 |
-
logger.error("Intento de crear usuario con contrase帽a no hasheada")
|
| 97 |
-
return False
|
| 98 |
-
|
| 99 |
return create_user(username, password, 'Estudiante', additional_info)
|
| 100 |
|
| 101 |
#########################################
|
|
@@ -133,7 +103,6 @@ def record_login(username):
|
|
| 133 |
return None
|
| 134 |
|
| 135 |
#########################################
|
| 136 |
-
|
| 137 |
def record_logout(username, session_id):
|
| 138 |
"""Registra el cierre de sesi贸n y calcula la duraci贸n"""
|
| 139 |
try:
|
|
@@ -148,11 +117,9 @@ def record_logout(username, session_id):
|
|
| 148 |
{"name": "@username", "value": username}
|
| 149 |
]
|
| 150 |
|
| 151 |
-
# Agregar enable_cross_partition_query=True
|
| 152 |
items = list(container.query_items(
|
| 153 |
query=query,
|
| 154 |
-
parameters=params
|
| 155 |
-
enable_cross_partition_query=True
|
| 156 |
))
|
| 157 |
|
| 158 |
if not items:
|
|
@@ -166,7 +133,8 @@ def record_logout(username, session_id):
|
|
| 166 |
|
| 167 |
session.update({
|
| 168 |
"logoutTime": logout_time.isoformat(),
|
| 169 |
-
"sessionDuration": duration
|
|
|
|
| 170 |
})
|
| 171 |
|
| 172 |
container.upsert_item(body=session)
|
|
@@ -193,14 +161,11 @@ def get_recent_sessions(limit=10):
|
|
| 193 |
OFFSET 0 LIMIT @limit
|
| 194 |
"""
|
| 195 |
|
| 196 |
-
# Agregar enable_cross_partition_query=True
|
| 197 |
sessions = list(container.query_items(
|
| 198 |
query=query,
|
| 199 |
-
parameters=[{"name": "@limit", "value": limit}]
|
| 200 |
-
enable_cross_partition_query=True
|
| 201 |
))
|
| 202 |
|
| 203 |
-
# Validar y limpiar los datos
|
| 204 |
clean_sessions = []
|
| 205 |
for session in sessions:
|
| 206 |
try:
|
|
@@ -220,7 +185,6 @@ def get_recent_sessions(limit=10):
|
|
| 220 |
return []
|
| 221 |
|
| 222 |
#########################################
|
| 223 |
-
|
| 224 |
def get_user_total_time(username):
|
| 225 |
"""Obtiene el tiempo total que un usuario ha pasado en la plataforma"""
|
| 226 |
try:
|
|
@@ -236,11 +200,9 @@ def get_user_total_time(username):
|
|
| 236 |
AND IS_DEFINED(c.sessionDuration)
|
| 237 |
"""
|
| 238 |
|
| 239 |
-
# Agregar enable_cross_partition_query=True
|
| 240 |
result = list(container.query_items(
|
| 241 |
query=query,
|
| 242 |
-
parameters=[{"name": "@username", "value": username}]
|
| 243 |
-
enable_cross_partition_query=True
|
| 244 |
))
|
| 245 |
|
| 246 |
return result[0] if result and result[0] is not None else 0
|
|
|
|
| 10 |
|
| 11 |
#########################################
|
| 12 |
def get_user(username, role=None):
|
|
|
|
| 13 |
container = get_container("users")
|
| 14 |
try:
|
| 15 |
+
query = f"SELECT * FROM c WHERE c.id = '{username}'"
|
|
|
|
|
|
|
| 16 |
if role:
|
| 17 |
+
query += f" AND c.role = '{role}'"
|
| 18 |
+
items = list(container.query_items(query=query))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
return items[0] if items else None
|
|
|
|
| 20 |
except Exception as e:
|
| 21 |
logger.error(f"Error al obtener usuario {username}: {str(e)}")
|
| 22 |
return None
|
| 23 |
|
| 24 |
+
|
| 25 |
#########################################
|
| 26 |
def get_admin_user(username):
|
| 27 |
return get_user(username, role='Administrador')
|
|
|
|
| 46 |
return False
|
| 47 |
|
| 48 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
user_data = {
|
| 50 |
'id': username,
|
| 51 |
+
'password': password,
|
| 52 |
'role': role,
|
| 53 |
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 54 |
+
'additional_info': additional_info or {},
|
| 55 |
+
'partitionKey': username # Agregar partition key
|
| 56 |
}
|
| 57 |
|
| 58 |
+
# Crear item sin especificar partition_key en el m茅todo
|
| 59 |
+
container.create_item(body=user_data)
|
| 60 |
+
logger.info(f"Usuario {role} creado: {username}")
|
| 61 |
+
return True
|
|
|
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
except Exception as e:
|
| 64 |
+
logger.error(f"Error al crear usuario {role}: {str(e)}")
|
| 65 |
return False
|
| 66 |
|
| 67 |
#########################################
|
| 68 |
def create_student_user(username, password, additional_info=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
return create_user(username, password, 'Estudiante', additional_info)
|
| 70 |
|
| 71 |
#########################################
|
|
|
|
| 103 |
return None
|
| 104 |
|
| 105 |
#########################################
|
|
|
|
| 106 |
def record_logout(username, session_id):
|
| 107 |
"""Registra el cierre de sesi贸n y calcula la duraci贸n"""
|
| 108 |
try:
|
|
|
|
| 117 |
{"name": "@username", "value": username}
|
| 118 |
]
|
| 119 |
|
|
|
|
| 120 |
items = list(container.query_items(
|
| 121 |
query=query,
|
| 122 |
+
parameters=params
|
|
|
|
| 123 |
))
|
| 124 |
|
| 125 |
if not items:
|
|
|
|
| 133 |
|
| 134 |
session.update({
|
| 135 |
"logoutTime": logout_time.isoformat(),
|
| 136 |
+
"sessionDuration": duration,
|
| 137 |
+
"partitionKey": username
|
| 138 |
})
|
| 139 |
|
| 140 |
container.upsert_item(body=session)
|
|
|
|
| 161 |
OFFSET 0 LIMIT @limit
|
| 162 |
"""
|
| 163 |
|
|
|
|
| 164 |
sessions = list(container.query_items(
|
| 165 |
query=query,
|
| 166 |
+
parameters=[{"name": "@limit", "value": limit}]
|
|
|
|
| 167 |
))
|
| 168 |
|
|
|
|
| 169 |
clean_sessions = []
|
| 170 |
for session in sessions:
|
| 171 |
try:
|
|
|
|
| 185 |
return []
|
| 186 |
|
| 187 |
#########################################
|
|
|
|
| 188 |
def get_user_total_time(username):
|
| 189 |
"""Obtiene el tiempo total que un usuario ha pasado en la plataforma"""
|
| 190 |
try:
|
|
|
|
| 200 |
AND IS_DEFINED(c.sessionDuration)
|
| 201 |
"""
|
| 202 |
|
|
|
|
| 203 |
result = list(container.query_items(
|
| 204 |
query=query,
|
| 205 |
+
parameters=[{"name": "@username", "value": username}]
|
|
|
|
| 206 |
))
|
| 207 |
|
| 208 |
return result[0] if result and result[0] is not None else 0
|