Proyectos de Subversion LeadersLinked - Services

Rev

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