Proyectos de Subversion LeadersLinked - Services

Rev

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