Proyectos de Subversion Moodle

Rev

Rev 1413 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php
// Configuración de headers para respuesta JSON y CORS
// header('Content-Type: application/json'); // MOVED: Will be set only when outputting JSON
// header('Access-Control-Allow-Origin: *'); // MOVED: Will be set only when outputting JSON

// Definición de constantes para autenticación y encriptación
define('LLWS_USERNAME', 'leaderdslinked-ws');
define('LLWS_PASSWORD', 'KFB3lFsLp&*CpB0uc2VNc!zVn@w!EZqZ*jr$J0AlE@sYREUcyP');
define('LLWS_RSA_N', 34589927);  // Clave pública RSA N
define('LLWS_RSA_D', 4042211);   // Clave privada RSA D
define('LLWS_RSA_E', 7331);      // Clave pública RSA E
define('LLWS_CATEGORY_ID', 6);   // ID de categoría para cursos

// Inclusión de archivos necesarios de Moodle
require_once(__DIR__ . '/../config.php');
global $DB, $CFG;

// Inclusión de librerías de Moodle
require_once($CFG->libdir . '/moodlelib.php');
require_once($CFG->libdir . '/externallib.php');
require_once($CFG->libdir . '/authlib.php');
require_once($CFG->libdir . '/gdlib.php');
require_once($CFG->dirroot . '/user/lib.php');
require_once(__DIR__ . '/rsa.php');
require_once(__DIR__ . '/lib.php');

// Obtención y sanitización de parámetros de la petición
$username   = trim(isset($_REQUEST['username']) ? filter_var($_REQUEST['username'], FILTER_SANITIZE_STRING) : '');
$password   = trim(isset($_REQUEST['password']) ? filter_var($_REQUEST['password'], FILTER_SANITIZE_STRING) : '');
$timestamp  = trim(isset($_REQUEST['timestamp']) ? filter_var($_REQUEST['timestamp'], FILTER_SANITIZE_STRING) : '');
$rand       = intval(isset($_REQUEST['rand']) ? filter_var($_REQUEST['rand'], FILTER_SANITIZE_NUMBER_INT) : 0, 10);
$data       = trim(isset($_REQUEST['data']) ? filter_var($_REQUEST['data'], FILTER_SANITIZE_STRING) : '');

/*
$data = '';
$input = fopen("php://input", "r");


while ($line = fread($input, 1024))
{
    $data .= $line; 
}
fclose($input);*/

/*
echo 'username = '. $username . PHP_EOL;
echo 'password = '. $password . PHP_EOL;
echo 'rand = '. $rand . PHP_EOL;
echo 'timestamp = '. $timestamp . PHP_EOL;
echo 'data = '. $data . PHP_EOL;


/*
list($usec, $sec) = explode(' ', microtime());
$seed = intval($sec + ((float) $usec * 100000));

$username   = LLWS_USERNAME;
$timestamp  = date('Y-m-d\TH:i:s');
mt_srand($seed, MT_RAND_MT19937);
$rand =  mt_rand();

$password   = LLWS_PASSWORD;
$password  = password_hash($username.'-'. $password. '-' . $rand. '-' . $timestamp, PASSWORD_DEFAULT);

$data       = $rsa->encrypt(json_encode(['email' => 'usuario4@test.com', 'first_name' => 'usuario4', 'last_name' => 'test']));
*/

// Helper function to output JSON error and exit
function output_json_error($errorCode)
{
    // It's good practice to ensure session is closed before output,
    // though Moodle's exit handling might cover this.
    if (function_exists('session_write_close')) {
        session_write_close();
    }
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *'); // Assuming CORS is needed for errors too
    echo json_encode(['success' => false, 'data' => $errorCode]);
    exit;
}

// Validación de parámetros de seguridad
if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
    output_json_error('ERROR_SECURITY1');
}

// Validación del nombre de usuario
if ($username != LLWS_USERNAME) {
    output_json_error('ERROR_SECURITY2');
}

// Validación del formato del timestamp
$dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
if (!$dt) {
    output_json_error('ERROR_SECURITY3');
}

// Validación del rango de tiempo del timestamp (±5 minutos)
$t0 = $dt->getTimestamp();
$t1 = strtotime('-5 minutes');
$t2 = strtotime('+5 minutes');

if ($t0 < $t1 || $t0 > $t2) {
    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
    //output_json_error('ERROR_SECURITY4'); // Kept commented as in original for this line
    //exit;
}

// Validación de la contraseña
if (!password_verify($username . '-' . LLWS_PASSWORD . '-' . $rand . '-' . $timestamp, $password)) {
    output_json_error('ERROR_SECURITY5');
}

// Validación de datos
if (empty($data)) {
    output_json_error('ERROR_PARAMETERS1');
}

// Decodificación de datos en base64
$data = base64_decode($data);
if (empty($data)) {
    output_json_error('ERROR_PARAMETERS2');
}

// Desencriptación de datos usando RSA
try {
    $rsa = new rsa();
    $rsa->setKeys(LLWS_RSA_N, LLWS_RSA_D, LLWS_RSA_E);
    $data = $rsa->decrypt($data);
} catch (Throwable $e) {
    output_json_error('ERROR_PARAMETERS3');
}

// Conversión de datos a array
$data = (array) json_decode($data);
if (empty($data)) {
    output_json_error('ERROR_PARAMETERS4');
}

// Extracción y validación de datos del usuario
$email      = trim(isset($data['email']) ? filter_var($data['email'], FILTER_SANITIZE_EMAIL) : '');
$first_name = trim(isset($data['first_name']) ? filter_var($data['first_name'], FILTER_SANITIZE_STRING) : '');
$last_name  = trim(isset($data['last_name']) ? filter_var($data['last_name'], FILTER_SANITIZE_STRING) : '');

if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
    output_json_error('ERROR_PARAMETERS5');
}

// Búsqueda o creación de usuario
$user = ll_get_user_by_email($email);
if ($user) {
    $new_user = false;
} else {
    $new_user = true;
    $username = ll_get_username_available($first_name, $last_name);
    $user = ll_create_user($username, $email, $first_name, $last_name);

    // Procesamiento de imagen de perfil si se proporciona
    if ($user) {
        $filename   = trim(isset($data['image_filename']) ? filter_var($data['image_filename'], FILTER_SANITIZE_EMAIL) : '');
        $content    = trim(isset($data['image_content']) ? filter_var($data['image_content'], FILTER_SANITIZE_STRING) : '');

        if ($filename && $content) {
            $tempfile = __DIR__ . DIRECTORY_SEPARATOR . $filename;
            try {
                file_put_contents($filename, base64_decode($content));
                if (file_exists($tempfile)) {
                    $usericonid = process_new_icon(context_user::instance($user->id, MUST_EXIST), 'user', 'icon', 0, $tempfile);
                    if ($usericonid) {
                        $DB->set_field('user', 'picture', $usericonid, array('id' => $user->id));
                    }
                }
            } catch (\Throwable $e) {
            } finally {
                if (file_exists($tempfile)) {
                    unlink($tempfile);
                }
            }
        }
    }
}

// Verificación de creación de usuario
if (!$user) {
    output_json_error('ERROR_MOODLE1');
}

// Inscripción en cursos para usuarios nuevos
if ($new_user) {
    $role = $DB->get_record('role', array('archetype' => 'student'));
    $enrolmethod = 'manual';

    $courses = get_courses();
    foreach ($courses as $course) {
        if ($course->categoy_id == LLWS_CATEGORY_ID) {
            $context = context_course::instance($course->id);
            if (!is_enrolled($context, $user)) {
                $enrol = enrol_get_plugin($enrolmethod);
                if ($enrol === null) {
                    return false;
                }
                $instances = enrol_get_instances($course->id, true);
                $manualinstance = null;
                foreach ($instances as $instance) {
                    if ($instance->name == $enrolmethod) {
                        $manualinstance = $instance;
                        break;
                    }
                }
                if ($manualinstance !== null) {
                    $instanceid = $enrol->add_default_instance($course);
                    if ($instanceid === null) {
                        $instanceid = $enrol->add_instance($course);
                    }
                    $instance = $DB->get_record('enrol', array('id' => $instanceid));
                    if ($instance) {
                        $enrol->enrol_user($instance, $user->id, $role->id);
                    }
                }
            }
        }
    }
}

// Obtención de datos completos del usuario y login
$user = get_complete_user_data('id', $user->id);
if ($user) {
    // Verificar si la cuenta está confirmada
    if (empty($user->confirmed)) {
        output_json_error('ACCOUNT_NOT_CONFIRMED');
    }

    // Verificar si la contraseña ha expirado (solo para autenticación LDAP)
    $userauth = get_auth_plugin($user->auth);
    if (!isguestuser() && !empty($userauth->config->expiration) && $userauth->config->expiration == 1) {
        $days2expire = $userauth->password_expire($user->username);
        if (intval($days2expire) < 0) {
            output_json_error('PASSWORD_EXPIRED');
        }
    }

    // Si hay una sesión existente, cerrarla primero
    if (isloggedin()) {
        \core\session\manager::kill_all_sessions();
        \core\session\manager::terminate_current();
        session_destroy();
        // Delete MoodleSession cookie
        setcookie('MoodleSession', '', time() - 3600, '/');
    }

    // Completar el proceso de inicio de sesión
    complete_user_login($user);

    // Aplicar límite de inicio de sesión concurrente
    //\core\session\manager::apply_concurrent_login_limit($user->id, session_id());

    // Configurar cookie de nombre de usuario
    if (!empty($CFG->nolastloggedin)) {
        // No almacenar último usuario conectado en cookie
    } else if (empty($CFG->rememberusername)) {
        // Sin cookies permanentes, eliminar la anterior si existe
        set_moodle_cookie('');
    } else {
        set_moodle_cookie($user->username);
    }

    // Limpiar mensajes de error antes de la última redirección
    unset($SESSION->loginerrormsg);
    unset($SESSION->logininfomsg);

    // Descartar loginredirect si estamos redirigiendo
    unset($SESSION->loginredirect);

    // Configurar la URL de destino
    $urltogo = $CFG->wwwroot . '/my';
    $SESSION->wantsurl = $urltogo;

    // Verificar que la sesión se haya iniciado correctamente
    if (isloggedin() && !isguestuser()) {
        // Enviar respuesta exitosa con datos del usuario
        // Instead of echoing JSON here and then redirecting (which is problematic),
        // we will just redirect. The browser will follow the redirect, and the
        // new session (with its cookie) will be active for the target page.
        /*
        echo json_encode([
            'success' => true,
            'data' => [
                'userid' => $user->id,
                'username' => $user->username,
                'fullname' => fullname($user),
                'email' => $user->email,
                'redirect' => $urltogo
            ]
        ]);
        */

        // Redirigir al usuario
        // redirect() will handle session_write_close(), send Location header, and exit.
        redirect($urltogo);
    } else {
        output_json_error('LOGIN_FAILED');
    }
} else {
    output_json_error('USER_NOT_FOUND');
}
// The script should have exited by now either via output_json_error() or redirect().
exit; // Explicit exit here as a fallback, though not strictly necessary if all paths exit.