Proyectos de Subversion Moodle

Rev

Rev 1408 | Rev 1410 | Ir a la última revisión | Mostrar el archivo completo | | | Autoría | Ultima modificación | Ver Log |

Rev 1408 Rev 1409
Línea 1... Línea 1...
1
<?php
1
<?php
2
// Configuración de headers para respuesta JSON y CORS
2
// Configuración de headers para respuesta JSON y CORS
3
header('Content-Type: application/json');
3
// header('Content-Type: application/json'); // MOVED: Will be set only when outputting JSON
4
header('Access-Control-Allow-Origin: *');
4
// header('Access-Control-Allow-Origin: *'); // MOVED: Will be set only when outputting JSON
Línea 5... Línea 5...
5
 
5
 
6
// Definición de constantes para autenticación y encriptación
6
// Definición de constantes para autenticación y encriptación
7
define('LLWS_USERNAME', 'leaderdslinked-ws');
7
define('LLWS_USERNAME', 'leaderdslinked-ws');
8
define('LLWS_PASSWORD', 'KFB3lFsLp&*CpB0uc2VNc!zVn@w!EZqZ*jr$J0AlE@sYREUcyP');
8
define('LLWS_PASSWORD', 'KFB3lFsLp&*CpB0uc2VNc!zVn@w!EZqZ*jr$J0AlE@sYREUcyP');
Línea 63... Línea 63...
63
$password  = password_hash($username.'-'. $password. '-' . $rand. '-' . $timestamp, PASSWORD_DEFAULT);
63
$password  = password_hash($username.'-'. $password. '-' . $rand. '-' . $timestamp, PASSWORD_DEFAULT);
Línea 64... Línea 64...
64
 
64
 
65
$data       = $rsa->encrypt(json_encode(['email' => 'usuario4@test.com', 'first_name' => 'usuario4', 'last_name' => 'test']));
65
$data       = $rsa->encrypt(json_encode(['email' => 'usuario4@test.com', 'first_name' => 'usuario4', 'last_name' => 'test']));
Línea -... Línea 66...
-
 
66
*/
-
 
67
 
-
 
68
// Helper function to output JSON error and exit
-
 
69
function output_json_error($errorCode)
-
 
70
{
-
 
71
    // It's good practice to ensure session is closed before output,
-
 
72
    // though Moodle's exit handling might cover this.
-
 
73
    if (function_exists('session_write_close')) {
-
 
74
        session_write_close();
-
 
75
    }
-
 
76
    header('Content-Type: application/json');
-
 
77
    header('Access-Control-Allow-Origin: *'); // Assuming CORS is needed for errors too
-
 
78
    echo json_encode(['success' => false, 'data' => $errorCode]);
-
 
79
    exit;
66
*/
80
}
67
 
81
 
68
// Validación de parámetros de seguridad
82
// Validación de parámetros de seguridad
69
if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
-
 
70
    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
83
if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
Línea 71... Línea 84...
71
    exit;
84
    output_json_error('ERROR_SECURITY1');
72
}
85
}
73
 
86
 
74
// Validación del nombre de usuario
-
 
75
if ($username != LLWS_USERNAME) {
87
// Validación del nombre de usuario
Línea 76... Línea 88...
76
    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
88
if ($username != LLWS_USERNAME) {
77
    exit;
89
    output_json_error('ERROR_SECURITY2');
78
}
90
}
79
 
91
 
80
// Validación del formato del timestamp
-
 
81
$dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
92
// Validación del formato del timestamp
Línea 82... Línea 93...
82
if (!$dt) {
93
$dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
83
    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
94
if (!$dt) {
84
    exit;
95
    output_json_error('ERROR_SECURITY3');
85
}
96
}
Línea 86... Línea 97...
86
 
97
 
87
// Validación del rango de tiempo del timestamp (±5 minutos)
98
// Validación del rango de tiempo del timestamp (±5 minutos)
-
 
99
$t0 = $dt->getTimestamp();
88
$t0 = $dt->getTimestamp();
100
$t1 = strtotime('-5 minutes');
89
$t1 = strtotime('-5 minutes');
101
$t2 = strtotime('+5 minutes');
Línea 90... Línea 102...
90
$t2 = strtotime('+5 minutes');
102
 
91
 
103
if ($t0 < $t1 || $t0 > $t2) {
92
if ($t0 < $t1 || $t0 > $t2) {
104
    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
93
    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
-
 
94
    //exit;
105
    //output_json_error('ERROR_SECURITY4'); // Kept commented as in original for this line
Línea 95... Línea 106...
95
}
106
    //exit;
96
 
107
}
97
// Validación de la contraseña
108
 
98
if (!password_verify($username . '-' . LLWS_PASSWORD . '-' . $rand . '-' . $timestamp, $password)) {
-
 
99
    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
109
// Validación de la contraseña
Línea 100... Línea 110...
100
    exit;
110
if (!password_verify($username . '-' . LLWS_PASSWORD . '-' . $rand . '-' . $timestamp, $password)) {
101
}
111
    output_json_error('ERROR_SECURITY5');
102
 
112
}
103
// Validación de datos
113
 
104
if (empty($data)) {
-
 
105
    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
114
// Validación de datos
Línea 106... Línea 115...
106
    exit;
115
if (empty($data)) {
107
}
116
    output_json_error('ERROR_PARAMETERS1');
108
 
117
}
109
// Decodificación de datos en base64
118
 
110
$data = base64_decode($data);
119
// Decodificación de datos en base64
111
if (empty($data)) {
120
$data = base64_decode($data);
112
    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
121
if (empty($data)) {
113
    exit;
-
 
114
}
122
    output_json_error('ERROR_PARAMETERS2');
Línea 115... Línea 123...
115
 
123
}
116
// Desencriptación de datos usando RSA
124
 
117
try {
125
// Desencriptación de datos usando RSA
118
    $rsa = new rsa();
126
try {
119
    $rsa->setKeys(LLWS_RSA_N, LLWS_RSA_D, LLWS_RSA_E);
-
 
120
    $data = $rsa->decrypt($data);
127
    $rsa = new rsa();
Línea 121... Línea 128...
121
} catch (Throwable $e) {
128
    $rsa->setKeys(LLWS_RSA_N, LLWS_RSA_D, LLWS_RSA_E);
122
    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
129
    $data = $rsa->decrypt($data);
123
    exit;
130
} catch (Throwable $e) {
124
}
131
    output_json_error('ERROR_PARAMETERS3');
Línea 125... Línea 132...
125
 
132
}
126
// Conversión de datos a array
133
 
127
$data = (array) json_decode($data);
-
 
128
if (empty($data)) {
134
// Conversión de datos a array
Línea 129... Línea 135...
129
    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
135
$data = (array) json_decode($data);
130
    exit;
136
if (empty($data)) {
131
}
137
    output_json_error('ERROR_PARAMETERS4');
Línea 174... Línea 180...
174
    }
180
    }
175
}
181
}
Línea 176... Línea 182...
176
 
182
 
177
// Verificación de creación de usuario
183
// Verificación de creación de usuario
178
if (!$user) {
184
if (!$user) {
179
    echo json_encode(['success' => false, 'data' => 'ERROR_MOODLE1']);
-
 
180
    exit;
185
    output_json_error('ERROR_MOODLE1');
Línea 181... Línea 186...
181
}
186
}
182
 
187
 
183
// Inscripción en cursos para usuarios nuevos
188
// Inscripción en cursos para usuarios nuevos
Línea 225... Línea 230...
225
        require_logout();
230
        require_logout();
226
    }
231
    }
Línea 227... Línea 232...
227
 
232
 
228
    // Verificar si la cuenta está confirmada
233
    // Verificar si la cuenta está confirmada
229
    if (empty($user->confirmed)) {
234
    if (empty($user->confirmed)) {
230
        echo json_encode(['success' => false, 'data' => 'ACCOUNT_NOT_CONFIRMED']);
-
 
231
        exit;
235
        output_json_error('ACCOUNT_NOT_CONFIRMED');
Línea 232... Línea 236...
232
    }
236
    }
233
 
237
 
234
    // Verificar si la contraseña ha expirado (solo para autenticación LDAP)
238
    // Verificar si la contraseña ha expirado (solo para autenticación LDAP)
235
    $userauth = get_auth_plugin($user->auth);
239
    $userauth = get_auth_plugin($user->auth);
236
    if (!isguestuser() && !empty($userauth->config->expiration) && $userauth->config->expiration == 1) {
240
    if (!isguestuser() && !empty($userauth->config->expiration) && $userauth->config->expiration == 1) {
237
        $days2expire = $userauth->password_expire($user->username);
241
        $days2expire = $userauth->password_expire($user->username);
238
        if (intval($days2expire) < 0) {
-
 
239
            echo json_encode(['success' => false, 'data' => 'PASSWORD_EXPIRED']);
242
        if (intval($days2expire) < 0) {
240
            exit;
243
            output_json_error('PASSWORD_EXPIRED');
Línea 241... Línea 244...
241
        }
244
        }
242
    }
245
    }
Línea 243... Línea -...
243
 
-
 
244
    // Completar el proceso de inicio de sesión
246
 
245
    complete_user_login($user);
247
    // Completar el proceso de inicio de sesión
Línea 246... Línea 248...
246
 
248
    complete_user_login($user);
247
 
249
 
Línea 270... Línea 272...
270
    $SESSION->wantsurl = $urltogo;
272
    $SESSION->wantsurl = $urltogo;
Línea 271... Línea 273...
271
 
273
 
272
    // Verificar que la sesión se haya iniciado correctamente
274
    // Verificar que la sesión se haya iniciado correctamente
273
    if (isloggedin() && !isguestuser()) {
275
    if (isloggedin() && !isguestuser()) {
-
 
276
        // Enviar respuesta exitosa con datos del usuario
-
 
277
        // Instead of echoing JSON here and then redirecting (which is problematic),
-
 
278
        // we will just redirect. The browser will follow the redirect, and the
-
 
279
        // new session (with its cookie) will be active for the target page.
274
        // Enviar respuesta exitosa con datos del usuario
280
        /*
275
        echo json_encode([
281
        echo json_encode([
276
            'success' => true,
282
            'success' => true,
277
            'data' => [
283
            'data' => [
278
                'userid' => $user->id,
284
                'userid' => $user->id,
279
                'username' => $user->username,
285
                'username' => $user->username,
280
                'fullname' => fullname($user),
286
                'fullname' => fullname($user),
281
                'email' => $user->email,
287
                'email' => $user->email,
282
                'redirect' => $urltogo
288
                'redirect' => $urltogo
283
            ]
289
            ]
-
 
290
        ]);
Línea 284... Línea 291...
284
        ]);
291
        */
-
 
292
 
285
 
293
        // Redirigir al usuario
286
        // Redirigir al usuario
294
        // redirect() will handle session_write_close(), send Location header, and exit.
287
        redirect($urltogo);
295
        redirect($urltogo);
288
    } else {
296
    } else {
289
        echo json_encode(['success' => false, 'data' => 'LOGIN_FAILED']);
297
        output_json_error('LOGIN_FAILED');
290
    }
298
    }
291
} else {
299
} else {
292
    echo json_encode(['success' => false, 'data' => 'USER_NOT_FOUND']);
-
 
-
 
300
    output_json_error('USER_NOT_FOUND');
-
 
301
}