Proyectos de Subversion LeadersLinked - Services

Rev

Rev 616 | Rev 756 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Controller;
6
 
7
use Nullix\CryptoJsAes\CryptoJsAes;
8
use GeoIp2\Database\Reader as GeoIp2Reader;
9
 
10
use Laminas\Authentication\AuthenticationService;
11
use Laminas\Authentication\Result as AuthResult;
12
use Laminas\Mvc\Controller\AbstractActionController;
13
use Laminas\View\Model\JsonModel;
14
 
283 www 15
 
1 efrain 16
use LeadersLinked\Form\Auth\SigninForm;
17
use LeadersLinked\Form\Auth\ResetPasswordForm;
18
use LeadersLinked\Form\Auth\ForgotPasswordForm;
19
use LeadersLinked\Form\Auth\SignupForm;
20
 
21
use LeadersLinked\Mapper\ConnectionMapper;
22
use LeadersLinked\Mapper\EmailTemplateMapper;
23
use LeadersLinked\Mapper\NetworkMapper;
24
use LeadersLinked\Mapper\UserMapper;
25
 
26
use LeadersLinked\Model\User;
27
use LeadersLinked\Model\UserType;
28
use LeadersLinked\Library\QueueEmail;
29
use LeadersLinked\Library\Functions;
30
use LeadersLinked\Model\EmailTemplate;
31
use LeadersLinked\Mapper\UserPasswordMapper;
32
use LeadersLinked\Model\UserBrowser;
33
use LeadersLinked\Mapper\UserBrowserMapper;
34
use LeadersLinked\Mapper\UserIpMapper;
35
use LeadersLinked\Model\UserIp;
36
use LeadersLinked\Form\Auth\MoodleForm;
37
use LeadersLinked\Library\Rsa;
38
use LeadersLinked\Library\Image;
39
 
40
use LeadersLinked\Authentication\AuthAdapter;
41
use LeadersLinked\Authentication\AuthEmailAdapter;
42
 
43
use LeadersLinked\Model\UserPassword;
44
 
45
use LeadersLinked\Model\Connection;
46
use LeadersLinked\Authentication\AuthImpersonateAdapter;
47
use LeadersLinked\Model\Network;
23 efrain 48
use LeadersLinked\Model\JwtToken;
49
use LeadersLinked\Mapper\JwtTokenMapper;
50
use Firebase\JWT\JWT;
24 efrain 51
use Firebase\JWT\Key;
211 efrain 52
use LeadersLinked\Form\Auth\SigninDebugForm;
257 efrain 53
use LeadersLinked\Library\ExternalCredentials;
283 www 54
use LeadersLinked\Library\Storage;
1 efrain 55
 
56
 
57
 
58
class AuthController extends AbstractActionController
59
{
283 www 60
 
616 ariadna 61
 
1 efrain 62
    /**
63
     *
64
     * @var \Laminas\Db\Adapter\AdapterInterface
65
     */
66
    private $adapter;
616 ariadna 67
 
1 efrain 68
    /**
69
     *
70
     * @var \LeadersLinked\Cache\CacheInterface
71
     */
72
    private $cache;
616 ariadna 73
 
74
 
1 efrain 75
    /**
76
     *
77
     * @var \Laminas\Log\LoggerInterface
78
     */
79
    private $logger;
616 ariadna 80
 
1 efrain 81
    /**
82
     *
83
     * @var array
84
     */
85
    private $config;
616 ariadna 86
 
87
 
1 efrain 88
    /**
89
     *
90
     * @var \Laminas\Mvc\I18n\Translator
91
     */
92
    private $translator;
616 ariadna 93
 
94
 
1 efrain 95
    /**
96
     *
97
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
98
     * @param \LeadersLinked\Cache\CacheInterface $cache
99
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
100
     * @param array $config
101
     * @param \Laminas\Mvc\I18n\Translator $translator
102
     */
103
    public function __construct($adapter, $cache, $logger, $config, $translator)
104
    {
105
        $this->adapter      = $adapter;
106
        $this->cache        = $cache;
107
        $this->logger       = $logger;
108
        $this->config       = $config;
109
        $this->translator   = $translator;
110
    }
111
 
112
    public function signinAction()
113
    {
114
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
115
        $currentNetwork = $currentNetworkPlugin->getNetwork();
116
 
117
        $request = $this->getRequest();
118
 
755 stevensc 119
        $this->logger->info('Ingreso a LeadersLiked', ['currentNetwork' => $currentNetwork]);
120
 
1 efrain 121
        if ($request->isPost()) {
122
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
123
            $currentNetwork = $currentNetworkPlugin->getNetwork();
616 ariadna 124
 
24 efrain 125
            $jwtToken = null;
126
            $headers = getallheaders();
53 efrain 127
 
616 ariadna 128
 
129
            if (!empty($headers['authorization']) || !empty($headers['Authorization'])) {
130
 
34 efrain 131
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
616 ariadna 132
 
133
 
134
                if (substr($token, 0, 6) == 'Bearer') {
135
 
24 efrain 136
                    $token = trim(substr($token, 7));
616 ariadna 137
 
138
                    if (!empty($this->config['leaderslinked.jwt.key'])) {
24 efrain 139
                        $key = $this->config['leaderslinked.jwt.key'];
616 ariadna 140
 
141
 
24 efrain 142
                        try {
143
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
616 ariadna 144
 
145
 
146
                            if (empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
24 efrain 147
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
148
                            }
616 ariadna 149
 
24 efrain 150
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
151
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
152
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
616 ariadna 153
                            if (!$jwtToken) {
24 efrain 154
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
155
                            }
616 ariadna 156
                        } catch (\Exception $e) {
24 efrain 157
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
158
                        }
159
                    } else {
160
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
161
                    }
162
                } else {
163
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
164
                }
165
            } else {
166
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
167
            }
1 efrain 168
 
24 efrain 169
 
249 efrain 170
 
1 efrain 171
            $form = new  SigninForm($this->config);
172
            $dataPost = $request->getPost()->toArray();
144 efrain 173
 
1 efrain 174
            if (empty($_SESSION['aes'])) {
175
                return new JsonModel([
176
                    'success'   => false,
177
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
178
                ]);
179
            }
616 ariadna 180
 
181
 
249 efrain 182
            $aes = $_SESSION['aes'];
616 ariadna 183
            unset($_SESSION['aes']);
184
 
1 efrain 185
            if (!empty($dataPost['email'])) {
249 efrain 186
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $aes);
1 efrain 187
            }
188
 
189
 
190
            if (!empty($dataPost['password'])) {
249 efrain 191
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $aes);
144 efrain 192
            }
616 ariadna 193
 
194
 
1 efrain 195
            $form->setData($dataPost);
196
 
197
            if ($form->isValid()) {
616 ariadna 198
 
1 efrain 199
                $dataPost = (array) $form->getData();
200
 
616 ariadna 201
 
1 efrain 202
                $email      = $dataPost['email'];
203
                $password   = $dataPost['password'];
204
 
616 ariadna 205
 
206
 
207
 
208
 
1 efrain 209
                $authAdapter = new AuthAdapter($this->adapter, $this->logger);
255 efrain 210
                $authAdapter->setData($email, $password, $currentNetwork->id);
1 efrain 211
                $authService = new AuthenticationService();
212
 
213
                $result = $authService->authenticate($authAdapter);
214
 
215
                if ($result->getCode() == AuthResult::SUCCESS) {
216
 
155 efrain 217
                    $identity = $result->getIdentity();
1 efrain 218
 
616 ariadna 219
 
1 efrain 220
                    $userMapper = UserMapper::getInstance($this->adapter);
155 efrain 221
                    $user = $userMapper->fetchOne($identity['user_id']);
616 ariadna 222
 
223
 
224
                    if ($token) {
37 efrain 225
                        $jwtToken->user_id = $user->id;
36 efrain 226
                        $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
37 efrain 227
                        $jwtTokenMapper->update($jwtToken);
36 efrain 228
                    }
1 efrain 229
 
616 ariadna 230
 
1 efrain 231
                    $navigator = get_browser(null, true);
232
                    $device_type    =  isset($navigator['device_type']) ? $navigator['device_type'] : '';
233
                    $platform       =  isset($navigator['platform']) ? $navigator['platform'] : '';
234
                    $browser        =  isset($navigator['browser']) ? $navigator['browser'] : '';
235
 
236
 
237
                    $istablet = isset($navigator['istablet']) ?  intval($navigator['istablet']) : 0;
238
                    $ismobiledevice = isset($navigator['ismobiledevice']) ? intval($navigator['ismobiledevice']) : 0;
239
                    $version = isset($navigator['version']) ? $navigator['version'] : '';
240
 
241
 
242
                    $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
243
                    $userBrowser = $userBrowserMapper->fetch($user->id, $device_type, $platform, $browser);
244
                    if ($userBrowser) {
245
                        $userBrowserMapper->update($userBrowser);
246
                    } else {
247
                        $userBrowser = new UserBrowser();
248
                        $userBrowser->user_id           = $user->id;
249
                        $userBrowser->browser           = $browser;
250
                        $userBrowser->platform          = $platform;
251
                        $userBrowser->device_type       = $device_type;
252
                        $userBrowser->is_tablet         = $istablet;
253
                        $userBrowser->is_mobile_device  = $ismobiledevice;
254
                        $userBrowser->version           = $version;
255
 
256
                        $userBrowserMapper->insert($userBrowser);
257
                    }
258
                    //
259
 
260
                    $ip = Functions::getUserIP();
261
                    $ip = $ip == '127.0.0.1' ? '148.240.211.148' : $ip;
262
 
263
                    $userIpMapper = UserIpMapper::getInstance($this->adapter);
264
                    $userIp = $userIpMapper->fetch($user->id, $ip);
265
                    if (empty($userIp)) {
266
 
267
                        if ($this->config['leaderslinked.runmode.sandbox']) {
268
                            $filename = $this->config['leaderslinked.geoip2.production_database'];
269
                        } else {
270
                            $filename = $this->config['leaderslinked.geoip2.sandbox_database'];
271
                        }
272
 
273
                        $reader = new GeoIp2Reader($filename); //GeoIP2-City.mmdb');
274
                        $record = $reader->city($ip);
275
                        if ($record) {
276
                            $userIp = new UserIp();
277
                            $userIp->user_id = $user->id;
278
                            $userIp->city = !empty($record->city->name) ? Functions::utf8_decode($record->city->name) : '';
279
                            $userIp->state_code = !empty($record->mostSpecificSubdivision->isoCode) ? Functions::utf8_decode($record->mostSpecificSubdivision->isoCode) : '';
280
                            $userIp->state_name = !empty($record->mostSpecificSubdivision->name) ? Functions::utf8_decode($record->mostSpecificSubdivision->name) : '';
281
                            $userIp->country_code = !empty($record->country->isoCode) ? Functions::utf8_decode($record->country->isoCode) : '';
282
                            $userIp->country_name = !empty($record->country->name) ? Functions::utf8_decode($record->country->name) : '';
283
                            $userIp->ip = $ip;
284
                            $userIp->latitude = !empty($record->location->latitude) ? $record->location->latitude : 0;
285
                            $userIp->longitude = !empty($record->location->longitude) ? $record->location->longitude : 0;
286
                            $userIp->postal_code = !empty($record->postal->code) ? $record->postal->code : '';
287
 
288
                            $userIpMapper->insert($userIp);
289
                        }
290
                    } else {
291
                        $userIpMapper->update($userIp);
292
                    }
293
 
24 efrain 294
                    /*
1 efrain 295
                    if ($remember) {
296
                        $expired = time() + 365 * 24 * 60 * 60;
297
 
298
                        $cookieEmail = new SetCookie('email', $email, $expired);
299
                    } else {
300
                        $expired = time() - 7200;
301
                        $cookieEmail = new SetCookie('email', '', $expired);
302
                    }
303
 
304
 
305
                    $response = $this->getResponse();
306
                    $response->getHeaders()->addHeader($cookieEmail);
24 efrain 307
                    */
1 efrain 308
 
309
 
310
 
616 ariadna 311
 
312
 
1 efrain 313
                    $this->logger->info('Ingreso a LeadersLiked', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
314
 
315
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
316
 
256 efrain 317
                    $url =  $this->url()->fromRoute('dashboard');
616 ariadna 318
 
256 efrain 319
                    if ($user_share_invitation && is_array($user_share_invitation)) {
616 ariadna 320
 
256 efrain 321
                        $content_uuid = $user_share_invitation['code'];
322
                        $content_type = $user_share_invitation['type'];
323
                        $content_user = $user_share_invitation['user'];
616 ariadna 324
 
325
 
326
 
256 efrain 327
                        $userRedirect = $userMapper->fetchOneByUuid($content_user);
1 efrain 328
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
329
                            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
330
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
331
 
332
                            if ($connection) {
333
 
334
                                if ($connection->status != Connection::STATUS_ACCEPTED) {
335
                                    $connectionMapper->approve($connection);
336
                                }
337
                            } else {
338
                                $connection = new Connection();
339
                                $connection->request_from = $user->id;
340
                                $connection->request_to = $userRedirect->id;
341
                                $connection->status = Connection::STATUS_ACCEPTED;
342
 
343
                                $connectionMapper->insert($connection);
344
                            }
345
                        }
616 ariadna 346
 
347
                        if ($content_type == 'feed') {
348
                            $url = $this->url()->fromRoute('dashboard', ['feed' => $content_uuid]);
349
                        } else if ($content_type == 'post') {
350
                            $url = $this->url()->fromRoute('post', ['id' => $content_uuid]);
351
                        } else {
256 efrain 352
                            $url = $this->url()->fromRoute('dashboard');
353
                        }
1 efrain 354
                    }
616 ariadna 355
 
356
 
256 efrain 357
                    $hostname = empty($_SERVER['HTTP_HOST']) ?  '' : $_SERVER['HTTP_HOST'];
616 ariadna 358
 
256 efrain 359
                    $networkMapper = NetworkMapper::getInstance($this->adapter);
360
                    $network = $networkMapper->fetchOneByHostnameForFrontend($hostname);
616 ariadna 361
 
362
                    if (!$network) {
256 efrain 363
                        $network = $networkMapper->fetchOneByDefault();
364
                    }
616 ariadna 365
 
256 efrain 366
                    $hostname = trim($network->main_hostname);
367
                    $url = 'https://' . $hostname . $url;
1 efrain 368
 
616 ariadna 369
 
257 efrain 370
                    $data = [
313 www 371
                        'redirect'  => $url,
372
                        'uuid'      => $user->uuid,
257 efrain 373
                    ];
1 efrain 374
 
616 ariadna 375
 
376
 
377
 
378
                    if ($currentNetwork->xmpp_active) {
257 efrain 379
                        $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
380
                        $externalCredentials->getUserBy($user->id);
616 ariadna 381
 
382
 
257 efrain 383
                        $data['xmpp_domain'] = $currentNetwork->xmpp_domain;
384
                        $data['xmpp_hostname'] = $currentNetwork->xmpp_hostname;
385
                        $data['xmpp_port'] = $currentNetwork->xmpp_port;
386
                        $data['xmpp_username'] = $externalCredentials->getUsernameXmpp();
387
                        $data['xmpp_pasword'] = $externalCredentials->getPasswordXmpp();
266 efrain 388
                        $data['inmail_username'] = $externalCredentials->getUsernameInmail();
389
                        $data['inmail_pasword'] = $externalCredentials->getPasswordInmail();
616 ariadna 390
                    }
266 efrain 391
 
1 efrain 392
                    $data = [
393
                        'success'   => true,
257 efrain 394
                        'data'      => $data
1 efrain 395
                    ];
396
 
616 ariadna 397
 
1 efrain 398
                    $this->cache->removeItem('user_share_invitation');
399
                } else {
400
 
401
                    $message = $result->getMessages()[0];
402
                    if (!in_array($message, [
616 ariadna 403
                        'ERROR_USER_NOT_FOUND',
404
                        'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED',
405
                        'ERROR_USER_IS_BLOCKED',
406
                        'ERROR_USER_IS_INACTIVE',
407
                        'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED',
408
                        'ERROR_ENTERED_PASS_INCORRECT_2',
409
                        'ERROR_ENTERED_PASS_INCORRECT_1',
410
                        'ERROR_USER_REQUEST_ACCESS_IS_PENDING',
411
                        'ERROR_USER_REQUEST_ACCESS_IS_REJECTED'
1 efrain 412
 
413
 
414
                    ])) {
415
                    }
416
 
417
                    switch ($message) {
418
                        case 'ERROR_USER_NOT_FOUND':
419
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
420
                            break;
421
 
422
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
423
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
424
                            break;
425
 
426
                        case 'ERROR_USER_IS_BLOCKED':
427
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
428
                            break;
429
 
430
                        case 'ERROR_USER_IS_INACTIVE':
431
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
432
                            break;
433
 
434
 
435
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
436
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
437
                            break;
438
 
439
 
440
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
441
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
442
                            break;
443
 
444
 
445
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
446
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
447
                            break;
448
 
449
 
450
                        case 'ERROR_USER_REQUEST_ACCESS_IS_PENDING':
451
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Falta verificar que pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
452
                            break;
453
 
454
                        case  'ERROR_USER_REQUEST_ACCESS_IS_REJECTED':
455
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Rechazado por no pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
456
                            break;
457
 
458
 
459
                        default:
460
                            $message = 'ERROR_UNKNOWN';
461
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
462
                            break;
463
                    }
464
 
465
 
466
 
467
 
468
                    $data = [
469
                        'success'   => false,
470
                        'data'   => $message
471
                    ];
472
                }
473
 
67 efrain 474
                return new JsonModel($data);
1 efrain 475
            } else {
476
                $messages = [];
477
 
478
 
479
 
480
                $form_messages = (array) $form->getMessages();
481
                foreach ($form_messages  as $fieldname => $field_messages) {
482
 
483
                    $messages[$fieldname] = array_values($field_messages);
484
                }
67 efrain 485
 
486
                return new JsonModel([
1 efrain 487
                    'success'   => false,
488
                    'data'   => $messages
67 efrain 489
                ]);
1 efrain 490
            }
491
        } else if ($request->isGet()) {
616 ariadna 492
 
120 efrain 493
            $aes = '';
107 efrain 494
            $jwtToken = null;
495
            $headers = getallheaders();
616 ariadna 496
 
497
 
498
            if (!empty($headers['authorization']) || !empty($headers['Authorization'])) {
499
 
107 efrain 500
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
616 ariadna 501
 
502
 
503
                if (substr($token, 0, 6) == 'Bearer') {
504
 
107 efrain 505
                    $token = trim(substr($token, 7));
616 ariadna 506
 
507
                    if (!empty($this->config['leaderslinked.jwt.key'])) {
107 efrain 508
                        $key = $this->config['leaderslinked.jwt.key'];
616 ariadna 509
 
510
 
107 efrain 511
                        try {
512
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
616 ariadna 513
 
514
 
515
                            if (empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
107 efrain 516
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
517
                            }
616 ariadna 518
 
107 efrain 519
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
520
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
521
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
616 ariadna 522
                        } catch (\Exception $e) {
107 efrain 523
                            //Token invalido
524
                        }
525
                    }
526
                }
1 efrain 527
            }
616 ariadna 528
 
529
            if (!$jwtToken) {
530
 
107 efrain 531
                $aes = Functions::generatePassword(16);
616 ariadna 532
 
107 efrain 533
                $jwtToken = new JwtToken();
534
                $jwtToken->aes = $aes;
616 ariadna 535
 
107 efrain 536
                $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
616 ariadna 537
                if ($jwtTokenMapper->insert($jwtToken)) {
107 efrain 538
                    $jwtToken = $jwtTokenMapper->fetchOne($jwtToken->id);
539
                }
616 ariadna 540
 
107 efrain 541
                $token = '';
616 ariadna 542
 
543
                if (!empty($this->config['leaderslinked.jwt.key'])) {
107 efrain 544
                    $issuedAt   = new \DateTimeImmutable();
249 efrain 545
                    $expire     = $issuedAt->modify('+365 days')->getTimestamp();
107 efrain 546
                    $serverName = $_SERVER['HTTP_HOST'];
547
                    $payload = [
548
                        'iat'  => $issuedAt->getTimestamp(),
549
                        'iss'  => $serverName,
550
                        'nbf'  => $issuedAt->getTimestamp(),
551
                        'exp'  => $expire,
552
                        'uuid' => $jwtToken->uuid,
553
                    ];
616 ariadna 554
 
555
 
107 efrain 556
                    $key = $this->config['leaderslinked.jwt.key'];
557
                    $token = JWT::encode($payload, $key, 'HS256');
558
                }
344 www 559
            } else {
616 ariadna 560
                if (!$jwtToken->user_id) {
344 www 561
                    $aes = Functions::generatePassword(16);
562
                    $jwtToken->aes = $aes;
563
                    $jwtTokenMapper->update($jwtToken);
564
                }
23 efrain 565
            }
1 efrain 566
 
23 efrain 567
 
616 ariadna 568
 
569
 
570
 
571
 
572
 
1 efrain 573
            if ($this->config['leaderslinked.runmode.sandbox']) {
574
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
575
            } else {
576
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
577
            }
578
 
579
 
580
            $access_usign_social_networks = $this->config['leaderslinked.runmode.access_usign_social_networks'];
581
 
582
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
583
            if ($sandbox) {
584
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
585
            } else {
586
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
587
            }
588
 
616 ariadna 589
 
189 efrain 590
            $parts = explode('.', $currentNetwork->main_hostname);
616 ariadna 591
            if ($parts[1] === 'com') {
189 efrain 592
                $replace_main = false;
593
            } else {
594
                $replace_main = true;
595
            }
283 www 596
 
1 efrain 597
 
616 ariadna 598
            $storage = Storage::getInstance($this->config, $this->adapter);
599
            $path = $storage->getPathNetwork();
151 efrain 600
 
616 ariadna 601
            if ($currentNetwork->logo) {
602
                $logo_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->logo);
603
            } else {
604
                $logo_url = '';
605
            }
606
 
607
            if ($currentNetwork->navbar) {
608
                $navbar_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->navbar);
609
            } else {
610
                $navbar_url = '';
611
            }
612
 
613
            if ($currentNetwork->favico) {
614
                $favico_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->favico);
615
            } else {
616
                $favico_url = '';
617
            }
618
 
619
 
620
 
621
 
1 efrain 622
            $data = [
23 efrain 623
                'google_map_key'                => $google_map_key,
624
                'email'                         => '',
625
                'remember'                      => false,
626
                'site_key'                      => $site_key,
627
                'theme_id'                      => $currentNetwork->theme_id,
628
                'aes'                           => $aes,
629
                'jwt'                           => $token,
630
                'defaultNetwork'                => $currentNetwork->default,
631
                'access_usign_social_networks'  => $access_usign_social_networks && $currentNetwork->default == Network::DEFAULT_YES ? 'y' : 'n',
148 efrain 632
                'logo_url'                      => $logo_url,
633
                'navbar_url'                    => $navbar_url,
634
                'favico_url'                    => $favico_url,
108 efrain 635
                'intro'                         => $currentNetwork->intro ? $currentNetwork->intro : '',
107 efrain 636
                'is_logged_in'                  => $jwtToken->user_id ? true : false,
1 efrain 637
            ];
616 ariadna 638
 
639
            if ($currentNetwork->default == Network::DEFAULT_YES) {
640
 
641
 
642
 
257 efrain 643
                $currentUserPlugin = $this->plugin('currentUserPlugin');
644
                if ($currentUserPlugin->hasIdentity()) {
616 ariadna 645
 
646
 
257 efrain 647
                    $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
648
                    $externalCredentials->getUserBy($currentUserPlugin->getUserId());
616 ariadna 649
 
650
 
651
                    if ($currentNetwork->xmpp_active) {
257 efrain 652
                        $data['xmpp_domain']      = $currentNetwork->xmpp_domain;
653
                        $data['xmpp_hostname']    = $currentNetwork->xmpp_hostname;
654
                        $data['xmpp_port']        = $currentNetwork->xmpp_port;
655
                        $data['xmpp_username']    = $externalCredentials->getUsernameXmpp();
656
                        $data['xmpp_password']    = $externalCredentials->getPasswordXmpp();
266 efrain 657
                        $data['inmail_username']    = $externalCredentials->getUsernameInmail();
658
                        $data['inmail_password']    = $externalCredentials->getPasswordInmail();
257 efrain 659
                    }
660
                }
661
            }
616 ariadna 662
 
49 efrain 663
            $data = [
664
                'success' => true,
50 efrain 665
                'data' =>  $data
49 efrain 666
            ];
1 efrain 667
        } else {
668
            $data = [
669
                'success' => false,
670
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
671
            ];
672
 
67 efrain 673
            return new JsonModel($data);
1 efrain 674
        }
675
 
67 efrain 676
        return new JsonModel($data);
1 efrain 677
    }
678
 
679
    public function facebookAction()
680
    {
681
 
682
        $request = $this->getRequest();
683
        if ($request->isGet()) {
684
            /*
685
          //  try {
686
                $app_id = $this->config['leaderslinked.facebook.app_id'];
687
                $app_password = $this->config['leaderslinked.facebook.app_password'];
688
                $app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];
689
                //$app_url_auth = $this->config['leaderslinked.facebook.app_url_auth'];
690
                //$redirect_url = $this->config['leaderslinked.facebook.app_redirect_url'];
691
 
692
                [facebook]
693
                app_id=343770226993130
694
                app_password=028ee729090fd591e50a17a786666c12
695
                app_graph_version=v17
696
                app_redirect_url=https://leaderslinked.com/oauth/facebook
697
 
698
                https://www.facebook.com/v17.0/dialog/oauth?client_id=343770226993130&redirect_uri= https://dev.leaderslinked.com/oauth/facebook&state=AE12345678
699
 
700
 
701
                $s = 'https://www.facebook.com/v17.0/dialog/oauth' .
702
                    '?client_id='
703
                    '&redirect_uri={"https://www.domain.com/login"}
704
                    '&state={"{st=state123abc,ds=123456789}"}
705
 
706
                $fb = new \Facebook\Facebook([
707
                    'app_id' => $app_id,
708
                    'app_secret' => $app_password,
709
                    'default_graph_version' => $app_graph_version,
710
                ]);
711
 
712
                $app_url_auth =  $this->url()->fromRoute('oauth/facebook', [], ['force_canonical' => true]);
713
                $helper = $fb->getRedirectLoginHelper();
714
                $permissions = ['email', 'public_profile']; // Optional permissions
715
                $facebookUrl = $helper->getLoginUrl($app_url_auth, $permissions);
716
 
717
 
718
 
719
                return new JsonModel([
720
                    'success' => false,
721
                    'data' => $facebookUrl
722
                ]);
723
            } catch (\Throwable $e) {
724
                return new JsonModel([
725
                    'success' => false,
726
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_FACEBOOK'
727
                ]);
728
            }*/
729
        } else {
730
            return new JsonModel([
731
                'success' => false,
732
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
733
            ]);
734
        }
735
    }
736
 
737
    public function twitterAction()
738
    {
739
        $request = $this->getRequest();
740
        if ($request->isGet()) {
741
 
742
            try {
743
                if ($this->config['leaderslinked.runmode.sandbox']) {
744
 
745
                    $twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];
746
                    $twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];
747
                } else {
748
                    $twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];
749
                    $twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];
750
                }
751
 
752
                /*
753
                 echo '$twitter_api_key = ' . $twitter_api_key . PHP_EOL;
754
                 echo '$twitter_api_secret = ' . $twitter_api_secret . PHP_EOL;
755
                 exit;
756
                 */
757
 
758
                //Twitter
759
                //$redirect_url =  $this->url()->fromRoute('oauth/twitter', [], ['force_canonical' => true]);
760
                $redirect_url = $this->config['leaderslinked.twitter.app_redirect_url'];
761
                $twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret);
762
                $request_token =  $twitter->oauth('oauth/request_token', ['oauth_callback' => $redirect_url]);
763
                $twitterUrl = $twitter->url('oauth/authorize', ['oauth_token' => $request_token['oauth_token']]);
764
 
765
                $twitterSession = new \Laminas\Session\Container('twitter');
766
                $twitterSession->oauth_token = $request_token['oauth_token'];
767
                $twitterSession->oauth_token_secret = $request_token['oauth_token_secret'];
768
 
769
                return new JsonModel([
770
                    'success' => true,
771
                    'data' =>  $twitterUrl
772
                ]);
773
            } catch (\Throwable $e) {
774
                return new JsonModel([
775
                    'success' => false,
776
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_TWITTER'
777
                ]);
778
            }
779
        } else {
780
            return new JsonModel([
781
                'success' => false,
782
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
783
            ]);
784
        }
785
    }
786
 
787
    public function googleAction()
788
    {
789
        $request = $this->getRequest();
790
        if ($request->isGet()) {
791
 
792
            try {
793
 
794
 
795
                //Google
796
                $google = new \Google_Client();
797
                $google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');
798
                $google->setAccessType("offline");        // offline access
799
 
800
                $google->setIncludeGrantedScopes(true);   // incremental auth
801
 
802
                $google->addScope('profile');
803
                $google->addScope('email');
804
 
805
                // $redirect_url =  $this->url()->fromRoute('oauth/google', [], ['force_canonical' => true]);
806
                $redirect_url = $this->config['leaderslinked.google_auth.app_redirect_url'];
807
 
808
                $google->setRedirectUri($redirect_url);
809
                $googleUrl = $google->createAuthUrl();
810
 
811
                return new JsonModel([
812
                    'success' => true,
813
                    'data' =>  $googleUrl
814
                ]);
815
            } catch (\Throwable $e) {
816
                return new JsonModel([
817
                    'success' => false,
818
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_GOOGLE'
819
                ]);
820
            }
821
        } else {
822
            return new JsonModel([
823
                'success' => false,
824
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
825
            ]);
826
        }
827
    }
828
 
829
    public function signoutAction()
830
    {
831
        $currentUserPlugin = $this->plugin('currentUserPlugin');
832
        $currentUser = $currentUserPlugin->getRawUser();
833
        if ($currentUserPlugin->hasImpersonate()) {
834
 
835
 
836
            $userMapper = UserMapper::getInstance($this->adapter);
837
            $userMapper->leaveImpersonate($currentUser->id);
838
 
839
            $networkMapper = NetworkMapper::getInstance($this->adapter);
840
            $network = $networkMapper->fetchOne($currentUser->network_id);
841
 
842
 
843
            if (!$currentUser->one_time_password) {
844
                $one_time_password = Functions::generatePassword(25);
845
 
846
                $currentUser->one_time_password = $one_time_password;
847
 
848
                $userMapper = UserMapper::getInstance($this->adapter);
849
                $userMapper->updateOneTimePassword($currentUser, $one_time_password);
850
            }
851
 
852
 
853
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
854
            if ($sandbox) {
855
                $salt = $this->config['leaderslinked.backend.sandbox_salt'];
856
            } else {
857
                $salt = $this->config['leaderslinked.backend.production_salt'];
858
            }
859
 
860
            $rand = 1000 + mt_rand(1, 999);
861
            $timestamp = time();
862
            $password = md5($currentUser->one_time_password . '-' . $rand . '-' . $timestamp . '-' . $salt);
863
 
864
            $params = [
865
                'user_uuid' => $currentUser->uuid,
866
                'password' => $password,
867
                'rand' => $rand,
868
                'time' => $timestamp,
869
            ];
870
 
871
            $currentUserPlugin->clearIdentity();
872
 
873
            return new JsonModel([
874
                'success'   => true,
875
                'data'      => [
876
                    'message' => 'LABEL_SIGNOUT_SUCCESSFULLY',
877
                    'url' => 'https://' . $network->main_hostname . '/signin/impersonate' . '?' . http_build_query($params)
616 ariadna 878
                ],
879
 
1 efrain 880
            ]);
616 ariadna 881
 
882
 
883
            // $url = 'https://' . $network->main_hostname . '/signin/impersonate' . '?' . http_build_query($params);
884
            // return $this->redirect()->toUrl($url);
1 efrain 885
        } else {
886
 
887
 
888
            if ($currentUserPlugin->hasIdentity()) {
889
 
890
                $this->logger->info('Desconexión de LeadersLinked', ['user_id' => $currentUserPlugin->getUserId(), 'ip' => Functions::getUserIP()]);
891
            }
892
 
893
            $currentUserPlugin->clearIdentity();
894
 
616 ariadna 895
            // return $this->redirect()->toRoute('home');
896
 
1 efrain 897
            return new JsonModel([
898
                'success'   => true,
899
                'data'      => [
900
                    'message' => 'LABEL_SIGNOUT_SUCCESSFULLY',
901
                    'url' => '',
902
                ],
616 ariadna 903
 
1 efrain 904
            ]);
905
        }
906
    }
907
 
908
 
909
    public function resetPasswordAction()
910
    {
911
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
912
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
913
 
616 ariadna 914
 
1 efrain 915
        $code =  Functions::sanitizeFilterString($this->params()->fromRoute('code', ''));
916
 
917
        $userMapper = UserMapper::getInstance($this->adapter);
918
        $user = $userMapper->fetchOneByPasswordResetKeyAndNetworkId($code, $currentNetwork->id);
919
        if (!$user) {
920
            $this->logger->err('Restablecer contraseña - Error código no existe', ['ip' => Functions::getUserIP()]);
921
 
922
            return new JsonModel([
183 efrain 923
                'success'   => false,
1 efrain 924
                'data'      => 'ERROR_PASSWORD_RECOVER_CODE_IS_INVALID'
925
            ]);
926
        }
927
 
616 ariadna 928
 
929
 
1 efrain 930
        $password_generated_on = strtotime($user->password_generated_on);
931
        $expiry_time = $password_generated_on + $this->config['leaderslinked.security.reset_password_expired'];
932
        if (time() > $expiry_time) {
933
            $this->logger->err('Restablecer contraseña - Error código expirado', ['ip' => Functions::getUserIP()]);
616 ariadna 934
 
1 efrain 935
            return new JsonModel([
181 efrain 936
                'success'   => false,
1 efrain 937
                'data'      => 'ERROR_PASSWORD_RECOVER_CODE_HAS_EXPIRED'
938
            ]);
939
        }
940
 
941
        $request = $this->getRequest();
942
        if ($request->isPost()) {
943
            $dataPost = $request->getPost()->toArray();
944
            if (empty($_SESSION['aes'])) {
945
                return new JsonModel([
946
                    'success'   => false,
947
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
616 ariadna 948
                ]);
1 efrain 949
            }
950
 
951
            if (!empty($dataPost['password'])) {
952
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
953
            }
954
            if (!empty($dataPost['confirmation'])) {
955
                $dataPost['confirmation'] = CryptoJsAes::decrypt($dataPost['confirmation'], $_SESSION['aes']);
956
            }
957
 
616 ariadna 958
 
959
 
1 efrain 960
            $form = new ResetPasswordForm($this->config);
961
            $form->setData($dataPost);
962
 
963
            if ($form->isValid()) {
964
                $data = (array) $form->getData();
965
                $password = $data['password'];
966
 
616 ariadna 967
 
1 efrain 968
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
969
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);
970
 
971
                $oldPassword = false;
972
                foreach ($userPasswords as $userPassword) {
973
                    if (password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password)) {
974
                        $oldPassword = true;
975
                        break;
976
                    }
977
                }
978
 
979
                if ($oldPassword) {
980
                    $this->logger->err('Restablecer contraseña - Error contraseña ya utilizada anteriormente', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
981
 
982
                    return new JsonModel([
983
                        'success'   => false,
984
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
985
 
986
                    ]);
987
                } else {
988
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
989
 
990
 
991
                    $result = $userMapper->updatePassword($user, $password_hash);
992
                    if ($result) {
993
 
994
                        $userPassword = new UserPassword();
995
                        $userPassword->user_id = $user->id;
996
                        $userPassword->password = $password_hash;
997
                        $userPasswordMapper->insert($userPassword);
998
 
999
 
1000
                        $this->logger->info('Restablecer contraseña realizado', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1001
 
1002
 
616 ariadna 1003
 
1 efrain 1004
                        return new JsonModel([
1005
                            'success'   => true,
138 efrain 1006
                            'data'      => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED'
1 efrain 1007
 
1008
                        ]);
1009
                    } else {
1010
                        $this->logger->err('Restablecer contraseña - Error desconocido', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1011
 
1012
                        return new JsonModel([
1013
                            'success'   => false,
1014
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
1015
 
1016
                        ]);
1017
                    }
1018
                }
1019
            } else {
1020
                $form_messages =  $form->getMessages('captcha');
1021
                if (!empty($form_messages)) {
1022
                    return new JsonModel([
1023
                        'success'   => false,
1024
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1025
                    ]);
1026
                }
1027
 
1028
                $messages = [];
1029
 
1030
                $form_messages = (array) $form->getMessages();
1031
                foreach ($form_messages  as $fieldname => $field_messages) {
1032
                    $messages[$fieldname] = array_values($field_messages);
1033
                }
1034
 
1035
                return new JsonModel([
1036
                    'success'   => false,
1037
                    'data'   => $messages
1038
                ]);
1039
            }
1040
        } else if ($request->isGet()) {
1041
 
1042
            if (empty($_SESSION['aes'])) {
1043
                $_SESSION['aes'] = Functions::generatePassword(16);
1044
            }
1045
 
1046
            if ($this->config['leaderslinked.runmode.sandbox']) {
1047
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1048
            } else {
1049
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1050
            }
1051
 
1052
 
1053
            return new JsonModel([
1054
                'code' => $code,
1055
                'site_key' => $site_key,
1056
                'aes'       => $_SESSION['aes'],
1057
                'defaultNetwork' => $currentNetwork->default,
1058
            ]);
1059
        }
1060
 
1061
 
1062
 
1063
        return new JsonModel([
1064
            'success' => false,
1065
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1066
        ]);
1067
    }
1068
 
1069
    public function forgotPasswordAction()
1070
    {
616 ariadna 1071
        // Obtiene el plugin de la red actual.
1 efrain 1072
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
616 ariadna 1073
        // Obtiene la información de la red actual.
1 efrain 1074
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1075
 
1076
 
1077
 
616 ariadna 1078
        // Obtiene la petición HTTP actual.
1079
        $request = $this->getRequest();
1080
        // Verifica si la petición es de tipo POST.
1 efrain 1081
        if ($request->isPost()) {
616 ariadna 1082
            // Obtiene los datos enviados por POST y los convierte a un array.
1 efrain 1083
            $dataPost = $request->getPost()->toArray();
616 ariadna 1084
            // Verifica si la clave AES no está presente en la sesión.
1 efrain 1085
            if (empty($_SESSION['aes'])) {
616 ariadna 1086
                // Retorna un error si no se encuentran las claves de encriptación.
1 efrain 1087
                return new JsonModel([
1088
                    'success'   => false,
1089
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
1090
                ]);
1091
            }
1092
 
616 ariadna 1093
            // Verifica si el campo 'email' no está vacío en los datos POST.
1 efrain 1094
            if (!empty($dataPost['email'])) {
616 ariadna 1095
                // Desencripta el email utilizando la clave AES de la sesión.
1 efrain 1096
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
1097
            }
1098
 
616 ariadna 1099
            // Crea una nueva instancia del formulario ForgotPasswordForm, pasando la configuración.
1 efrain 1100
            $form = new ForgotPasswordForm($this->config);
616 ariadna 1101
            // Establece los datos del POST en el formulario.
1 efrain 1102
            $form->setData($dataPost);
1103
 
616 ariadna 1104
            // Verifica si el formulario es válido.
1105
            if ($form->isValid()) {
1106
                // Obtiene los datos validados del formulario como un array.
1107
                $dataPost = (array) $form->getData();
1108
                // Extrae el email de los datos del formulario.
1109
                $email      = $dataPost['email'];
1110
 
1111
                // Obtiene una instancia del UserMapper.
1112
                $userMapper = UserMapper::getInstance($this->adapter);
1113
                // Busca un usuario por email y ID de red.
1114
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1115
                // Verifica si no se encontró ningún usuario.
1116
                if (!$user) {
1117
                    // Registra un error si el email no existe.
1118
                    $this->logger->err('Olvidó contraseña ' . $email . '- Email no existe ', ['ip' => Functions::getUserIP()]);
1119
 
1120
                    // Retorna un error indicando que el email no está registrado.
1121
                    return new JsonModel([
1122
                        'success' => false,
1123
                        'data' =>  'ERROR_EMAIL_IS_NOT_REGISTERED'
1124
                    ]);
1125
                } else {
1126
                    // Verifica si el estado del usuario es inactivo.
1127
                    if ($user->status == User::STATUS_INACTIVE) {
1128
                        // Retorna un error indicando que el usuario está inactivo.
1129
                        return new JsonModel([
1130
                            'success' => false,
1131
                            'data' =>  'ERROR_USER_IS_INACTIVE'
1132
                        ]);
1133
                        // Verifica si el email del usuario no ha sido verificado.
1134
                    } else if ($user->email_verified == User::EMAIL_VERIFIED_NO) {
1135
                        // Registra un error si el email no ha sido verificado.
1136
                        $this->logger->err('Olvidó contraseña - Email no verificado ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1137
 
1138
                        // Retorna un error indicando que el email no ha sido verificado.
1139
                        return new JsonModel([
1140
                            'success' => false,
1141
                            'data' => 'ERROR_EMAIL_HAS_NOT_BEEN_VERIFIED'
1142
                        ]);
1143
                    } else {
1144
                        // Genera una clave de reseteo de contraseña utilizando el email del usuario y el timestamp actual.
1145
                        $password_reset_key = md5($user->email . time());
1146
                        // Actualiza la clave de reseteo de contraseña del usuario en la base de datos.
1147
                        $userMapper->updatePasswordResetKey((int) $user->id, $password_reset_key);
1148
 
1149
                        // Obtiene una instancia del EmailTemplateMapper.
1150
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1151
                        // Busca una plantilla de email por código y ID de red.
1152
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RESET_PASSWORD, $currentNetwork->id);
1153
                        // Verifica si se encontró la plantilla de email.
1154
                        if ($emailTemplate) {
1155
                            // Prepara los datos para la plantilla de email.
1156
                            $arrayCont = [
1157
                                'firstname'             => $user->first_name,
1158
                                'lastname'              => $user->last_name,
1159
                                'other_user_firstname'  => '',
1160
                                'other_user_lastname'   => '',
1161
                                'company_name'          => '',
1162
                                'group_name'            => '',
1163
                                'content'               => '',
1164
                                'code'                  => '',
1165
                                // Genera el enlace para resetear la contraseña.
1166
                                'link'                  => $this->url()->fromRoute('reset-password', ['code' => $password_reset_key], ['force_canonical' => true])
1167
                            ];
1168
 
1169
                            // Crea una nueva instancia de QueueEmail.
1170
                            $email = new QueueEmail($this->adapter);
1171
                            // Procesa y envía el email utilizando la plantilla y los datos preparados.
1172
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1173
                        }
1174
 
1175
                        // Registra una información indicando que se envió el link de recuperación.
1176
                        $this->logger->info('Olvidó contraseña - Se envio link de recuperación ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1177
 
1178
                        // Retorna una respuesta exitosa indicando que el link de recuperación fue enviado.
1179
                        return new JsonModel([
1180
                            'success' => true,
1181
                            'data' => 'LABEL_RECOVERY_LINK_WAS_SENT_TO_YOUR_EMAIL'
1182
                        ]);
1183
                    }
1184
                }
1185
            } else {
1186
 
1187
                // Obtiene los mensajes de error del campo 'captcha' del formulario.
1 efrain 1188
                $form_messages =  $form->getMessages('captcha');
1189
 
616 ariadna 1190
 
1191
                // Verifica si hay mensajes de error para el captcha.
1 efrain 1192
                if (!empty($form_messages)) {
616 ariadna 1193
                    // Retorna un error indicando que el reCAPTCHA está vacío o es inválido.
1 efrain 1194
                    return new JsonModel([
1195
                        'success'   => false,
1196
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1197
                    ]);
1198
                }
1199
 
616 ariadna 1200
                // Inicializa un array para almacenar los mensajes de error del formulario.
1 efrain 1201
                $messages = [];
616 ariadna 1202
                // Obtiene todos los mensajes de error del formulario como un array.
1 efrain 1203
                $form_messages = (array) $form->getMessages();
616 ariadna 1204
                // Itera sobre los mensajes de error del formulario.
1 efrain 1205
                foreach ($form_messages  as $fieldname => $field_messages) {
616 ariadna 1206
                    // Agrupa los mensajes de error por nombre de campo.
1 efrain 1207
                    $messages[$fieldname] = array_values($field_messages);
1208
                }
1209
 
616 ariadna 1210
                // Retorna una respuesta de error con los mensajes del formulario.
1 efrain 1211
                return new JsonModel([
1212
                    'success'   => false,
1213
                    'data'      => $messages
1214
                ]);
1215
            }
616 ariadna 1216
            // Verifica si la petición es de tipo GET.
1217
        } else  if ($request->isGet()) {
1 efrain 1218
 
616 ariadna 1219
            // Verifica si la clave AES no está presente en la sesión.
1220
            if (empty($_SESSION['aes'])) {
1221
                // Genera una nueva clave AES y la guarda en la sesión.
1222
                $_SESSION['aes'] = Functions::generatePassword(16);
1 efrain 1223
            }
1224
 
616 ariadna 1225
            // Verifica si el entorno es sandbox.
1226
            if ($this->config['leaderslinked.runmode.sandbox']) {
1227
                // Obtiene la clave del sitio de Google reCAPTCHA para sandbox.
1228
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1229
            } else {
1230
                // Obtiene la clave del sitio de Google reCAPTCHA para producción.
1231
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1 efrain 1232
            }
1233
 
616 ariadna 1234
            // Retorna los datos necesarios para el frontend (clave del sitio, clave AES y si es la red por defecto).
1 efrain 1235
            return new JsonModel([
616 ariadna 1236
                'site_key'  => $site_key,
1237
                'aes'       => $_SESSION['aes'],
1238
                'defaultNetwork' => $currentNetwork->default,
1 efrain 1239
            ]);
1240
        }
1241
 
616 ariadna 1242
        // Retorna un error si el método HTTP no está permitido (ni POST ni GET).
1 efrain 1243
        return new JsonModel([
1244
            'success' => false,
1245
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1246
        ]);
1247
    }
1248
 
1249
    public function signupAction()
1250
    {
1251
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1252
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1253
 
1254
 
1255
        $request = $this->getRequest();
1256
        if ($request->isPost()) {
1257
            $dataPost = $request->getPost()->toArray();
1258
 
1259
            if (empty($_SESSION['aes'])) {
1260
                return new JsonModel([
1261
                    'success'   => false,
1262
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
1263
                ]);
1264
            }
1265
 
1266
            if (!empty($dataPost['email'])) {
1267
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
1268
            }
1269
 
1270
            if (!empty($dataPost['password'])) {
1271
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
1272
            }
1273
 
1274
            if (!empty($dataPost['confirmation'])) {
1275
                $dataPost['confirmation'] = CryptoJsAes::decrypt($dataPost['confirmation'], $_SESSION['aes']);
1276
            }
1277
 
1278
            if (empty($dataPost['is_adult'])) {
1279
                $dataPost['is_adult'] = User::IS_ADULT_NO;
1280
            } else {
1281
                $dataPost['is_adult'] = $dataPost['is_adult'] == User::IS_ADULT_YES ? User::IS_ADULT_YES : User::IS_ADULT_NO;
1282
            }
1283
 
1284
 
1285
 
1286
            $form = new SignupForm($this->config);
1287
            $form->setData($dataPost);
1288
 
1289
            if ($form->isValid()) {
1290
                $dataPost = (array) $form->getData();
1291
 
1292
                $email = $dataPost['email'];
1293
 
1294
                $userMapper = UserMapper::getInstance($this->adapter);
1295
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1296
                if ($user) {
1297
                    $this->logger->err('Registro ' . $email . '- Email ya  existe ', ['ip' => Functions::getUserIP()]);
1298
 
1299
 
1300
 
1301
                    return new JsonModel([
1302
                        'success' => false,
1303
                        'data' => 'ERROR_EMAIL_IS_REGISTERED'
1304
                    ]);
1305
                } else {
1306
 
1307
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
1308
 
1309
 
255 efrain 1310
                    if ($user_share_invitation && is_array($user_share_invitation)) {
616 ariadna 1311
 
249 efrain 1312
                        $content_uuid = $user_share_invitation['code'];
1313
                        $content_type = $user_share_invitation['type'];
1314
                        $content_user = $user_share_invitation['user'];
616 ariadna 1315
 
1316
 
249 efrain 1317
                        $userRedirect = $userMapper->fetchOneByUuid($content_user);
1 efrain 1318
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE) {
1319
                            $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1320
 
1321
                            $user = new User();
1322
                            $user->network_id           = $currentNetwork->id;
1323
                            $user->email                = $dataPost['email'];
1324
                            $user->first_name           = $dataPost['first_name'];
1325
                            $user->last_name            = $dataPost['last_name'];
385 www 1326
                            $user->timezone             = $dataPost['timezone'];
1 efrain 1327
                            $user->usertype_id          = UserType::USER;
1328
                            $user->password             = $password_hash;
1329
                            $user->password_updated_on  = date('Y-m-d H:i:s');
1330
                            $user->status               = User::STATUS_ACTIVE;
1331
                            $user->blocked              = User::BLOCKED_NO;
1332
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
1333
                            $user->login_attempt        = 0;
1334
                            $user->is_adult             = $dataPost['is_adult'];
1335
                            $user->request_access       = User::REQUEST_ACCESS_APPROVED;
1336
 
1337
 
1338
 
1339
 
1340
 
1341
                            if ($userMapper->insert($user)) {
1342
 
1343
                                $userPassword = new UserPassword();
1344
                                $userPassword->user_id = $user->id;
1345
                                $userPassword->password = $password_hash;
1346
 
1347
                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1348
                                $userPasswordMapper->insert($userPassword);
1349
 
1350
 
1351
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1352
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1353
 
1354
                                if ($connection) {
1355
 
1356
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1357
                                        $connectionMapper->approve($connection);
1358
                                    }
1359
                                } else {
1360
                                    $connection = new Connection();
1361
                                    $connection->request_from = $user->id;
1362
                                    $connection->request_to = $userRedirect->id;
1363
                                    $connection->status = Connection::STATUS_ACCEPTED;
1364
 
1365
                                    $connectionMapper->insert($connection);
1366
                                }
1367
 
1368
 
1369
                                $this->cache->removeItem('user_share_invitation');
1370
 
1371
 
616 ariadna 1372
 
1373
                                if ($content_type == 'feed') {
1374
                                    $url = $this->url()->fromRoute('dashboard', ['feed' => $content_uuid]);
1375
                                } else if ($content_type == 'post') {
1376
                                    $url = $this->url()->fromRoute('post', ['id' => $content_uuid]);
1377
                                } else {
249 efrain 1378
                                    $url = $this->url()->fromRoute('dashboard');
1379
                                }
616 ariadna 1380
 
249 efrain 1381
                                $hostname = empty($_SERVER['HTTP_HOST']) ?  '' : $_SERVER['HTTP_HOST'];
616 ariadna 1382
 
249 efrain 1383
                                $networkMapper = NetworkMapper::getInstance($this->adapter);
1384
                                $network = $networkMapper->fetchOneByHostnameForFrontend($hostname);
616 ariadna 1385
 
1386
                                if (!$network) {
249 efrain 1387
                                    $network = $networkMapper->fetchOneByDefault();
1388
                                }
616 ariadna 1389
 
249 efrain 1390
                                $hostname = trim($network->main_hostname);
1391
                                $url = 'https://' . $hostname . $url;
1 efrain 1392
 
616 ariadna 1393
 
1 efrain 1394
                                $data = [
1395
                                    'success'   => true,
249 efrain 1396
                                    'data'      => $url
1 efrain 1397
                                ];
1398
 
1399
 
1400
                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1401
 
1402
                                return new JsonModel($data);
1403
                            }
1404
                        }
1405
                    }
1406
 
1407
 
1408
 
1409
 
1410
                    $timestamp = time();
1411
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);
1412
 
1413
                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1414
 
1415
                    $user = new User();
1416
                    $user->network_id           = $currentNetwork->id;
1417
                    $user->email                = $dataPost['email'];
1418
                    $user->first_name           = $dataPost['first_name'];
1419
                    $user->last_name            = $dataPost['last_name'];
1420
                    $user->usertype_id          = UserType::USER;
1421
                    $user->password             = $password_hash;
1422
                    $user->password_updated_on  = date('Y-m-d H:i:s');
1423
                    $user->activation_key       = $activation_key;
1424
                    $user->status               = User::STATUS_INACTIVE;
1425
                    $user->blocked              = User::BLOCKED_NO;
1426
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
1427
                    $user->login_attempt        = 0;
1428
 
1429
                    if ($currentNetwork->default == Network::DEFAULT_YES) {
1430
                        $user->request_access = User::REQUEST_ACCESS_APPROVED;
1431
                    } else {
1432
                        $user->request_access = User::REQUEST_ACCESS_PENDING;
1433
                    }
1434
 
257 efrain 1435
                    $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
1436
                    $externalCredentials->completeDataFromNewUser($user);
1 efrain 1437
 
1438
                    if ($userMapper->insert($user)) {
1439
 
1440
                        $userPassword = new UserPassword();
1441
                        $userPassword->user_id = $user->id;
1442
                        $userPassword->password = $password_hash;
1443
 
1444
                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1445
                        $userPasswordMapper->insert($userPassword);
1446
 
1447
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1448
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
1449
                        if ($emailTemplate) {
1450
                            $arrayCont = [
1451
                                'firstname'             => $user->first_name,
1452
                                'lastname'              => $user->last_name,
1453
                                'other_user_firstname'  => '',
1454
                                'other_user_lastname'   => '',
1455
                                'company_name'          => '',
1456
                                'group_name'            => '',
1457
                                'content'               => '',
1458
                                'code'                  => '',
1459
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
1460
                            ];
1461
 
1462
                            $email = new QueueEmail($this->adapter);
1463
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1464
                        }
1465
 
1466
                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1467
 
1468
                        return new JsonModel([
1469
                            'success' => true,
180 efrain 1470
                            'data' => 'LABEL_REGISTRATION_DONE'
1 efrain 1471
                        ]);
1472
                    } else {
1473
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);
1474
 
1475
                        return new JsonModel([
1476
                            'success' => false,
1477
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1478
                        ]);
1479
                    }
1480
                }
1481
            } else {
1482
 
1483
                $form_messages =  $form->getMessages('captcha');
1484
                if (!empty($form_messages)) {
1485
                    return new JsonModel([
1486
                        'success'   => false,
1487
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1488
                    ]);
1489
                }
1490
 
1491
                $messages = [];
1492
 
1493
                $form_messages = (array) $form->getMessages();
1494
                foreach ($form_messages  as $fieldname => $field_messages) {
1495
                    $messages[$fieldname] = array_values($field_messages);
1496
                }
1497
 
1498
                return new JsonModel([
1499
                    'success'   => false,
1500
                    'data'   => $messages
1501
                ]);
1502
            }
1503
        } else if ($request->isGet()) {
1504
 
1505
            if (empty($_SESSION['aes'])) {
1506
                $_SESSION['aes'] = Functions::generatePassword(16);
1507
            }
1508
 
1509
            if ($this->config['leaderslinked.runmode.sandbox']) {
1510
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1511
            } else {
1512
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1513
            }
1514
 
1515
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
1516
 
1517
            return new JsonModel([
1518
                'site_key'  => $site_key,
1519
                'aes'       => $_SESSION['aes'],
1520
                'defaultNetwork' => $currentNetwork->default,
1521
            ]);
1522
        }
1523
 
1524
        return new JsonModel([
1525
            'success' => false,
1526
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1527
        ]);
1528
    }
1529
 
1530
    public function activateAccountAction()
1531
    {
1532
 
1533
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1534
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1535
 
1536
 
1537
 
1538
        $request = $this->getRequest();
1539
        if ($request->isGet()) {
1540
            $code   =  Functions::sanitizeFilterString($this->params()->fromRoute('code'));
1541
            $userMapper = UserMapper::getInstance($this->adapter);
1542
            $user = $userMapper->fetchOneByActivationKeyAndNetworkId($code, $currentNetwork->id);
1543
 
1544
 
180 efrain 1545
 
1 efrain 1546
            if ($user) {
1547
                if (User::EMAIL_VERIFIED_YES == $user->email_verified) {
616 ariadna 1548
 
1 efrain 1549
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
616 ariadna 1550
 
180 efrain 1551
                    $response = [
1552
                        'success' => false,
1553
                        'data' => 'ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED'
1554
                    ];
616 ariadna 1555
 
180 efrain 1556
                    return new JsonModel($response);
1 efrain 1557
                } else {
1558
 
1559
                    if ($userMapper->activateAccount((int) $user->id)) {
1560
 
1561
                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1562
 
1563
 
1564
 
1565
                        $user_share_invitation = $this->cache->getItem('user_share_invitation');
1566
 
1567
                        if ($user_share_invitation) {
1568
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
1569
                            if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
1570
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1571
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1572
 
1573
                                if ($connection) {
1574
 
1575
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1576
                                        $connectionMapper->approve($connection);
1577
                                    }
1578
                                } else {
1579
                                    $connection = new Connection();
1580
                                    $connection->request_from = $user->id;
1581
                                    $connection->request_to = $userRedirect->id;
1582
                                    $connection->status = Connection::STATUS_ACCEPTED;
1583
 
1584
                                    $connectionMapper->insert($connection);
1585
                                }
1586
                            }
1587
                        }
1588
 
1589
 
1590
 
1591
                        $this->cache->removeItem('user_share_invitation');
1592
 
1593
 
1594
                        if ($currentNetwork->default == Network::DEFAULT_YES) {
616 ariadna 1595
 
180 efrain 1596
                            $response = [
1597
                                'success' => true,
1598
                                'data' => 'LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED'
1599
                            ];
616 ariadna 1600
 
180 efrain 1601
                            return new JsonModel($response);
1 efrain 1602
                        } else {
1603
 
1604
                            $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1605
                            $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_REQUEST_ACCESS_PENDING, $currentNetwork->id);
1606
 
1607
                            if ($emailTemplate) {
1608
                                $arrayCont = [
1609
                                    'firstname'             => $user->first_name,
1610
                                    'lastname'              => $user->last_name,
1611
                                    'other_user_firstname'  => '',
1612
                                    'other_user_lastname'   => '',
1613
                                    'company_name'          => '',
1614
                                    'group_name'            => '',
1615
                                    'content'               => '',
1616
                                    'code'                  => '',
1617
                                    'link'                  => '',
1618
                                ];
1619
 
1620
                                $email = new QueueEmail($this->adapter);
1621
                                $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1622
                            }
616 ariadna 1623
 
180 efrain 1624
                            $response = [
1625
                                'success' => true,
1626
                                'data' => 'LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED_WE_ARE_VERIFYING_YOUR_INFORMATION'
1627
                            ];
616 ariadna 1628
 
180 efrain 1629
                            return new JsonModel($response);
1 efrain 1630
                        }
1631
                    } else {
1632
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
616 ariadna 1633
 
180 efrain 1634
                        $response = [
1635
                            'success' => false,
1636
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1637
                        ];
616 ariadna 1638
 
180 efrain 1639
                        return new JsonModel($response);
1 efrain 1640
                    }
1641
                }
1642
            } else {
616 ariadna 1643
 
1644
 
1 efrain 1645
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);
1646
 
180 efrain 1647
                $response = [
1648
                    'success' => false,
616 ariadna 1649
                    'data' => 'ERROR_ACTIVATION_CODE_IS_NOT_VALID'
180 efrain 1650
                ];
616 ariadna 1651
 
180 efrain 1652
                return new JsonModel($response);
1 efrain 1653
            }
1654
        } else {
1655
            $response = [
1656
                'success' => false,
1657
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1658
            ];
1659
        }
1660
 
1661
        return new JsonModel($response);
1662
    }
616 ariadna 1663
 
1 efrain 1664
    public function onroomAction()
1665
    {
1666
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1667
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
616 ariadna 1668
 
1669
 
1670
 
1 efrain 1671
        $request = $this->getRequest();
616 ariadna 1672
 
1 efrain 1673
        if ($request->isPost()) {
616 ariadna 1674
 
1 efrain 1675
            $dataPost = $request->getPost()->toArray();
616 ariadna 1676
 
1677
 
1 efrain 1678
            $form = new  MoodleForm();
1679
            $form->setData($dataPost);
1680
            if ($form->isValid()) {
616 ariadna 1681
 
1 efrain 1682
                $dataPost   = (array) $form->getData();
1683
                $username   = $dataPost['username'];
1684
                $password   = $dataPost['password'];
1685
                $timestamp  = $dataPost['timestamp'];
1686
                $rand       = $dataPost['rand'];
1687
                $data       = $dataPost['data'];
616 ariadna 1688
 
1 efrain 1689
                $config_username    = $this->config['leaderslinked.moodle.username'];
1690
                $config_password    = $this->config['leaderslinked.moodle.password'];
1691
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1692
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
1693
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
616 ariadna 1694
 
1695
 
1696
 
1697
 
1 efrain 1698
                if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1699
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
1700
                    exit;
1701
                }
616 ariadna 1702
 
1 efrain 1703
                if ($username != $config_username) {
1704
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
1705
                    exit;
1706
                }
616 ariadna 1707
 
1 efrain 1708
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1709
                if (!$dt) {
1710
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
1711
                    exit;
1712
                }
616 ariadna 1713
 
1 efrain 1714
                $t0 = $dt->getTimestamp();
1715
                $t1 = strtotime('-5 minutes');
1716
                $t2 = strtotime('+5 minutes');
616 ariadna 1717
 
1 efrain 1718
                if ($t0 < $t1 || $t0 > $t2) {
1719
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1720
                    //exit;
1721
                }
616 ariadna 1722
 
1 efrain 1723
                if (!password_verify($username . '-' . $config_password . '-' . $rand . '-' . $timestamp, $password)) {
1724
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
1725
                    exit;
1726
                }
616 ariadna 1727
 
1 efrain 1728
                if (empty($data)) {
1729
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
1730
                    exit;
1731
                }
616 ariadna 1732
 
1 efrain 1733
                $data = base64_decode($data);
1734
                if (empty($data)) {
1735
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
1736
                    exit;
1737
                }
616 ariadna 1738
 
1739
 
1 efrain 1740
                try {
1741
                    $rsa = Rsa::getInstance();
1742
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1743
                } catch (\Throwable $e) {
1744
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
1745
                    exit;
1746
                }
616 ariadna 1747
 
1 efrain 1748
                $data = (array) json_decode($data);
1749
                if (empty($data)) {
1750
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
1751
                    exit;
1752
                }
616 ariadna 1753
 
1 efrain 1754
                $email      = isset($data['email']) ? Functions::sanitizeFilterString($data['email']) : '';
1755
                $first_name = isset($data['first_name']) ? Functions::sanitizeFilterString($data['first_name']) : '';
1756
                $last_name  = isset($data['last_name']) ? Functions::sanitizeFilterString($data['last_name']) : '';
616 ariadna 1757
 
1 efrain 1758
                if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
1759
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']);
1760
                    exit;
1761
                }
616 ariadna 1762
 
1 efrain 1763
                $userMapper = UserMapper::getInstance($this->adapter);
1764
                $user = $userMapper->fetchOneByEmail($email);
1765
                if (!$user) {
616 ariadna 1766
 
1767
 
1 efrain 1768
                    $user = new User();
1769
                    $user->network_id = $currentNetwork->id;
1770
                    $user->blocked = User::BLOCKED_NO;
1771
                    $user->email = $email;
1772
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1773
                    $user->first_name = $first_name;
1774
                    $user->last_name = $last_name;
1775
                    $user->login_attempt = 0;
1776
                    $user->password = '-NO-PASSWORD-';
1777
                    $user->usertype_id = UserType::USER;
1778
                    $user->status = User::STATUS_ACTIVE;
1779
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
616 ariadna 1780
 
1 efrain 1781
                    if ($userMapper->insert($user)) {
1782
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]);
1783
                        exit;
1784
                    }
616 ariadna 1785
 
266 efrain 1786
                    $user = $userMapper->fetchOne($user->id);
616 ariadna 1787
 
1788
 
1789
 
1790
 
1 efrain 1791
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
1792
                    $content    = isset($data['avatar_content']) ? Functions::sanitizeFilterString($data['avatar_content']) : '';
616 ariadna 1793
 
1 efrain 1794
                    if ($filename && $content) {
1795
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
1796
                        try {
616 ariadna 1797
 
1798
 
1 efrain 1799
                            file_put_contents($source, base64_decode($content));
1800
                            if (file_exists($source)) {
1801
                                list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
616 ariadna 1802
 
1 efrain 1803
                                $target_filename    = 'user-' . uniqid() . '.png';
1804
                                $crop_to_dimensions = true;
616 ariadna 1805
 
266 efrain 1806
                                $image = Image::getInstance($this->config);
1807
                                $target_path    = $image->getStorage()->getPathUser();
1808
                                $unlink_source  = true;
616 ariadna 1809
 
1810
 
334 www 1811
                                if (!$image->uploadProcessChangeSize($source, $target_path, $user->uuid, $target_filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
1 efrain 1812
                                    return new JsonModel([
1813
                                        'success'   => false,
1814
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1815
                                    ]);
1816
                                }
616 ariadna 1817
 
1 efrain 1818
                                $user->image = $target_filename;
1819
                                $userMapper->updateImage($user);
1820
                            }
1821
                        } catch (\Throwable $e) {
1822
                        } finally {
1823
                            if (file_exists($source)) {
1824
                                unlink($source);
1825
                            }
1826
                        }
1827
                    }
1828
                }
616 ariadna 1829
 
1 efrain 1830
                $auth = new AuthEmailAdapter($this->adapter);
1831
                $auth->setData($email);
616 ariadna 1832
 
1 efrain 1833
                $result = $auth->authenticate();
1834
                if ($result->getCode() == AuthResult::SUCCESS) {
1835
                    return $this->redirect()->toRoute('dashboard');
1836
                } else {
1837
                    $message = $result->getMessages()[0];
1838
                    if (!in_array($message, [
616 ariadna 1839
                        'ERROR_USER_NOT_FOUND',
1840
                        'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED',
1841
                        'ERROR_USER_IS_BLOCKED',
1842
                        'ERROR_USER_IS_INACTIVE',
1843
                        'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED',
1844
                        'ERROR_ENTERED_PASS_INCORRECT_2',
1 efrain 1845
                        'ERROR_ENTERED_PASS_INCORRECT_1'
1846
                    ])) {
1847
                    }
616 ariadna 1848
 
1 efrain 1849
                    switch ($message) {
1850
                        case 'ERROR_USER_NOT_FOUND':
1851
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1852
                            break;
616 ariadna 1853
 
1 efrain 1854
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
1855
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1856
                            break;
616 ariadna 1857
 
1 efrain 1858
                        case 'ERROR_USER_IS_BLOCKED':
1859
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1860
                            break;
616 ariadna 1861
 
1 efrain 1862
                        case 'ERROR_USER_IS_INACTIVE':
1863
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1864
                            break;
616 ariadna 1865
 
1866
 
1 efrain 1867
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1868
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1869
                            break;
616 ariadna 1870
 
1871
 
1 efrain 1872
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
1873
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1874
                            break;
616 ariadna 1875
 
1876
 
1 efrain 1877
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
1878
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1879
                            break;
616 ariadna 1880
 
1881
 
1 efrain 1882
                        default:
1883
                            $message = 'ERROR_UNKNOWN';
1884
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1885
                            break;
1886
                    }
616 ariadna 1887
 
1888
 
1889
 
1890
 
1 efrain 1891
                    return new JsonModel([
1892
                        'success'   => false,
1893
                        'data'   => $message
1894
                    ]);
1895
                }
1896
            } else {
1897
                $messages = [];
616 ariadna 1898
 
1899
 
1900
 
283 www 1901
                $form_messages = (array) $form->getMessages();
1902
                foreach ($form_messages  as $fieldname => $field_messages) {
616 ariadna 1903
 
283 www 1904
                    $messages[$fieldname] = array_values($field_messages);
1905
                }
616 ariadna 1906
 
283 www 1907
                return new JsonModel([
1908
                    'success'   => false,
1909
                    'data'   => $messages
1910
                ]);
1911
            }
1912
        } else {
1913
            $data = [
1914
                'success' => false,
1915
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1916
            ];
616 ariadna 1917
 
283 www 1918
            return new JsonModel($data);
1919
        }
616 ariadna 1920
 
283 www 1921
        return new JsonModel($data);
1922
    }
1 efrain 1923
 
1924
 
1925
 
283 www 1926
    public function cesamsAction()
1927
    {
1928
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1929
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1930
 
1931
        $request = $this->getRequest();
1932
 
1933
        if ($request->isPost()) {
1934
 
1935
            $dataPost = $request->getPost()->toArray();
1936
 
1937
 
1938
            $form = new  MoodleForm();
1939
            $form->setData($dataPost);
1940
            if ($form->isValid()) {
1941
 
1942
                $dataPost   = (array) $form->getData();
1943
                $username   = $dataPost['username'];
1944
                $password   = $dataPost['password'];
1945
                $timestamp  = $dataPost['timestamp'];
1946
                $rand       = $dataPost['rand'];
1947
                $data       = $dataPost['data'];
1948
 
1949
                $config_username    = $this->config['leaderslinked.moodle.username'];
1950
                $config_password    = $this->config['leaderslinked.moodle.password'];
1951
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1952
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
291 www 1953
                //$config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
283 www 1954
 
1955
                if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1956
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
1957
                    exit;
1958
                }
1959
 
1960
                if ($username != $config_username) {
1961
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
1962
                    exit;
1963
                }
1964
 
1965
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1966
                if (!$dt) {
1967
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
1968
                    exit;
1969
                }
1970
 
1971
                $dt = \DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s',  gmdate('Y-m-d\TH:i:s'));
1972
                $dtMax = $dt->add(\DateInterval::createFromDateString('5 minutes'));
1973
                $dtMin = $dt->sub(\DateInterval::createFromDateString('5 minutes'));
616 ariadna 1974
 
1975
 
283 www 1976
                $t0 = $dt->getTimestamp();
1977
                $t1 = $dtMin->getTimestamp();
1978
                $t2 = $dtMax->getTimestamp();
1979
                if ($t0 < $t1 || $t0 > $t2) {
616 ariadna 1980
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']);
301 www 1981
                    exit;
283 www 1982
                }
1983
 
1984
                if (!password_verify($username . '-' . $config_password . '-' . $rand . '-' . $timestamp, $password)) {
1985
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
1986
                    exit;
1987
                }
1988
 
1989
                if (empty($data)) {
1990
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
1991
                    exit;
1992
                }
1993
 
1994
                $data = base64_decode($data);
1995
                if (empty($data)) {
1996
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
1997
                    exit;
1998
                }
1999
 
2000
                try {
2001
                    $rsa = Rsa::getInstance();
2002
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
2003
                } catch (\Throwable $e) {
2004
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
2005
                    exit;
2006
                }
2007
 
2008
                $data = (array) json_decode($data);
2009
                if (empty($data)) {
2010
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
2011
                    exit;
2012
                }
2013
 
2014
                $email      = isset($data['email']) ? Functions::sanitizeFilterString($data['email']) : '';
2015
                $first_name = isset($data['first_name']) ? Functions::sanitizeFilterString($data['first_name']) : '';
2016
                $last_name  = isset($data['last_name']) ? Functions::sanitizeFilterString($data['last_name']) : '';
2017
                $password   = isset($data['password']) ? Functions::sanitizeFilterString($data['password']) : '';
2018
 
2019
                if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name) || empty($password)) {
2020
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']);
2021
                    exit;
2022
                }
2023
 
2024
                $userMapper = UserMapper::getInstance($this->adapter);
2025
                $user = $userMapper->fetchOneByEmail($email);
2026
                if (!$user) {
2027
 
2028
                    $user = new User();
2029
                    $user->network_id = $currentNetwork->id;
2030
                    $user->blocked = User::BLOCKED_NO;
2031
                    $user->email = $email;
2032
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
2033
                    $user->first_name = $first_name;
2034
                    $user->last_name = $last_name;
2035
                    $user->login_attempt = 0;
2036
                    $user->password = password_hash($password, PASSWORD_DEFAULT);
2037
                    $user->usertype_id = UserType::USER;
2038
                    $user->status = User::STATUS_ACTIVE;
2039
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
2040
 
2041
                    if ($userMapper->insert($user)) {
2042
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]);
2043
                        exit;
2044
                    }
616 ariadna 2045
 
283 www 2046
                    $user = $userMapper->fetchOne($user->id);
616 ariadna 2047
 
283 www 2048
                    $userPassword = new UserPassword();
2049
                    $userPassword->user_id = $user->id;
2050
                    $userPassword->password = password_hash($password, PASSWORD_DEFAULT);
616 ariadna 2051
 
283 www 2052
                    $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
2053
                    $userPasswordMapper->insert($userPassword);
616 ariadna 2054
 
283 www 2055
                    $userDefaultForConnection = $userMapper->fetchOneDefaultForConnection();
616 ariadna 2056
                    if ($userDefaultForConnection) {
2057
 
283 www 2058
                        $connection = new Connection();
616 ariadna 2059
                        $connection->request_from = $userDefaultForConnection->id;
283 www 2060
                        $connection->request_to = $user->id;
2061
                        $connection->status = Connection::STATUS_ACCEPTED;
616 ariadna 2062
 
283 www 2063
                        $connectionMapper = ConnectionMapper::getInstance($this->adapter);
2064
                        $connectionMapper->insert($connection);
2065
                    }
2066
                }
2067
 
2068
                return new JsonModel([
2069
                    'success'   => true,
2070
                    'data'   => $user->uuid
2071
                ]);
2072
            } else {
2073
                $messages = [];
2074
 
2075
 
2076
 
1 efrain 2077
                $form_messages = (array) $form->getMessages();
2078
                foreach ($form_messages  as $fieldname => $field_messages) {
2079
 
2080
                    $messages[$fieldname] = array_values($field_messages);
2081
                }
2082
 
2083
                return new JsonModel([
2084
                    'success'   => false,
2085
                    'data'   => $messages
2086
                ]);
2087
            }
2088
        } else {
2089
            $data = [
2090
                'success' => false,
2091
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2092
            ];
2093
 
2094
            return new JsonModel($data);
2095
        }
2096
 
2097
        return new JsonModel($data);
2098
    }
2099
 
2100
    public function csrfAction()
2101
    {
2102
        $request = $this->getRequest();
2103
        if ($request->isGet()) {
616 ariadna 2104
 
95 efrain 2105
            $jwtToken = null;
2106
            $headers = getallheaders();
616 ariadna 2107
 
2108
 
2109
            if (!empty($headers['authorization']) || !empty($headers['Authorization'])) {
2110
 
95 efrain 2111
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
616 ariadna 2112
 
2113
 
2114
                if (substr($token, 0, 6) == 'Bearer') {
2115
 
95 efrain 2116
                    $token = trim(substr($token, 7));
616 ariadna 2117
 
2118
                    if (!empty($this->config['leaderslinked.jwt.key'])) {
95 efrain 2119
                        $key = $this->config['leaderslinked.jwt.key'];
616 ariadna 2120
 
2121
 
95 efrain 2122
                        try {
2123
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
616 ariadna 2124
 
2125
 
2126
                            if (empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
95 efrain 2127
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
2128
                            }
616 ariadna 2129
 
95 efrain 2130
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
2131
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2132
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
616 ariadna 2133
                            if (!$jwtToken) {
95 efrain 2134
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
2135
                            }
616 ariadna 2136
                        } catch (\Exception $e) {
95 efrain 2137
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
2138
                        }
2139
                    } else {
2140
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
2141
                    }
2142
                } else {
2143
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
2144
                }
2145
            } else {
2146
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
279 efrain 2147
            }
616 ariadna 2148
 
95 efrain 2149
            $jwtToken->csrf = md5(uniqid('CSFR-' . mt_rand(), true));
2150
            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2151
            $jwtTokenMapper->update($jwtToken);
1 efrain 2152
 
2153
 
616 ariadna 2154
            // error_log('token id = ' . $jwtToken->id . ' csrf = ' . $jwtToken->csrf);
2155
 
2156
 
1 efrain 2157
            return new JsonModel([
2158
                'success' => true,
99 efrain 2159
                'data' => $jwtToken->csrf
1 efrain 2160
            ]);
2161
        } else {
2162
            return new JsonModel([
2163
                'success' => false,
2164
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2165
            ]);
2166
        }
2167
    }
2168
 
2169
    public function impersonateAction()
2170
    {
2171
        $request = $this->getRequest();
2172
        if ($request->isGet()) {
2173
            $user_uuid  = Functions::sanitizeFilterString($this->params()->fromQuery('user_uuid'));
2174
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
2175
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
2176
            $password   = Functions::sanitizeFilterString($this->params()->fromQuery('password'));
2177
 
2178
 
2179
            if (!$user_uuid || !$rand || !$timestamp || !$password) {
2180
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
2181
            }
2182
 
2183
 
2184
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2185
            $currentUserPlugin->clearIdentity();
2186
 
2187
 
2188
            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
2189
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);
2190
 
2191
            $authService = new AuthenticationService();
2192
            $result = $authService->authenticate($authAdapter);
2193
 
2194
 
2195
            if ($result->getCode() == AuthResult::SUCCESS) {
2196
                return $this->redirect()->toRoute('dashboard');
2197
            } else {
2198
                throw new \Exception($result->getMessages()[0]);
2199
            }
2200
        }
2201
 
2202
        return new JsonModel([
2203
            'success' => false,
2204
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2205
        ]);
2206
    }
616 ariadna 2207
 
2208
 
2209
 
340 www 2210
    public function debugAction()
2211
    {
2212
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
2213
        $currentNetwork = $currentNetworkPlugin->getNetwork();
616 ariadna 2214
 
340 www 2215
        $request = $this->getRequest();
616 ariadna 2216
 
340 www 2217
        if ($request->isPost()) {
2218
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
2219
            $currentNetwork = $currentNetworkPlugin->getNetwork();
616 ariadna 2220
 
340 www 2221
            $jwtToken = null;
2222
            $headers = getallheaders();
616 ariadna 2223
 
2224
 
2225
            if (!empty($headers['authorization']) || !empty($headers['Authorization'])) {
2226
 
340 www 2227
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
616 ariadna 2228
 
2229
 
2230
                if (substr($token, 0, 6) == 'Bearer') {
2231
 
340 www 2232
                    $token = trim(substr($token, 7));
616 ariadna 2233
 
2234
                    if (!empty($this->config['leaderslinked.jwt.key'])) {
340 www 2235
                        $key = $this->config['leaderslinked.jwt.key'];
616 ariadna 2236
 
2237
 
340 www 2238
                        try {
2239
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
616 ariadna 2240
 
2241
 
2242
                            if (empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
340 www 2243
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
2244
                            }
616 ariadna 2245
 
340 www 2246
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
2247
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2248
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
616 ariadna 2249
                            if (!$jwtToken) {
340 www 2250
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
2251
                            }
616 ariadna 2252
                        } catch (\Exception $e) {
340 www 2253
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
2254
                        }
2255
                    } else {
2256
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
2257
                    }
2258
                } else {
2259
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
2260
                }
2261
            } else {
2262
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
2263
            }
616 ariadna 2264
 
2265
 
2266
 
340 www 2267
            $form = new  SigninDebugForm($this->config);
2268
            $dataPost = $request->getPost()->toArray();
616 ariadna 2269
 
340 www 2270
            if (empty($_SESSION['aes'])) {
2271
                return new JsonModel([
2272
                    'success'   => false,
2273
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
2274
                ]);
2275
            }
616 ariadna 2276
 
340 www 2277
            error_log(print_r($dataPost, true));
616 ariadna 2278
 
340 www 2279
            $aes = $_SESSION['aes'];
2280
            error_log('aes : ' . $aes);
616 ariadna 2281
 
2282
 
2283
            unset($_SESSION['aes']);
2284
 
340 www 2285
            if (!empty($dataPost['email'])) {
2286
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $aes);
2287
            }
616 ariadna 2288
 
2289
 
340 www 2290
            if (!empty($dataPost['password'])) {
2291
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $aes);
2292
            }
616 ariadna 2293
 
2294
 
340 www 2295
            error_log(print_r($dataPost, true));
616 ariadna 2296
 
340 www 2297
            $form->setData($dataPost);
616 ariadna 2298
 
340 www 2299
            if ($form->isValid()) {
616 ariadna 2300
 
340 www 2301
                $dataPost = (array) $form->getData();
616 ariadna 2302
 
2303
 
340 www 2304
                $email      = $dataPost['email'];
2305
                $password   = $dataPost['password'];
616 ariadna 2306
 
2307
 
2308
 
2309
 
2310
 
340 www 2311
                $authAdapter = new AuthAdapter($this->adapter, $this->logger);
2312
                $authAdapter->setData($email, $password, $currentNetwork->id);
2313
                $authService = new AuthenticationService();
616 ariadna 2314
 
340 www 2315
                $result = $authService->authenticate($authAdapter);
616 ariadna 2316
 
340 www 2317
                if ($result->getCode() == AuthResult::SUCCESS) {
616 ariadna 2318
 
340 www 2319
                    $identity = $result->getIdentity();
616 ariadna 2320
 
2321
 
340 www 2322
                    $userMapper = UserMapper::getInstance($this->adapter);
2323
                    $user = $userMapper->fetchOne($identity['user_id']);
616 ariadna 2324
 
2325
 
2326
                    if ($token) {
340 www 2327
                        $jwtToken->user_id = $user->id;
2328
                        $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2329
                        $jwtTokenMapper->update($jwtToken);
2330
                    }
616 ariadna 2331
 
2332
 
340 www 2333
                    $navigator = get_browser(null, true);
2334
                    $device_type    =  isset($navigator['device_type']) ? $navigator['device_type'] : '';
2335
                    $platform       =  isset($navigator['platform']) ? $navigator['platform'] : '';
2336
                    $browser        =  isset($navigator['browser']) ? $navigator['browser'] : '';
616 ariadna 2337
 
2338
 
340 www 2339
                    $istablet = isset($navigator['istablet']) ?  intval($navigator['istablet']) : 0;
2340
                    $ismobiledevice = isset($navigator['ismobiledevice']) ? intval($navigator['ismobiledevice']) : 0;
2341
                    $version = isset($navigator['version']) ? $navigator['version'] : '';
616 ariadna 2342
 
2343
 
340 www 2344
                    $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
2345
                    $userBrowser = $userBrowserMapper->fetch($user->id, $device_type, $platform, $browser);
2346
                    if ($userBrowser) {
2347
                        $userBrowserMapper->update($userBrowser);
2348
                    } else {
2349
                        $userBrowser = new UserBrowser();
2350
                        $userBrowser->user_id           = $user->id;
2351
                        $userBrowser->browser           = $browser;
2352
                        $userBrowser->platform          = $platform;
2353
                        $userBrowser->device_type       = $device_type;
2354
                        $userBrowser->is_tablet         = $istablet;
2355
                        $userBrowser->is_mobile_device  = $ismobiledevice;
2356
                        $userBrowser->version           = $version;
616 ariadna 2357
 
340 www 2358
                        $userBrowserMapper->insert($userBrowser);
2359
                    }
2360
                    //
616 ariadna 2361
 
340 www 2362
                    $ip = Functions::getUserIP();
2363
                    $ip = $ip == '127.0.0.1' ? '148.240.211.148' : $ip;
616 ariadna 2364
 
340 www 2365
                    $userIpMapper = UserIpMapper::getInstance($this->adapter);
2366
                    $userIp = $userIpMapper->fetch($user->id, $ip);
2367
                    if (empty($userIp)) {
616 ariadna 2368
 
340 www 2369
                        if ($this->config['leaderslinked.runmode.sandbox']) {
2370
                            $filename = $this->config['leaderslinked.geoip2.production_database'];
2371
                        } else {
2372
                            $filename = $this->config['leaderslinked.geoip2.sandbox_database'];
2373
                        }
616 ariadna 2374
 
340 www 2375
                        $reader = new GeoIp2Reader($filename); //GeoIP2-City.mmdb');
2376
                        $record = $reader->city($ip);
2377
                        if ($record) {
2378
                            $userIp = new UserIp();
2379
                            $userIp->user_id = $user->id;
2380
                            $userIp->city = !empty($record->city->name) ? Functions::utf8_decode($record->city->name) : '';
2381
                            $userIp->state_code = !empty($record->mostSpecificSubdivision->isoCode) ? Functions::utf8_decode($record->mostSpecificSubdivision->isoCode) : '';
2382
                            $userIp->state_name = !empty($record->mostSpecificSubdivision->name) ? Functions::utf8_decode($record->mostSpecificSubdivision->name) : '';
2383
                            $userIp->country_code = !empty($record->country->isoCode) ? Functions::utf8_decode($record->country->isoCode) : '';
2384
                            $userIp->country_name = !empty($record->country->name) ? Functions::utf8_decode($record->country->name) : '';
2385
                            $userIp->ip = $ip;
2386
                            $userIp->latitude = !empty($record->location->latitude) ? $record->location->latitude : 0;
2387
                            $userIp->longitude = !empty($record->location->longitude) ? $record->location->longitude : 0;
2388
                            $userIp->postal_code = !empty($record->postal->code) ? $record->postal->code : '';
616 ariadna 2389
 
340 www 2390
                            $userIpMapper->insert($userIp);
2391
                        }
2392
                    } else {
2393
                        $userIpMapper->update($userIp);
2394
                    }
616 ariadna 2395
 
340 www 2396
                    /*
2397
                     if ($remember) {
2398
                     $expired = time() + 365 * 24 * 60 * 60;
2399
 
2400
                     $cookieEmail = new SetCookie('email', $email, $expired);
2401
                     } else {
2402
                     $expired = time() - 7200;
2403
                     $cookieEmail = new SetCookie('email', '', $expired);
2404
                     }
2405
 
2406
 
2407
                     $response = $this->getResponse();
2408
                     $response->getHeaders()->addHeader($cookieEmail);
2409
                     */
616 ariadna 2410
 
2411
 
2412
 
2413
 
2414
 
340 www 2415
                    $this->logger->info('Ingreso a LeadersLiked', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
616 ariadna 2416
 
340 www 2417
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
616 ariadna 2418
 
340 www 2419
                    $url =  $this->url()->fromRoute('dashboard');
616 ariadna 2420
 
340 www 2421
                    if ($user_share_invitation && is_array($user_share_invitation)) {
616 ariadna 2422
 
340 www 2423
                        $content_uuid = $user_share_invitation['code'];
2424
                        $content_type = $user_share_invitation['type'];
2425
                        $content_user = $user_share_invitation['user'];
616 ariadna 2426
 
2427
 
2428
 
340 www 2429
                        $userRedirect = $userMapper->fetchOneByUuid($content_user);
2430
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
2431
                            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
2432
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
616 ariadna 2433
 
340 www 2434
                            if ($connection) {
616 ariadna 2435
 
340 www 2436
                                if ($connection->status != Connection::STATUS_ACCEPTED) {
2437
                                    $connectionMapper->approve($connection);
2438
                                }
2439
                            } else {
2440
                                $connection = new Connection();
2441
                                $connection->request_from = $user->id;
2442
                                $connection->request_to = $userRedirect->id;
2443
                                $connection->status = Connection::STATUS_ACCEPTED;
616 ariadna 2444
 
340 www 2445
                                $connectionMapper->insert($connection);
2446
                            }
2447
                        }
616 ariadna 2448
 
2449
                        if ($content_type == 'feed') {
2450
                            $url = $this->url()->fromRoute('dashboard', ['feed' => $content_uuid]);
2451
                        } else if ($content_type == 'post') {
2452
                            $url = $this->url()->fromRoute('post', ['id' => $content_uuid]);
2453
                        } else {
340 www 2454
                            $url = $this->url()->fromRoute('dashboard');
2455
                        }
2456
                    }
616 ariadna 2457
 
2458
 
340 www 2459
                    $hostname = empty($_SERVER['HTTP_HOST']) ?  '' : $_SERVER['HTTP_HOST'];
616 ariadna 2460
 
340 www 2461
                    $networkMapper = NetworkMapper::getInstance($this->adapter);
2462
                    $network = $networkMapper->fetchOneByHostnameForFrontend($hostname);
616 ariadna 2463
 
2464
                    if (!$network) {
340 www 2465
                        $network = $networkMapper->fetchOneByDefault();
2466
                    }
616 ariadna 2467
 
340 www 2468
                    $hostname = trim($network->main_hostname);
2469
                    $url = 'https://' . $hostname . $url;
616 ariadna 2470
 
2471
 
340 www 2472
                    $data = [
2473
                        'redirect'  => $url,
2474
                        'uuid'      => $user->uuid,
2475
                    ];
616 ariadna 2476
 
2477
 
2478
 
2479
 
2480
                    if ($currentNetwork->xmpp_active) {
340 www 2481
                        $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
2482
                        $externalCredentials->getUserBy($user->id);
616 ariadna 2483
 
2484
 
340 www 2485
                        $data['xmpp_domain'] = $currentNetwork->xmpp_domain;
2486
                        $data['xmpp_hostname'] = $currentNetwork->xmpp_hostname;
2487
                        $data['xmpp_port'] = $currentNetwork->xmpp_port;
2488
                        $data['xmpp_username'] = $externalCredentials->getUsernameXmpp();
2489
                        $data['xmpp_pasword'] = $externalCredentials->getPasswordXmpp();
2490
                        $data['inmail_username'] = $externalCredentials->getUsernameInmail();
2491
                        $data['inmail_pasword'] = $externalCredentials->getPasswordInmail();
2492
                    }
616 ariadna 2493
 
340 www 2494
                    $data = [
2495
                        'success'   => true,
2496
                        'data'      => $data
2497
                    ];
616 ariadna 2498
 
2499
 
340 www 2500
                    $this->cache->removeItem('user_share_invitation');
2501
                } else {
616 ariadna 2502
 
340 www 2503
                    $message = $result->getMessages()[0];
2504
                    if (!in_array($message, [
616 ariadna 2505
                        'ERROR_USER_NOT_FOUND',
2506
                        'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED',
2507
                        'ERROR_USER_IS_BLOCKED',
2508
                        'ERROR_USER_IS_INACTIVE',
2509
                        'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED',
2510
                        'ERROR_ENTERED_PASS_INCORRECT_2',
2511
                        'ERROR_ENTERED_PASS_INCORRECT_1',
2512
                        'ERROR_USER_REQUEST_ACCESS_IS_PENDING',
2513
                        'ERROR_USER_REQUEST_ACCESS_IS_REJECTED'
2514
 
2515
 
340 www 2516
                    ])) {
2517
                    }
616 ariadna 2518
 
340 www 2519
                    switch ($message) {
2520
                        case 'ERROR_USER_NOT_FOUND':
2521
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
2522
                            break;
616 ariadna 2523
 
340 www 2524
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
2525
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
2526
                            break;
616 ariadna 2527
 
340 www 2528
                        case 'ERROR_USER_IS_BLOCKED':
2529
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
2530
                            break;
616 ariadna 2531
 
340 www 2532
                        case 'ERROR_USER_IS_INACTIVE':
2533
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
2534
                            break;
616 ariadna 2535
 
2536
 
340 www 2537
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
2538
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
2539
                            break;
616 ariadna 2540
 
2541
 
340 www 2542
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
2543
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
2544
                            break;
616 ariadna 2545
 
2546
 
340 www 2547
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
2548
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
2549
                            break;
616 ariadna 2550
 
2551
 
340 www 2552
                        case 'ERROR_USER_REQUEST_ACCESS_IS_PENDING':
2553
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Falta verificar que pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
2554
                            break;
616 ariadna 2555
 
340 www 2556
                        case  'ERROR_USER_REQUEST_ACCESS_IS_REJECTED':
2557
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Rechazado por no pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
2558
                            break;
616 ariadna 2559
 
2560
 
340 www 2561
                        default:
2562
                            $message = 'ERROR_UNKNOWN';
2563
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
2564
                            break;
2565
                    }
616 ariadna 2566
 
2567
 
2568
 
2569
 
340 www 2570
                    $data = [
2571
                        'success'   => false,
2572
                        'data'   => $message
2573
                    ];
2574
                }
616 ariadna 2575
 
340 www 2576
                return new JsonModel($data);
2577
            } else {
2578
                $messages = [];
616 ariadna 2579
 
2580
 
2581
 
340 www 2582
                $form_messages = (array) $form->getMessages();
2583
                foreach ($form_messages  as $fieldname => $field_messages) {
616 ariadna 2584
 
340 www 2585
                    $messages[$fieldname] = array_values($field_messages);
2586
                }
616 ariadna 2587
 
340 www 2588
                return new JsonModel([
2589
                    'success'   => false,
2590
                    'data'   => $messages
2591
                ]);
2592
            }
2593
        } else if ($request->isGet()) {
616 ariadna 2594
 
340 www 2595
            $aes = '';
2596
            $jwtToken = null;
2597
            $headers = getallheaders();
616 ariadna 2598
 
2599
 
2600
            if (!empty($headers['authorization']) || !empty($headers['Authorization'])) {
2601
 
340 www 2602
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
616 ariadna 2603
 
2604
 
2605
                if (substr($token, 0, 6) == 'Bearer') {
2606
 
340 www 2607
                    $token = trim(substr($token, 7));
616 ariadna 2608
 
2609
                    if (!empty($this->config['leaderslinked.jwt.key'])) {
340 www 2610
                        $key = $this->config['leaderslinked.jwt.key'];
616 ariadna 2611
 
2612
 
340 www 2613
                        try {
2614
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
616 ariadna 2615
 
2616
 
2617
                            if (empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
340 www 2618
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
2619
                            }
616 ariadna 2620
 
340 www 2621
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
2622
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2623
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
616 ariadna 2624
                        } catch (\Exception $e) {
340 www 2625
                            //Token invalido
2626
                        }
2627
                    }
2628
                }
2629
            }
344 www 2630
 
616 ariadna 2631
 
2632
            if (!$jwtToken) {
2633
 
340 www 2634
                $aes = Functions::generatePassword(16);
616 ariadna 2635
 
340 www 2636
                $jwtToken = new JwtToken();
2637
                $jwtToken->aes = $aes;
616 ariadna 2638
 
340 www 2639
                $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
616 ariadna 2640
                if ($jwtTokenMapper->insert($jwtToken)) {
340 www 2641
                    $jwtToken = $jwtTokenMapper->fetchOne($jwtToken->id);
2642
                }
616 ariadna 2643
 
340 www 2644
                $token = '';
616 ariadna 2645
 
2646
                if (!empty($this->config['leaderslinked.jwt.key'])) {
340 www 2647
                    $issuedAt   = new \DateTimeImmutable();
2648
                    $expire     = $issuedAt->modify('+365 days')->getTimestamp();
2649
                    $serverName = $_SERVER['HTTP_HOST'];
2650
                    $payload = [
2651
                        'iat'  => $issuedAt->getTimestamp(),
2652
                        'iss'  => $serverName,
2653
                        'nbf'  => $issuedAt->getTimestamp(),
2654
                        'exp'  => $expire,
2655
                        'uuid' => $jwtToken->uuid,
2656
                    ];
616 ariadna 2657
 
2658
 
340 www 2659
                    $key = $this->config['leaderslinked.jwt.key'];
2660
                    $token = JWT::encode($payload, $key, 'HS256');
2661
                }
2662
            }
616 ariadna 2663
 
2664
 
2665
 
2666
 
2667
 
2668
 
2669
 
340 www 2670
            if ($this->config['leaderslinked.runmode.sandbox']) {
2671
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
2672
            } else {
2673
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
2674
            }
616 ariadna 2675
 
2676
 
340 www 2677
            $access_usign_social_networks = $this->config['leaderslinked.runmode.access_usign_social_networks'];
616 ariadna 2678
 
340 www 2679
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
2680
            if ($sandbox) {
2681
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
2682
            } else {
2683
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
2684
            }
616 ariadna 2685
 
2686
 
340 www 2687
            $parts = explode('.', $currentNetwork->main_hostname);
616 ariadna 2688
            if ($parts[1] === 'com') {
340 www 2689
                $replace_main = false;
2690
            } else {
2691
                $replace_main = true;
2692
            }
616 ariadna 2693
 
2694
 
340 www 2695
            $storage = Storage::getInstance($this->config, $this->adapter);
2696
            $path = $storage->getPathNetwork();
616 ariadna 2697
 
2698
            if ($currentNetwork->logo) {
340 www 2699
                $logo_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->logo);
2700
            } else {
2701
                $logo_url = '';
2702
            }
616 ariadna 2703
 
2704
            if ($currentNetwork->navbar) {
340 www 2705
                $navbar_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->navbar);
2706
            } else {
2707
                $navbar_url = '';
2708
            }
616 ariadna 2709
 
2710
            if ($currentNetwork->favico) {
340 www 2711
                $favico_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->favico);
2712
            } else {
2713
                $favico_url = '';
2714
            }
616 ariadna 2715
 
2716
 
2717
 
2718
 
340 www 2719
            $data = [
2720
                'google_map_key'                => $google_map_key,
2721
                'email'                         => '',
2722
                'remember'                      => false,
2723
                'site_key'                      => $site_key,
2724
                'theme_id'                      => $currentNetwork->theme_id,
2725
                'aes'                           => $aes,
2726
                'jwt'                           => $token,
2727
                'defaultNetwork'                => $currentNetwork->default,
2728
                'access_usign_social_networks'  => $access_usign_social_networks && $currentNetwork->default == Network::DEFAULT_YES ? 'y' : 'n',
2729
                'logo_url'                      => $logo_url,
2730
                'navbar_url'                    => $navbar_url,
2731
                'favico_url'                    => $favico_url,
2732
                'intro'                         => $currentNetwork->intro ? $currentNetwork->intro : '',
2733
                'is_logged_in'                  => $jwtToken->user_id ? true : false,
616 ariadna 2734
 
340 www 2735
            ];
616 ariadna 2736
 
2737
            if ($currentNetwork->default == Network::DEFAULT_YES) {
2738
 
2739
 
2740
 
340 www 2741
                $currentUserPlugin = $this->plugin('currentUserPlugin');
2742
                if ($currentUserPlugin->hasIdentity()) {
616 ariadna 2743
 
2744
 
340 www 2745
                    $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
2746
                    $externalCredentials->getUserBy($currentUserPlugin->getUserId());
616 ariadna 2747
 
2748
 
2749
                    if ($currentNetwork->xmpp_active) {
340 www 2750
                        $data['xmpp_domain']      = $currentNetwork->xmpp_domain;
2751
                        $data['xmpp_hostname']    = $currentNetwork->xmpp_hostname;
2752
                        $data['xmpp_port']        = $currentNetwork->xmpp_port;
2753
                        $data['xmpp_username']    = $externalCredentials->getUsernameXmpp();
2754
                        $data['xmpp_password']    = $externalCredentials->getPasswordXmpp();
2755
                        $data['inmail_username']    = $externalCredentials->getUsernameInmail();
2756
                        $data['inmail_password']    = $externalCredentials->getPasswordInmail();
2757
                    }
2758
                }
2759
            }
616 ariadna 2760
 
340 www 2761
            $data = [
2762
                'success' => true,
2763
                'data' =>  $data
2764
            ];
2765
        } else {
2766
            $data = [
2767
                'success' => false,
2768
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2769
            ];
616 ariadna 2770
 
340 www 2771
            return new JsonModel($data);
2772
        }
616 ariadna 2773
 
340 www 2774
        return new JsonModel($data);
2775
    }
1 efrain 2776
}