96 |
efrain |
1 |
<?php
|
1389 |
ariadna |
2 |
// Configuración de headers para respuesta JSON y CORS
|
96 |
efrain |
3 |
header('Content-Type: application/json');
|
|
|
4 |
header('Access-Control-Allow-Origin: *');
|
1389 |
ariadna |
5 |
|
|
|
6 |
// Definición de constantes para autenticación y encriptación
|
96 |
efrain |
7 |
define('LLWS_USERNAME', 'leaderdslinked-ws');
|
|
|
8 |
define('LLWS_PASSWORD', 'KFB3lFsLp&*CpB0uc2VNc!zVn@w!EZqZ*jr$J0AlE@sYREUcyP');
|
1389 |
ariadna |
9 |
define('LLWS_RSA_N', 34589927); // Clave pública RSA N
|
|
|
10 |
define('LLWS_RSA_D', 4042211); // Clave privada RSA D
|
|
|
11 |
define('LLWS_RSA_E', 7331); // Clave pública RSA E
|
|
|
12 |
define('LLWS_CATEGORY_ID', 6); // ID de categoría para cursos
|
96 |
efrain |
13 |
|
1389 |
ariadna |
14 |
// Inclusión de archivos necesarios de Moodle
|
96 |
efrain |
15 |
require_once(__DIR__ . '/../config.php');
|
|
|
16 |
global $DB, $CFG;
|
|
|
17 |
|
1389 |
ariadna |
18 |
// Inclusión de librerías de Moodle
|
1383 |
ariadna |
19 |
require_once($CFG->libdir . '/moodlelib.php');
|
96 |
efrain |
20 |
require_once($CFG->libdir . '/externallib.php');
|
1383 |
ariadna |
21 |
require_once($CFG->libdir . '/authlib.php');
|
|
|
22 |
require_once($CFG->libdir . '/gdlib.php');
|
|
|
23 |
require_once($CFG->dirroot . '/user/lib.php');
|
1389 |
ariadna |
24 |
require_once(__DIR__ . '/rsa.php');
|
|
|
25 |
require_once(__DIR__ . '/lib.php');
|
96 |
efrain |
26 |
|
1399 |
ariadna |
27 |
/**
|
|
|
28 |
* Valida los parámetros de seguridad de la petición
|
|
|
29 |
* @param array $params Parámetros de la petición
|
|
|
30 |
* @return array|false Array con los parámetros validados o false si hay error
|
|
|
31 |
*/
|
|
|
32 |
function validateSecurityParams($params)
|
1388 |
ariadna |
33 |
{
|
1399 |
ariadna |
34 |
$username = trim(isset($params['username']) ? filter_var($params['username'], FILTER_SANITIZE_STRING) : '');
|
|
|
35 |
$password = trim(isset($params['password']) ? filter_var($params['password'], FILTER_SANITIZE_STRING) : '');
|
|
|
36 |
$timestamp = trim(isset($params['timestamp']) ? filter_var($params['timestamp'], FILTER_SANITIZE_STRING) : '');
|
|
|
37 |
$rand = intval(isset($params['rand']) ? filter_var($params['rand'], FILTER_SANITIZE_NUMBER_INT) : 0, 10);
|
|
|
38 |
$data = trim(isset($params['data']) ? filter_var($params['data'], FILTER_SANITIZE_STRING) : '');
|
1388 |
ariadna |
39 |
|
1399 |
ariadna |
40 |
if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
|
|
|
41 |
return ['error' => 'ERROR_SECURITY1', 'message' => 'Missing or invalid security parameters'];
|
|
|
42 |
}
|
1388 |
ariadna |
43 |
|
1399 |
ariadna |
44 |
if ($username != LLWS_USERNAME) {
|
|
|
45 |
return ['error' => 'ERROR_SECURITY2', 'message' => 'Invalid username'];
|
|
|
46 |
}
|
1388 |
ariadna |
47 |
|
1399 |
ariadna |
48 |
$dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
|
|
|
49 |
if (!$dt) {
|
|
|
50 |
return ['error' => 'ERROR_SECURITY3', 'message' => 'Invalid timestamp format'];
|
|
|
51 |
}
|
1388 |
ariadna |
52 |
|
1399 |
ariadna |
53 |
$t0 = $dt->getTimestamp();
|
|
|
54 |
$t1 = strtotime('-5 minutes');
|
|
|
55 |
$t2 = strtotime('+5 minutes');
|
1388 |
ariadna |
56 |
|
1400 |
ariadna |
57 |
/* if ($t0 < $t1 || $t0 > $t2) {
|
1399 |
ariadna |
58 |
return ['error' => 'ERROR_SECURITY4', 'message' => 'Timestamp out of valid range'];
|
1400 |
ariadna |
59 |
} */
|
1388 |
ariadna |
60 |
|
1399 |
ariadna |
61 |
if (!password_verify($username . '-' . LLWS_PASSWORD . '-' . $rand . '-' . $timestamp, $password)) {
|
|
|
62 |
return ['error' => 'ERROR_SECURITY5', 'message' => 'Invalid password'];
|
|
|
63 |
}
|
1388 |
ariadna |
64 |
|
1399 |
ariadna |
65 |
return [
|
|
|
66 |
'username' => $username,
|
|
|
67 |
'password' => $password,
|
|
|
68 |
'timestamp' => $timestamp,
|
|
|
69 |
'rand' => $rand,
|
|
|
70 |
'data' => $data
|
|
|
71 |
];
|
96 |
efrain |
72 |
}
|
|
|
73 |
|
1399 |
ariadna |
74 |
/**
|
|
|
75 |
* Procesa y decodifica los datos de la petición
|
|
|
76 |
* @param string $data Datos encriptados
|
|
|
77 |
* @return array|false Array con los datos decodificados o false si hay error
|
|
|
78 |
*/
|
|
|
79 |
function processRequestData($data)
|
|
|
80 |
{
|
|
|
81 |
if (empty($data)) {
|
|
|
82 |
return ['error' => 'ERROR_PARAMETERS1', 'message' => 'No data provided'];
|
|
|
83 |
}
|
96 |
efrain |
84 |
|
1399 |
ariadna |
85 |
$data = base64_decode($data);
|
|
|
86 |
if (empty($data)) {
|
|
|
87 |
return ['error' => 'ERROR_PARAMETERS2', 'message' => 'Invalid base64 data'];
|
|
|
88 |
}
|
96 |
efrain |
89 |
|
1399 |
ariadna |
90 |
try {
|
|
|
91 |
$rsa = new rsa();
|
|
|
92 |
$rsa->setKeys(LLWS_RSA_N, LLWS_RSA_D, LLWS_RSA_E);
|
|
|
93 |
$data = $rsa->decrypt($data);
|
|
|
94 |
} catch (Throwable $e) {
|
|
|
95 |
return ['error' => 'ERROR_PARAMETERS3', 'message' => 'Decryption failed'];
|
|
|
96 |
}
|
96 |
efrain |
97 |
|
1399 |
ariadna |
98 |
$data = (array) json_decode($data);
|
|
|
99 |
if (empty($data)) {
|
|
|
100 |
return ['error' => 'ERROR_PARAMETERS4', 'message' => 'Invalid JSON data'];
|
|
|
101 |
}
|
96 |
efrain |
102 |
|
1399 |
ariadna |
103 |
$email = trim(isset($data['email']) ? filter_var($data['email'], FILTER_SANITIZE_EMAIL) : '');
|
|
|
104 |
$first_name = trim(isset($data['first_name']) ? filter_var($data['first_name'], FILTER_SANITIZE_STRING) : '');
|
|
|
105 |
$last_name = trim(isset($data['last_name']) ? filter_var($data['last_name'], FILTER_SANITIZE_STRING) : '');
|
96 |
efrain |
106 |
|
1399 |
ariadna |
107 |
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
|
|
|
108 |
return ['error' => 'ERROR_PARAMETERS5', 'message' => 'Invalid user data'];
|
|
|
109 |
}
|
96 |
efrain |
110 |
|
1399 |
ariadna |
111 |
return [
|
|
|
112 |
'email' => $email,
|
|
|
113 |
'first_name' => $first_name,
|
|
|
114 |
'last_name' => $last_name,
|
|
|
115 |
'image_filename' => trim(isset($data['image_filename']) ? filter_var($data['image_filename'], FILTER_SANITIZE_STRING) : ''),
|
|
|
116 |
'image_content' => trim(isset($data['image_content']) ? filter_var($data['image_content'], FILTER_SANITIZE_STRING) : '')
|
|
|
117 |
];
|
96 |
efrain |
118 |
}
|
|
|
119 |
|
1399 |
ariadna |
120 |
/**
|
|
|
121 |
* Gestiona la creación o actualización del usuario
|
|
|
122 |
* @param array $userData Datos del usuario
|
|
|
123 |
* @return array|false Array con el usuario o false si hay error
|
|
|
124 |
*/
|
|
|
125 |
function manageUser($userData)
|
|
|
126 |
{
|
|
|
127 |
global $DB;
|
1383 |
ariadna |
128 |
|
1399 |
ariadna |
129 |
$user = ll_get_user_by_email($userData['email']);
|
|
|
130 |
if ($user) {
|
|
|
131 |
return ['user' => $user, 'is_new' => false];
|
|
|
132 |
}
|
96 |
efrain |
133 |
|
1399 |
ariadna |
134 |
$username = ll_get_username_available($userData['first_name'], $userData['last_name']);
|
|
|
135 |
$user = ll_create_user($username, $userData['email'], $userData['first_name'], $userData['last_name']);
|
96 |
efrain |
136 |
|
1399 |
ariadna |
137 |
if (!$user) {
|
|
|
138 |
return ['error' => 'ERROR_MOODLE1', 'message' => 'Failed to create user'];
|
|
|
139 |
}
|
96 |
efrain |
140 |
|
1399 |
ariadna |
141 |
if ($userData['image_filename'] && $userData['image_content']) {
|
|
|
142 |
$tempfile = __DIR__ . DIRECTORY_SEPARATOR . $userData['image_filename'];
|
|
|
143 |
try {
|
|
|
144 |
file_put_contents($tempfile, base64_decode($userData['image_content']));
|
|
|
145 |
if (file_exists($tempfile)) {
|
|
|
146 |
$usericonid = process_new_icon(context_user::instance($user->id, MUST_EXIST), 'user', 'icon', 0, $tempfile);
|
|
|
147 |
if ($usericonid) {
|
|
|
148 |
$DB->set_field('user', 'picture', $usericonid, array('id' => $user->id));
|
96 |
efrain |
149 |
}
|
|
|
150 |
}
|
1399 |
ariadna |
151 |
} catch (\Throwable $e) {
|
|
|
152 |
// Log error but continue
|
|
|
153 |
} finally {
|
|
|
154 |
if (file_exists($tempfile)) {
|
|
|
155 |
unlink($tempfile);
|
|
|
156 |
}
|
96 |
efrain |
157 |
}
|
|
|
158 |
}
|
|
|
159 |
|
1399 |
ariadna |
160 |
return ['user' => $user, 'is_new' => true];
|
1383 |
ariadna |
161 |
}
|
96 |
efrain |
162 |
|
1399 |
ariadna |
163 |
/**
|
|
|
164 |
* Gestiona la inscripción en cursos
|
|
|
165 |
* @param object $user Usuario a inscribir
|
|
|
166 |
* @return bool True si la inscripción fue exitosa
|
|
|
167 |
*/
|
|
|
168 |
function manageCourseEnrollment($user)
|
|
|
169 |
{
|
|
|
170 |
global $DB;
|
|
|
171 |
|
96 |
efrain |
172 |
$role = $DB->get_record('role', array('archetype' => 'student'));
|
|
|
173 |
$enrolmethod = 'manual';
|
1383 |
ariadna |
174 |
|
96 |
efrain |
175 |
$courses = get_courses();
|
1383 |
ariadna |
176 |
foreach ($courses as $course) {
|
|
|
177 |
if ($course->categoy_id == LLWS_CATEGORY_ID) {
|
96 |
efrain |
178 |
$context = context_course::instance($course->id);
|
|
|
179 |
if (!is_enrolled($context, $user)) {
|
|
|
180 |
$enrol = enrol_get_plugin($enrolmethod);
|
|
|
181 |
if ($enrol === null) {
|
1399 |
ariadna |
182 |
continue;
|
96 |
efrain |
183 |
}
|
|
|
184 |
$instances = enrol_get_instances($course->id, true);
|
|
|
185 |
$manualinstance = null;
|
|
|
186 |
foreach ($instances as $instance) {
|
|
|
187 |
if ($instance->name == $enrolmethod) {
|
|
|
188 |
$manualinstance = $instance;
|
|
|
189 |
break;
|
|
|
190 |
}
|
|
|
191 |
}
|
|
|
192 |
if ($manualinstance !== null) {
|
|
|
193 |
$instanceid = $enrol->add_default_instance($course);
|
|
|
194 |
if ($instanceid === null) {
|
|
|
195 |
$instanceid = $enrol->add_instance($course);
|
|
|
196 |
}
|
|
|
197 |
$instance = $DB->get_record('enrol', array('id' => $instanceid));
|
1383 |
ariadna |
198 |
if ($instance) {
|
96 |
efrain |
199 |
$enrol->enrol_user($instance, $user->id, $role->id);
|
|
|
200 |
}
|
|
|
201 |
}
|
|
|
202 |
}
|
|
|
203 |
}
|
|
|
204 |
}
|
1399 |
ariadna |
205 |
return true;
|
96 |
efrain |
206 |
}
|
|
|
207 |
|
1399 |
ariadna |
208 |
/**
|
|
|
209 |
* Gestiona el inicio de sesión del usuario
|
|
|
210 |
* @param object $user Usuario a iniciar sesión
|
|
|
211 |
* @return array|false Array con los datos de la sesión o false si hay error
|
|
|
212 |
*/
|
|
|
213 |
function manageUserSession($user)
|
|
|
214 |
{
|
|
|
215 |
global $CFG, $SESSION;
|
|
|
216 |
|
|
|
217 |
// Cerrar sesión existente si la hay
|
1392 |
ariadna |
218 |
if (isloggedin()) {
|
|
|
219 |
require_logout();
|
|
|
220 |
}
|
|
|
221 |
|
1399 |
ariadna |
222 |
// Limpiar todas las cookies de sesión
|
|
|
223 |
if (isset($_COOKIE)) {
|
|
|
224 |
foreach ($_COOKIE as $name => $value) {
|
|
|
225 |
setcookie($name, '', time() - 3600, '/');
|
|
|
226 |
unset($_COOKIE[$name]);
|
|
|
227 |
}
|
|
|
228 |
}
|
|
|
229 |
|
|
|
230 |
// Limpiar la cookie de Moodle específicamente
|
|
|
231 |
set_moodle_cookie('');
|
|
|
232 |
|
1392 |
ariadna |
233 |
if (empty($user->confirmed)) {
|
1399 |
ariadna |
234 |
return ['error' => 'ACCOUNT_NOT_CONFIRMED', 'message' => 'Account not confirmed'];
|
1392 |
ariadna |
235 |
}
|
|
|
236 |
|
|
|
237 |
$userauth = get_auth_plugin($user->auth);
|
|
|
238 |
if (!isguestuser() && !empty($userauth->config->expiration) && $userauth->config->expiration == 1) {
|
|
|
239 |
$days2expire = $userauth->password_expire($user->username);
|
|
|
240 |
if (intval($days2expire) < 0) {
|
1399 |
ariadna |
241 |
return ['error' => 'PASSWORD_EXPIRED', 'message' => 'Password has expired'];
|
1391 |
ariadna |
242 |
}
|
1392 |
ariadna |
243 |
}
|
1391 |
ariadna |
244 |
|
1392 |
ariadna |
245 |
complete_user_login($user);
|
|
|
246 |
\core\session\manager::apply_concurrent_login_limit($user->id, session_id());
|
1391 |
ariadna |
247 |
|
1392 |
ariadna |
248 |
if (!empty($CFG->nolastloggedin)) {
|
|
|
249 |
// No almacenar último usuario conectado en cookie
|
|
|
250 |
} else if (empty($CFG->rememberusername)) {
|
|
|
251 |
set_moodle_cookie('');
|
|
|
252 |
} else {
|
|
|
253 |
set_moodle_cookie($user->username);
|
|
|
254 |
}
|
1391 |
ariadna |
255 |
|
1392 |
ariadna |
256 |
unset($SESSION->loginerrormsg);
|
|
|
257 |
unset($SESSION->logininfomsg);
|
|
|
258 |
unset($SESSION->loginredirect);
|
1391 |
ariadna |
259 |
|
1398 |
ariadna |
260 |
$urltogo = $CFG->wwwroot . '/my';
|
|
|
261 |
$SESSION->wantsurl = $urltogo;
|
1391 |
ariadna |
262 |
|
1398 |
ariadna |
263 |
if (isloggedin() && !isguestuser()) {
|
1399 |
ariadna |
264 |
return [
|
1398 |
ariadna |
265 |
'success' => true,
|
|
|
266 |
'data' => [
|
|
|
267 |
'userid' => $user->id,
|
|
|
268 |
'username' => $user->username,
|
|
|
269 |
'fullname' => fullname($user),
|
|
|
270 |
'email' => $user->email,
|
|
|
271 |
'redirect' => $urltogo
|
|
|
272 |
]
|
1399 |
ariadna |
273 |
];
|
|
|
274 |
}
|
1398 |
ariadna |
275 |
|
1399 |
ariadna |
276 |
return ['error' => 'LOGIN_FAILED', 'message' => 'Login failed'];
|
|
|
277 |
}
|
|
|
278 |
|
|
|
279 |
// Procesamiento principal
|
|
|
280 |
$securityResult = validateSecurityParams($_REQUEST);
|
|
|
281 |
if (isset($securityResult['error'])) {
|
|
|
282 |
echo json_encode(['success' => false, 'data' => $securityResult['error']]);
|
|
|
283 |
exit;
|
|
|
284 |
}
|
|
|
285 |
|
|
|
286 |
$dataResult = processRequestData($securityResult['data']);
|
|
|
287 |
if (isset($dataResult['error'])) {
|
|
|
288 |
echo json_encode(['success' => false, 'data' => $dataResult['error']]);
|
|
|
289 |
exit;
|
|
|
290 |
}
|
|
|
291 |
|
|
|
292 |
$userResult = manageUser($dataResult);
|
|
|
293 |
if (isset($userResult['error'])) {
|
|
|
294 |
echo json_encode(['success' => false, 'data' => $userResult['error']]);
|
|
|
295 |
exit;
|
|
|
296 |
}
|
|
|
297 |
|
|
|
298 |
if ($userResult['is_new']) {
|
|
|
299 |
manageCourseEnrollment($userResult['user']);
|
|
|
300 |
}
|
|
|
301 |
|
|
|
302 |
$user = get_complete_user_data('id', $userResult['user']->id);
|
|
|
303 |
if (!$user) {
|
1391 |
ariadna |
304 |
echo json_encode(['success' => false, 'data' => 'USER_NOT_FOUND']);
|
1399 |
ariadna |
305 |
exit;
|
96 |
efrain |
306 |
}
|
1399 |
ariadna |
307 |
|
|
|
308 |
$sessionResult = manageUserSession($user);
|
|
|
309 |
if (isset($sessionResult['error'])) {
|
|
|
310 |
echo json_encode(['success' => false, 'data' => $sessionResult['error']]);
|
|
|
311 |
exit;
|
|
|
312 |
}
|
|
|
313 |
|
|
|
314 |
echo json_encode($sessionResult);
|
|
|
315 |
redirect($sessionResult['data']['redirect']);
|
1388 |
ariadna |
316 |
exit;
|