|
import os
|
|
from azure.cosmos import CosmosClient, exceptions
|
|
from azure.cosmos.exceptions import CosmosHttpResponseError
|
|
import bcrypt
|
|
import base64
|
|
from ..database.sql_db import (
|
|
get_user,
|
|
get_student_user,
|
|
get_admin_user,
|
|
get_teacher_user,
|
|
create_student_user,
|
|
update_student_user,
|
|
delete_student_user
|
|
)
|
|
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def clean_and_validate_key(key):
|
|
key = key.strip()
|
|
while len(key) % 4 != 0:
|
|
key += '='
|
|
try:
|
|
base64.b64decode(key)
|
|
return key
|
|
except:
|
|
raise ValueError("La clave proporcionada no es v谩lida")
|
|
|
|
|
|
endpoint = os.getenv("COSMOS_ENDPOINT")
|
|
key = os.getenv("COSMOS_KEY")
|
|
|
|
if not endpoint or not key:
|
|
raise ValueError("Las variables de entorno COSMOS_ENDPOINT y COSMOS_KEY deben estar configuradas")
|
|
|
|
key = clean_and_validate_key(key)
|
|
|
|
|
|
|
|
def authenticate_user(username, password):
|
|
try:
|
|
user_item = get_user(username)
|
|
if user_item and verify_password(user_item['password'], password):
|
|
logger.info(f"Usuario autenticado: {username}, Rol: {user_item['role']}")
|
|
return True, user_item['role']
|
|
logger.warning(f"Autenticaci贸n fallida para el usuario: {username}")
|
|
return False, None
|
|
except Exception as e:
|
|
logger.error(f"Error durante la autenticaci贸n del usuario: {str(e)}")
|
|
return False, None
|
|
|
|
def authenticate_admin(username, password):
|
|
return authenticate_user(username, password)
|
|
|
|
def authenticate_student(username, password):
|
|
return authenticate_user(username, password)
|
|
|
|
def authenticate_teacher(username, password):
|
|
return authenticate_user(username, password)
|
|
|
|
|
|
def register_student(username, password, additional_info=None):
|
|
try:
|
|
if get_student_user(username):
|
|
logger.warning(f"Intento de registro de estudiante existente: {username}")
|
|
return False
|
|
|
|
success = create_student_user(username, password, additional_info)
|
|
if success:
|
|
logger.info(f"Nuevo estudiante registrado: {username}")
|
|
return True
|
|
else:
|
|
logger.error(f"Error al registrar nuevo estudiante: {username}")
|
|
return False
|
|
except Exception as e:
|
|
logger.error(f"Error al registrar estudiante: {str(e)}")
|
|
return False
|
|
|
|
def update_student_info(username, new_info):
|
|
try:
|
|
success = update_student_user(username, new_info)
|
|
if success:
|
|
logger.info(f"Informaci贸n del estudiante actualizada: {username}")
|
|
return True
|
|
else:
|
|
logger.error(f"Error al actualizar informaci贸n del estudiante: {username}")
|
|
return False
|
|
except Exception as e:
|
|
logger.error(f"Error al actualizar informaci贸n del estudiante: {str(e)}")
|
|
return False
|
|
|
|
def delete_student(username):
|
|
try:
|
|
success = delete_student_user(username)
|
|
if success:
|
|
logger.info(f"Estudiante eliminado: {username}")
|
|
return True
|
|
else:
|
|
logger.error(f"Error al eliminar estudiante: {username}")
|
|
return False
|
|
except Exception as e:
|
|
logger.error(f"Error al eliminar estudiante: {str(e)}")
|
|
return False
|
|
|
|
|
|
|
|
|
|
def hash_password(password):
|
|
"""Hash a password for storing."""
|
|
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
|
|
|
|
|
|
|
def verify_password(stored_password, provided_password):
|
|
"""Verify a stored password against one provided by user"""
|
|
return bcrypt.checkpw(provided_password.encode('utf-8'), stored_password.encode('utf-8'))
|
|
|
|
|