File size: 10,665 Bytes
bbf8ddd 585b429 1fa328e ad3e638 1fa328e 86b2b70 1fa328e 86b2b70 ad3e638 86b2b70 ad3e638 86b2b70 1fa328e fe4cbc8 1fa328e 0b4cbcf d61380b 1fa328e fe4cbc8 1fa328e fe4cbc8 1fa328e fe4cbc8 1fa328e d61380b fe4cbc8 1fa328e d61380b 1fa328e fe4cbc8 1fa328e ada2aa5 3ab9131 1fa328e ada2aa5 1fa328e ad3e638 ada2aa5 ad3e638 0b4cbcf 1fa328e 0b4cbcf 1fa328e 86b2b70 ada2aa5 1fa328e ada2aa5 d1cbdd7 ada2aa5 d1cbdd7 ada2aa5 0b4cbcf 1fa328e 3ab9131 ada2aa5 86b2b70 1fa328e ada2aa5 1fa328e 0b4cbcf ada2aa5 0b4cbcf ada2aa5 86b2b70 0b4cbcf 86b2b70 ada2aa5 1fa328e 0b4cbcf 3ab9131 ada2aa5 1fa328e 3ab9131 1fa328e ada2aa5 0b4cbcf ada2aa5 3ab9131 ada2aa5 1fa328e 3ab9131 ada2aa5 1fa328e ada2aa5 1fa328e 86b2b70 ada2aa5 86b2b70 1fa328e ada2aa5 1fa328e 86b2b70 3ab9131 ada2aa5 1fa328e ada2aa5 1fa328e ada2aa5 1fa328e 0b4cbcf 1fa328e ada2aa5 1fa328e 0b4cbcf ada2aa5 1fa328e ada2aa5 1fa328e ada2aa5 1fa328e c58df45 |
1 2 3 4 5 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 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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
#modules/database/sql_db.py
from .database_init import get_container
from datetime import datetime, timezone
import logging
import bcrypt
import uuid
logger = logging.getLogger(__name__)
def get_user(username, role=None):
container = get_container("users")
try:
query = f"SELECT * FROM c WHERE c.id = '{username}'"
if role:
query += f" AND c.role = '{role}'"
items = list(container.query_items(
query=query,
enable_cross_partition_query=True
))
return items[0] if items else None
except Exception as e:
logger.error(f"Error al obtener usuario {username}: {str(e)}")
return None
def get_admin_user(username):
return get_user(username, role='Administrador')
def get_student_user(username):
return get_user(username, role='Estudiante')
def get_teacher_user(username):
return get_user(username, role='Profesor')
#################################################################################
#El error ocurre porque el par谩metro `partition_key`
#no es soportado en la versi贸n actual del SDK.
#Modifiquemos la funci贸n `create_user()` para incluir la partici贸n en el cuerpo del documento:
def create_user(username, password, role, additional_info=None):
container = get_container("users")
if not container:
logger.error("No se pudo obtener el contenedor de usuarios")
return False
try:
# Generar salt y hash de la contrase帽a
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
user_data = {
'id': username,
'password': hashed.decode('utf-8'),
'salt': salt.decode('utf-8'),
'role': role,
'timestamp': datetime.now(timezone.utc).isoformat(),
'additional_info': additional_info or {},
# La partici贸n va dentro del documento
'partitionKey': username
}
container.create_item(body=user_data)
logger.info(f"Usuario {role} creado: {username}")
return True
except Exception as e:
logger.error(f"Error al crear usuario {role}: {str(e)}")
return False
#########################################################################
def create_student_user(username, password, additional_info=None):
return create_user(username, password, 'Estudiante', additional_info)
def create_teacher_user(username, password, additional_info=None):
return create_user(username, password, 'Profesor', additional_info)
def create_admin_user(username, password, additional_info=None):
return create_user(username, password, 'Administrador', additional_info)
############-- Funciones de control del tiempo de sesi贸n ##################
###########################################################
def record_login(username):
"""Registra el inicio de sesi贸n de un usuario"""
try:
container = get_container("users_sessions")
if not container:
logger.error("No se pudo obtener el contenedor users_sessions")
return None
session_id = str(uuid.uuid4())
session_doc = {
"id": session_id,
"type": "session",
"username": username,
"loginTime": datetime.now(timezone.utc).isoformat(),
"additional_info": {},
# El campo para partition key debe estar en el documento
"partitionKey": username
}
# Crear el documento usando options
result = container.create_item(
body=session_doc,
enable_cross_partition_query=True
)
logger.info(f"Sesi贸n {session_id} registrada para {username}")
return session_id
except Exception as e:
logger.error(f"Error registrando login: {str(e)}")
return None
###########################################################
def record_logout(username, session_id):
"""Registra el cierre de sesi贸n y calcula la duraci贸n"""
try:
container = get_container("users_sessions")
if not container:
logger.error("No se pudo obtener el contenedor users_sessions")
return False
# Obtener la sesi贸n actual
query = "SELECT * FROM c WHERE c.id = @id AND c.username = @username"
params = [
{"name": "@id", "value": session_id},
{"name": "@username", "value": username}
]
items = list(container.query_items(
query=query,
parameters=params,
enable_cross_partition_query=True
))
if not items:
logger.warning(f"Sesi贸n no encontrada: {session_id}")
return False
session = items[0]
login_time = datetime.fromisoformat(session['loginTime'].rstrip('Z'))
logout_time = datetime.now(timezone.utc)
duration = int((logout_time - login_time).total_seconds())
session.update({
"logoutTime": logout_time.isoformat(),
"sessionDuration": duration
})
# Actualizar el documento
container.upsert_item(
body=session
)
logger.info(f"Sesi贸n {session_id} cerrada para {username}, duraci贸n: {duration}s")
return True
except Exception as e:
logger.error(f"Error registrando logout: {str(e)}")
return False
###########################################################
def get_recent_sessions(limit=10):
"""Obtiene las sesiones m谩s recientes"""
try:
container = get_container("users_sessions")
if not container:
logger.error("No se pudo obtener el contenedor users_sessions")
return []
query = """
SELECT c.username, c.loginTime, c.logoutTime, c.sessionDuration
FROM c
WHERE c.type = 'session'
ORDER BY c.loginTime DESC
OFFSET 0 LIMIT @limit
"""
sessions = list(container.query_items(
query=query,
parameters=[{"name": "@limit", "value": limit}],
enable_cross_partition_query=True
))
# Validar y limpiar los datos
clean_sessions = []
for session in sessions:
try:
clean_sessions.append({
"username": session["username"],
"loginTime": session["loginTime"],
"logoutTime": session.get("logoutTime", "Activo"),
"sessionDuration": session.get("sessionDuration", 0)
})
except KeyError as e:
logger.warning(f"Sesi贸n con datos incompletos: {e}")
continue
return clean_sessions
except Exception as e:
logger.error(f"Error obteniendo sesiones recientes: {str(e)}")
return []
###########################################################
def get_user_total_time(username):
"""Obtiene el tiempo total que un usuario ha pasado en la plataforma"""
try:
container = get_container("users_sessions")
if not container:
return None
query = """
SELECT VALUE SUM(c.sessionDuration)
FROM c
WHERE c.type = 'session'
AND c.username = @username
AND IS_DEFINED(c.sessionDuration)
"""
result = list(container.query_items(
query=query,
parameters=[{"name": "@username", "value": username}],
enable_cross_partition_query=True
))
return result[0] if result and result[0] is not None else 0
except Exception as e:
logger.error(f"Error obteniendo tiempo total: {str(e)}")
return 0
###########################################################
def update_student_user(username, new_info):
user_container, _, _ = get_sql_containers()
try:
user = get_student_user(username)
if user:
user['additional_info'].update(new_info)
user_container.upsert_item(body=user)
logger.info(f"Informaci贸n del estudiante actualizada: {username}")
return True
else:
logger.warning(f"Intento de actualizar estudiante no existente: {username}")
return False
except Exception as e:
logger.error(f"Error al actualizar informaci贸n del estudiante {username}: {str(e)}")
return False
def delete_student_user(username):
user_container, _, _ = get_sql_containers()
try:
user = get_student_user(username)
if user:
user_container.delete_item(item=user['id'], partition_key=username)
logger.info(f"Estudiante eliminado: {username}")
return True
else:
logger.warning(f"Intento de eliminar estudiante no existente: {username}")
return False
except Exception as e:
logger.error(f"Error al eliminar estudiante {username}: {str(e)}")
return False
def store_application_request(name, lastname, email, institution, current_role, desired_role, reason):
_, application_requests_container, _ = get_sql_containers()
try:
application_request = {
"id": str(uuid.uuid4()),
"name": name,
"lastname": lastname,
"email": email,
"institution": institution,
"current_role": current_role,
"desired_role": desired_role,
"reason": reason,
"requestDate": datetime.utcnow().isoformat()
}
application_requests_container.create_item(body=application_request)
logger.info(f"Solicitud de aplicaci贸n almacenada para el email: {email}")
return True
except Exception as e:
logger.error(f"Error al almacenar la solicitud de aplicaci贸n: {str(e)}")
return False
def store_student_feedback(username, name, email, feedback):
_, _, user_feedback_container = get_sql_containers()
try:
feedback_item = {
"id": str(uuid.uuid4()),
"username": username,
"name": name,
"email": email,
"feedback": feedback,
"role": "Estudiante",
'timestamp': datetime.now(timezone.utc).isoformat(),
}
result = user_feedback_container.create_item(body=feedback_item)
logger.info(f"Feedback de estudiante almacenado con ID: {result['id']} para el usuario: {username}")
return True
except Exception as e:
logger.error(f"Error al almacenar el feedback del estudiante {username}: {str(e)}")
return False |