Proyectos de Subversion LeadersLinked - Services

Rev

Rev 149 | Rev 151 | 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
 
203
 
204
                    $userMapper = UserMapper::getInstance($this->adapter);
205
                    $user = $userMapper->fetchOneByEmail($email);
36 efrain 206
 
207
 
208
                    if($token) {
37 efrain 209
                        $jwtToken->user_id = $user->id;
36 efrain 210
                        $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
37 efrain 211
                        $jwtTokenMapper->update($jwtToken);
36 efrain 212
                    }
213
 
1 efrain 214
 
215
                    $navigator = get_browser(null, true);
216
                    $device_type    =  isset($navigator['device_type']) ? $navigator['device_type'] : '';
217
                    $platform       =  isset($navigator['platform']) ? $navigator['platform'] : '';
218
                    $browser        =  isset($navigator['browser']) ? $navigator['browser'] : '';
219
 
220
 
221
                    $istablet = isset($navigator['istablet']) ?  intval($navigator['istablet']) : 0;
222
                    $ismobiledevice = isset($navigator['ismobiledevice']) ? intval($navigator['ismobiledevice']) : 0;
223
                    $version = isset($navigator['version']) ? $navigator['version'] : '';
224
 
225
 
226
                    $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
227
                    $userBrowser = $userBrowserMapper->fetch($user->id, $device_type, $platform, $browser);
228
                    if ($userBrowser) {
229
                        $userBrowserMapper->update($userBrowser);
230
                    } else {
231
                        $userBrowser = new UserBrowser();
232
                        $userBrowser->user_id           = $user->id;
233
                        $userBrowser->browser           = $browser;
234
                        $userBrowser->platform          = $platform;
235
                        $userBrowser->device_type       = $device_type;
236
                        $userBrowser->is_tablet         = $istablet;
237
                        $userBrowser->is_mobile_device  = $ismobiledevice;
238
                        $userBrowser->version           = $version;
239
 
240
                        $userBrowserMapper->insert($userBrowser);
241
                    }
242
                    //
243
 
244
                    $ip = Functions::getUserIP();
245
                    $ip = $ip == '127.0.0.1' ? '148.240.211.148' : $ip;
246
 
247
                    $userIpMapper = UserIpMapper::getInstance($this->adapter);
248
                    $userIp = $userIpMapper->fetch($user->id, $ip);
249
                    if (empty($userIp)) {
250
 
251
                        if ($this->config['leaderslinked.runmode.sandbox']) {
252
                            $filename = $this->config['leaderslinked.geoip2.production_database'];
253
                        } else {
254
                            $filename = $this->config['leaderslinked.geoip2.sandbox_database'];
255
                        }
256
 
257
                        $reader = new GeoIp2Reader($filename); //GeoIP2-City.mmdb');
258
                        $record = $reader->city($ip);
259
                        if ($record) {
260
                            $userIp = new UserIp();
261
                            $userIp->user_id = $user->id;
262
                            $userIp->city = !empty($record->city->name) ? Functions::utf8_decode($record->city->name) : '';
263
                            $userIp->state_code = !empty($record->mostSpecificSubdivision->isoCode) ? Functions::utf8_decode($record->mostSpecificSubdivision->isoCode) : '';
264
                            $userIp->state_name = !empty($record->mostSpecificSubdivision->name) ? Functions::utf8_decode($record->mostSpecificSubdivision->name) : '';
265
                            $userIp->country_code = !empty($record->country->isoCode) ? Functions::utf8_decode($record->country->isoCode) : '';
266
                            $userIp->country_name = !empty($record->country->name) ? Functions::utf8_decode($record->country->name) : '';
267
                            $userIp->ip = $ip;
268
                            $userIp->latitude = !empty($record->location->latitude) ? $record->location->latitude : 0;
269
                            $userIp->longitude = !empty($record->location->longitude) ? $record->location->longitude : 0;
270
                            $userIp->postal_code = !empty($record->postal->code) ? $record->postal->code : '';
271
 
272
                            $userIpMapper->insert($userIp);
273
                        }
274
                    } else {
275
                        $userIpMapper->update($userIp);
276
                    }
277
 
24 efrain 278
                    /*
1 efrain 279
                    if ($remember) {
280
                        $expired = time() + 365 * 24 * 60 * 60;
281
 
282
                        $cookieEmail = new SetCookie('email', $email, $expired);
283
                    } else {
284
                        $expired = time() - 7200;
285
                        $cookieEmail = new SetCookie('email', '', $expired);
286
                    }
287
 
288
 
289
                    $response = $this->getResponse();
290
                    $response->getHeaders()->addHeader($cookieEmail);
24 efrain 291
                    */
292
 
293
 
1 efrain 294
 
295
 
296
 
297
                    $this->logger->info('Ingreso a LeadersLiked', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
298
 
299
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
300
 
301
                    if ($user_share_invitation) {
302
                        $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
303
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
304
                            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
305
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
306
 
307
                            if ($connection) {
308
 
309
                                if ($connection->status != Connection::STATUS_ACCEPTED) {
310
                                    $connectionMapper->approve($connection);
311
                                }
312
                            } else {
313
                                $connection = new Connection();
314
                                $connection->request_from = $user->id;
315
                                $connection->request_to = $userRedirect->id;
316
                                $connection->status = Connection::STATUS_ACCEPTED;
317
 
318
                                $connectionMapper->insert($connection);
319
                            }
320
                        }
321
                    }
322
 
323
 
324
 
325
                    $data = [
326
                        'success'   => true,
327
                        'data'      => $this->url()->fromRoute('dashboard'),
328
                    ];
329
 
330
                    $this->cache->removeItem('user_share_invitation');
331
                } else {
332
 
333
                    $message = $result->getMessages()[0];
334
                    if (!in_array($message, [
335
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
336
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
337
                        'ERROR_ENTERED_PASS_INCORRECT_1', 'ERROR_USER_REQUEST_ACCESS_IS_PENDING', 'ERROR_USER_REQUEST_ACCESS_IS_REJECTED'
338
 
339
 
340
                    ])) {
341
                    }
342
 
343
                    switch ($message) {
344
                        case 'ERROR_USER_NOT_FOUND':
345
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
346
                            break;
347
 
348
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
349
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
350
                            break;
351
 
352
                        case 'ERROR_USER_IS_BLOCKED':
353
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
354
                            break;
355
 
356
                        case 'ERROR_USER_IS_INACTIVE':
357
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
358
                            break;
359
 
360
 
361
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
362
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
363
                            break;
364
 
365
 
366
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
367
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
368
                            break;
369
 
370
 
371
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
372
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
373
                            break;
374
 
375
 
376
                        case 'ERROR_USER_REQUEST_ACCESS_IS_PENDING':
377
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Falta verificar que pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
378
                            break;
379
 
380
                        case  'ERROR_USER_REQUEST_ACCESS_IS_REJECTED':
381
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Rechazado por no pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
382
                            break;
383
 
384
 
385
                        default:
386
                            $message = 'ERROR_UNKNOWN';
387
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
388
                            break;
389
                    }
390
 
391
 
392
 
393
 
394
                    $data = [
395
                        'success'   => false,
396
                        'data'   => $message
397
                    ];
398
                }
399
 
67 efrain 400
                return new JsonModel($data);
1 efrain 401
            } else {
402
                $messages = [];
403
 
404
 
405
 
406
                $form_messages = (array) $form->getMessages();
407
                foreach ($form_messages  as $fieldname => $field_messages) {
408
 
409
                    $messages[$fieldname] = array_values($field_messages);
410
                }
67 efrain 411
 
412
                return new JsonModel([
1 efrain 413
                    'success'   => false,
414
                    'data'   => $messages
67 efrain 415
                ]);
1 efrain 416
            }
417
        } else if ($request->isGet()) {
418
 
120 efrain 419
            $aes = '';
107 efrain 420
            $jwtToken = null;
421
            $headers = getallheaders();
1 efrain 422
 
23 efrain 423
 
107 efrain 424
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
425
 
426
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
427
 
428
 
429
                if (substr($token, 0, 6 ) == 'Bearer') {
430
 
431
                    $token = trim(substr($token, 7));
432
 
433
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
434
                        $key = $this->config['leaderslinked.jwt.key'];
435
 
436
 
437
                        try {
438
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
439
 
440
 
441
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
442
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
443
                            }
444
 
445
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
446
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
447
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
448
                        } catch(\Exception $e) {
449
                            //Token invalido
450
                        }
451
                    }
452
                }
1 efrain 453
            }
23 efrain 454
 
107 efrain 455
            if(!$jwtToken) {
23 efrain 456
 
107 efrain 457
                $aes = Functions::generatePassword(16);
23 efrain 458
 
107 efrain 459
                $jwtToken = new JwtToken();
460
                $jwtToken->aes = $aes;
23 efrain 461
 
107 efrain 462
                $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
463
                if($jwtTokenMapper->insert($jwtToken)) {
464
                    $jwtToken = $jwtTokenMapper->fetchOne($jwtToken->id);
465
                }
466
 
467
                $token = '';
468
 
469
                if(!empty($this->config['leaderslinked.jwt.key'])) {
470
                    $issuedAt   = new \DateTimeImmutable();
471
                    $expire     = $issuedAt->modify('+24 hours')->getTimestamp();
472
                    $serverName = $_SERVER['HTTP_HOST'];
473
                    $payload = [
474
                        'iat'  => $issuedAt->getTimestamp(),
475
                        'iss'  => $serverName,
476
                        'nbf'  => $issuedAt->getTimestamp(),
477
                        'exp'  => $expire,
478
                        'uuid' => $jwtToken->uuid,
479
                    ];
480
 
481
 
482
                    $key = $this->config['leaderslinked.jwt.key'];
483
                    $token = JWT::encode($payload, $key, 'HS256');
484
                }
23 efrain 485
            }
486
 
487
 
488
 
107 efrain 489
 
490
 
1 efrain 491
 
23 efrain 492
 
1 efrain 493
            if ($this->config['leaderslinked.runmode.sandbox']) {
494
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
495
            } else {
496
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
497
            }
498
 
499
 
500
            $access_usign_social_networks = $this->config['leaderslinked.runmode.access_usign_social_networks'];
501
 
502
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
503
            if ($sandbox) {
504
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
505
            } else {
506
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
507
            }
149 efrain 508
 
509
            echo '<pre>';
510
            print_r($currentNetwork);
511
            echo '</pre>';
150 efrain 512
 
1 efrain 513
 
148 efrain 514
 
515
 
516
            $logo_url = $this->url()->fromRoute('storage-network', ['type' => 'logo'],['force_canonical' => true]);
517
            $logo_url = str_replace($currentNetwork->main_hostname, $currentNetwork->service_hostname, $logo_url);
518
            if($currentNetwork->alternative_hostname) {
519
                $logo_url = str_replace($currentNetwork->alternative_hostname, $currentNetwork->service_hostname, $logo_url);
520
 
521
            }
522
 
523
 
524
            $navbar_url = $this->url()->fromRoute('storage-network', ['type' => 'navbar'],['force_canonical' => true]);
525
            $navbar_url = str_replace($currentNetwork->main_hostname, $currentNetwork->service_hostname, $navbar_url);
526
            if($currentNetwork->alternative_hostname) {
527
                $navbar_url = str_replace($currentNetwork->alternative_hostname, $currentNetwork->service_hostname, $navbar_url);
528
 
529
            }
530
 
531
 
532
            $favico_url= $this->url()->fromRoute('storage-network', ['type' => 'favico'],['force_canonical' => true]);
533
            $favico_url = str_replace($currentNetwork->main_hostname, $currentNetwork->service_hostname, $favico_url);
534
            if($currentNetwork->alternative_hostname) {
535
                $favico_url = str_replace($currentNetwork->alternative_hostname, $currentNetwork->service_hostname, $favico_url);
536
 
537
            }
150 efrain 538
 
539
            exit;
1 efrain 540
 
541
            $data = [
23 efrain 542
                'google_map_key'                => $google_map_key,
543
                'email'                         => '',
544
                'remember'                      => false,
545
                'site_key'                      => $site_key,
546
                'theme_id'                      => $currentNetwork->theme_id,
547
                'aes'                           => $aes,
548
                'jwt'                           => $token,
549
                'defaultNetwork'                => $currentNetwork->default,
550
                'access_usign_social_networks'  => $access_usign_social_networks && $currentNetwork->default == Network::DEFAULT_YES ? 'y' : 'n',
148 efrain 551
                'logo_url'                      => $logo_url,
552
                'navbar_url'                    => $navbar_url,
553
                'favico_url'                    => $favico_url,
108 efrain 554
                'intro'                         => $currentNetwork->intro ? $currentNetwork->intro : '',
107 efrain 555
                'is_logged_in'                  => $jwtToken->user_id ? true : false,
1 efrain 556
 
557
            ];
49 efrain 558
 
559
            $data = [
560
                'success' => true,
50 efrain 561
                'data' =>  $data
49 efrain 562
            ];
1 efrain 563
 
564
        } else {
565
            $data = [
566
                'success' => false,
567
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
568
            ];
569
 
67 efrain 570
            return new JsonModel($data);
1 efrain 571
        }
572
 
67 efrain 573
        return new JsonModel($data);
1 efrain 574
    }
575
 
576
    public function facebookAction()
577
    {
578
 
579
        $request = $this->getRequest();
580
        if ($request->isGet()) {
581
            /*
582
          //  try {
583
                $app_id = $this->config['leaderslinked.facebook.app_id'];
584
                $app_password = $this->config['leaderslinked.facebook.app_password'];
585
                $app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];
586
                //$app_url_auth = $this->config['leaderslinked.facebook.app_url_auth'];
587
                //$redirect_url = $this->config['leaderslinked.facebook.app_redirect_url'];
588
 
589
                [facebook]
590
                app_id=343770226993130
591
                app_password=028ee729090fd591e50a17a786666c12
592
                app_graph_version=v17
593
                app_redirect_url=https://leaderslinked.com/oauth/facebook
594
 
595
                https://www.facebook.com/v17.0/dialog/oauth?client_id=343770226993130&redirect_uri= https://dev.leaderslinked.com/oauth/facebook&state=AE12345678
596
 
597
 
598
                $s = 'https://www.facebook.com/v17.0/dialog/oauth' .
599
                    '?client_id='
600
                    '&redirect_uri={"https://www.domain.com/login"}
601
                    '&state={"{st=state123abc,ds=123456789}"}
602
 
603
                $fb = new \Facebook\Facebook([
604
                    'app_id' => $app_id,
605
                    'app_secret' => $app_password,
606
                    'default_graph_version' => $app_graph_version,
607
                ]);
608
 
609
                $app_url_auth =  $this->url()->fromRoute('oauth/facebook', [], ['force_canonical' => true]);
610
                $helper = $fb->getRedirectLoginHelper();
611
                $permissions = ['email', 'public_profile']; // Optional permissions
612
                $facebookUrl = $helper->getLoginUrl($app_url_auth, $permissions);
613
 
614
 
615
 
616
                return new JsonModel([
617
                    'success' => false,
618
                    'data' => $facebookUrl
619
                ]);
620
            } catch (\Throwable $e) {
621
                return new JsonModel([
622
                    'success' => false,
623
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_FACEBOOK'
624
                ]);
625
            }*/
626
        } else {
627
            return new JsonModel([
628
                'success' => false,
629
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
630
            ]);
631
        }
632
    }
633
 
634
    public function twitterAction()
635
    {
636
        $request = $this->getRequest();
637
        if ($request->isGet()) {
638
 
639
            try {
640
                if ($this->config['leaderslinked.runmode.sandbox']) {
641
 
642
                    $twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];
643
                    $twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];
644
                } else {
645
                    $twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];
646
                    $twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];
647
                }
648
 
649
                /*
650
                 echo '$twitter_api_key = ' . $twitter_api_key . PHP_EOL;
651
                 echo '$twitter_api_secret = ' . $twitter_api_secret . PHP_EOL;
652
                 exit;
653
                 */
654
 
655
                //Twitter
656
                //$redirect_url =  $this->url()->fromRoute('oauth/twitter', [], ['force_canonical' => true]);
657
                $redirect_url = $this->config['leaderslinked.twitter.app_redirect_url'];
658
                $twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret);
659
                $request_token =  $twitter->oauth('oauth/request_token', ['oauth_callback' => $redirect_url]);
660
                $twitterUrl = $twitter->url('oauth/authorize', ['oauth_token' => $request_token['oauth_token']]);
661
 
662
                $twitterSession = new \Laminas\Session\Container('twitter');
663
                $twitterSession->oauth_token = $request_token['oauth_token'];
664
                $twitterSession->oauth_token_secret = $request_token['oauth_token_secret'];
665
 
666
                return new JsonModel([
667
                    'success' => true,
668
                    'data' =>  $twitterUrl
669
                ]);
670
            } catch (\Throwable $e) {
671
                return new JsonModel([
672
                    'success' => false,
673
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_TWITTER'
674
                ]);
675
            }
676
        } else {
677
            return new JsonModel([
678
                'success' => false,
679
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
680
            ]);
681
        }
682
    }
683
 
684
    public function googleAction()
685
    {
686
        $request = $this->getRequest();
687
        if ($request->isGet()) {
688
 
689
            try {
690
 
691
 
692
                //Google
693
                $google = new \Google_Client();
694
                $google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');
695
                $google->setAccessType("offline");        // offline access
696
 
697
                $google->setIncludeGrantedScopes(true);   // incremental auth
698
 
699
                $google->addScope('profile');
700
                $google->addScope('email');
701
 
702
                // $redirect_url =  $this->url()->fromRoute('oauth/google', [], ['force_canonical' => true]);
703
                $redirect_url = $this->config['leaderslinked.google_auth.app_redirect_url'];
704
 
705
                $google->setRedirectUri($redirect_url);
706
                $googleUrl = $google->createAuthUrl();
707
 
708
                return new JsonModel([
709
                    'success' => true,
710
                    'data' =>  $googleUrl
711
                ]);
712
            } catch (\Throwable $e) {
713
                return new JsonModel([
714
                    'success' => false,
715
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_GOOGLE'
716
                ]);
717
            }
718
        } else {
719
            return new JsonModel([
720
                'success' => false,
721
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
722
            ]);
723
        }
724
    }
725
 
726
    public function signoutAction()
727
    {
728
        $currentUserPlugin = $this->plugin('currentUserPlugin');
729
        $currentUser = $currentUserPlugin->getRawUser();
730
        if ($currentUserPlugin->hasImpersonate()) {
731
 
732
 
733
            $userMapper = UserMapper::getInstance($this->adapter);
734
            $userMapper->leaveImpersonate($currentUser->id);
735
 
736
            $networkMapper = NetworkMapper::getInstance($this->adapter);
737
            $network = $networkMapper->fetchOne($currentUser->network_id);
738
 
739
 
740
            if (!$currentUser->one_time_password) {
741
                $one_time_password = Functions::generatePassword(25);
742
 
743
                $currentUser->one_time_password = $one_time_password;
744
 
745
                $userMapper = UserMapper::getInstance($this->adapter);
746
                $userMapper->updateOneTimePassword($currentUser, $one_time_password);
747
            }
748
 
749
 
750
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
751
            if ($sandbox) {
752
                $salt = $this->config['leaderslinked.backend.sandbox_salt'];
753
            } else {
754
                $salt = $this->config['leaderslinked.backend.production_salt'];
755
            }
756
 
757
            $rand = 1000 + mt_rand(1, 999);
758
            $timestamp = time();
759
            $password = md5($currentUser->one_time_password . '-' . $rand . '-' . $timestamp . '-' . $salt);
760
 
761
            $params = [
762
                'user_uuid' => $currentUser->uuid,
763
                'password' => $password,
764
                'rand' => $rand,
765
                'time' => $timestamp,
766
            ];
767
 
768
            $currentUserPlugin->clearIdentity();
769
 
770
            return new JsonModel([
771
                'success'   => true,
772
                'data'      => [
773
                    'message' => 'LABEL_SIGNOUT_SUCCESSFULLY',
774
                    'url' => 'https://' . $network->main_hostname . '/signin/impersonate' . '?' . http_build_query($params)
775
                ],
776
 
777
            ]);
778
 
779
 
780
           // $url = 'https://' . $network->main_hostname . '/signin/impersonate' . '?' . http_build_query($params);
781
           // return $this->redirect()->toUrl($url);
782
        } else {
783
 
784
 
785
            if ($currentUserPlugin->hasIdentity()) {
786
 
787
                $this->logger->info('Desconexión de LeadersLinked', ['user_id' => $currentUserPlugin->getUserId(), 'ip' => Functions::getUserIP()]);
788
            }
789
 
790
            $currentUserPlugin->clearIdentity();
791
 
792
           // return $this->redirect()->toRoute('home');
793
 
794
            return new JsonModel([
795
                'success'   => true,
796
                'data'      => [
797
                    'message' => 'LABEL_SIGNOUT_SUCCESSFULLY',
798
                    'url' => '',
799
                ],
800
 
801
            ]);
802
        }
803
    }
804
 
805
 
806
    public function resetPasswordAction()
807
    {
808
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
809
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
810
 
811
 
812
        $flashMessenger = $this->plugin('FlashMessenger');
813
        $code =  Functions::sanitizeFilterString($this->params()->fromRoute('code', ''));
814
 
815
        $userMapper = UserMapper::getInstance($this->adapter);
816
        $user = $userMapper->fetchOneByPasswordResetKeyAndNetworkId($code, $currentNetwork->id);
817
        if (!$user) {
818
            $this->logger->err('Restablecer contraseña - Error código no existe', ['ip' => Functions::getUserIP()]);
819
 
820
            return new JsonModel([
821
                'success'   => true,
822
                'data'      => 'ERROR_PASSWORD_RECOVER_CODE_IS_INVALID'
823
            ]);
824
 
825
        }
826
 
827
 
828
 
829
        $password_generated_on = strtotime($user->password_generated_on);
830
        $expiry_time = $password_generated_on + $this->config['leaderslinked.security.reset_password_expired'];
831
        if (time() > $expiry_time) {
832
            $this->logger->err('Restablecer contraseña - Error código expirado', ['ip' => Functions::getUserIP()]);
833
 
834
            return new JsonModel([
835
                'success'   => true,
836
                'data'      => 'ERROR_PASSWORD_RECOVER_CODE_HAS_EXPIRED'
837
            ]);
838
        }
839
 
840
        $request = $this->getRequest();
841
        if ($request->isPost()) {
842
            $dataPost = $request->getPost()->toArray();
843
            if (empty($_SESSION['aes'])) {
844
                return new JsonModel([
845
                    'success'   => false,
846
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
847
                ]);
848
 
849
 
850
            }
851
 
852
            if (!empty($dataPost['password'])) {
853
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
854
            }
855
            if (!empty($dataPost['confirmation'])) {
856
                $dataPost['confirmation'] = CryptoJsAes::decrypt($dataPost['confirmation'], $_SESSION['aes']);
857
            }
858
 
859
 
860
 
861
            $form = new ResetPasswordForm($this->config);
862
            $form->setData($dataPost);
863
 
864
            if ($form->isValid()) {
865
                $data = (array) $form->getData();
866
                $password = $data['password'];
867
 
868
 
869
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
870
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);
871
 
872
                $oldPassword = false;
873
                foreach ($userPasswords as $userPassword) {
874
                    if (password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password)) {
875
                        $oldPassword = true;
876
                        break;
877
                    }
878
                }
879
 
880
                if ($oldPassword) {
881
                    $this->logger->err('Restablecer contraseña - Error contraseña ya utilizada anteriormente', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
882
 
883
                    return new JsonModel([
884
                        'success'   => false,
885
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
886
 
887
                    ]);
888
                } else {
889
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
890
 
891
 
892
                    $result = $userMapper->updatePassword($user, $password_hash);
893
                    if ($result) {
894
 
895
                        $userPassword = new UserPassword();
896
                        $userPassword->user_id = $user->id;
897
                        $userPassword->password = $password_hash;
898
                        $userPasswordMapper->insert($userPassword);
899
 
900
 
901
                        $this->logger->info('Restablecer contraseña realizado', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
902
 
903
 
904
                        $flashMessenger->addSuccessMessage('LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED');
905
 
906
                        return new JsonModel([
907
                            'success'   => true,
138 efrain 908
                            'data'      => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED'
1 efrain 909
 
910
                        ]);
911
                    } else {
912
                        $this->logger->err('Restablecer contraseña - Error desconocido', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
913
 
914
                        return new JsonModel([
915
                            'success'   => false,
916
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
917
 
918
                        ]);
919
                    }
920
                }
921
            } else {
922
                $form_messages =  $form->getMessages('captcha');
923
                if (!empty($form_messages)) {
924
                    return new JsonModel([
925
                        'success'   => false,
926
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
927
                    ]);
928
                }
929
 
930
                $messages = [];
931
 
932
                $form_messages = (array) $form->getMessages();
933
                foreach ($form_messages  as $fieldname => $field_messages) {
934
                    $messages[$fieldname] = array_values($field_messages);
935
                }
936
 
937
                return new JsonModel([
938
                    'success'   => false,
939
                    'data'   => $messages
940
                ]);
941
            }
942
        } else if ($request->isGet()) {
943
 
944
            if (empty($_SESSION['aes'])) {
945
                $_SESSION['aes'] = Functions::generatePassword(16);
946
            }
947
 
948
            if ($this->config['leaderslinked.runmode.sandbox']) {
949
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
950
            } else {
951
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
952
            }
953
 
954
 
955
            return new JsonModel([
956
                'code' => $code,
957
                'site_key' => $site_key,
958
                'aes'       => $_SESSION['aes'],
959
                'defaultNetwork' => $currentNetwork->default,
960
            ]);
961
 
962
        }
963
 
964
 
965
 
966
        return new JsonModel([
967
            'success' => false,
968
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
969
        ]);
970
    }
971
 
972
    public function forgotPasswordAction()
973
    {
974
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
975
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
976
 
977
 
978
 
979
        $request = $this->getRequest();
980
        if ($request->isPost()) {
981
            $dataPost = $request->getPost()->toArray();
982
            if (empty($_SESSION['aes'])) {
983
                return new JsonModel([
984
                    'success'   => false,
985
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
986
                ]);
987
            }
988
 
989
            if (!empty($dataPost['email'])) {
990
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
991
            }
992
 
993
            $form = new ForgotPasswordForm($this->config);
994
            $form->setData($dataPost);
995
 
996
            if ($form->isValid()) {
997
                $dataPost = (array) $form->getData();
998
                $email      = $dataPost['email'];
999
 
1000
                $userMapper = UserMapper::getInstance($this->adapter);
1001
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1002
                if (!$user) {
1003
                    $this->logger->err('Olvidó contraseña ' . $email . '- Email no existe ', ['ip' => Functions::getUserIP()]);
1004
 
1005
                    return new JsonModel([
1006
                        'success' => false,
1007
                        'data' =>  'ERROR_EMAIL_IS_NOT_REGISTERED'
1008
                    ]);
1009
                } else {
1010
                    if ($user->status == User::STATUS_INACTIVE) {
1011
                        return new JsonModel([
1012
                            'success' => false,
1013
                            'data' =>  'ERROR_USER_IS_INACTIVE'
1014
                        ]);
1015
                    } else if ($user->email_verified == User::EMAIL_VERIFIED_NO) {
1016
                        $this->logger->err('Olvidó contraseña - Email no verificado ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1017
 
1018
                        return new JsonModel([
1019
                            'success' => false,
1020
                            'data' => 'ERROR_EMAIL_HAS_NOT_BEEN_VERIFIED'
1021
                        ]);
1022
                    } else {
1023
                        $password_reset_key = md5($user->email . time());
1024
                        $userMapper->updatePasswordResetKey((int) $user->id, $password_reset_key);
1025
 
1026
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1027
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RESET_PASSWORD, $currentNetwork->id);
1028
                        if ($emailTemplate) {
1029
                            $arrayCont = [
1030
                                'firstname'             => $user->first_name,
1031
                                'lastname'              => $user->last_name,
1032
                                'other_user_firstname'  => '',
1033
                                'other_user_lastname'   => '',
1034
                                'company_name'          => '',
1035
                                'group_name'            => '',
1036
                                'content'               => '',
1037
                                'code'                  => '',
1038
                                'link'                  => $this->url()->fromRoute('reset-password', ['code' => $password_reset_key], ['force_canonical' => true])
1039
                            ];
1040
 
1041
                            $email = new QueueEmail($this->adapter);
1042
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1043
                        }
1044
                        $flashMessenger = $this->plugin('FlashMessenger');
1045
                        $flashMessenger->addSuccessMessage('LABEL_RECOVERY_LINK_WAS_SENT_TO_YOUR_EMAIL');
1046
 
1047
                        $this->logger->info('Olvidó contraseña - Se envio link de recuperación ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1048
 
1049
                        return new JsonModel([
1050
                            'success' => true,
1051
                        ]);
1052
                    }
1053
                }
1054
            } else {
1055
 
1056
 
1057
                $form_messages =  $form->getMessages('captcha');
1058
 
1059
 
1060
 
1061
                if (!empty($form_messages)) {
1062
                    return new JsonModel([
1063
                        'success'   => false,
1064
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1065
                    ]);
1066
                }
1067
 
1068
                $messages = [];
1069
                $form_messages = (array) $form->getMessages();
1070
                foreach ($form_messages  as $fieldname => $field_messages) {
1071
                    $messages[$fieldname] = array_values($field_messages);
1072
                }
1073
 
1074
                return new JsonModel([
1075
                    'success'   => false,
1076
                    'data'      => $messages
1077
                ]);
1078
            }
1079
        } else  if ($request->isGet()) {
1080
 
1081
            if (empty($_SESSION['aes'])) {
1082
                $_SESSION['aes'] = Functions::generatePassword(16);
1083
            }
1084
 
1085
            if ($this->config['leaderslinked.runmode.sandbox']) {
1086
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1087
            } else {
1088
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1089
            }
1090
 
1091
            return new JsonModel([
1092
                'site_key'  => $site_key,
1093
                'aes'       => $_SESSION['aes'],
1094
                'defaultNetwork' => $currentNetwork->default,
1095
            ]);
1096
        }
1097
 
1098
        return new JsonModel([
1099
            'success' => false,
1100
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1101
        ]);
1102
    }
1103
 
1104
    public function signupAction()
1105
    {
1106
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1107
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1108
 
1109
 
1110
        $request = $this->getRequest();
1111
        if ($request->isPost()) {
1112
            $dataPost = $request->getPost()->toArray();
1113
 
1114
            if (empty($_SESSION['aes'])) {
1115
                return new JsonModel([
1116
                    'success'   => false,
1117
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
1118
                ]);
1119
            }
1120
 
1121
            if (!empty($dataPost['email'])) {
1122
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
1123
            }
1124
 
1125
            if (!empty($dataPost['password'])) {
1126
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
1127
            }
1128
 
1129
            if (!empty($dataPost['confirmation'])) {
1130
                $dataPost['confirmation'] = CryptoJsAes::decrypt($dataPost['confirmation'], $_SESSION['aes']);
1131
            }
1132
 
1133
            if (empty($dataPost['is_adult'])) {
1134
                $dataPost['is_adult'] = User::IS_ADULT_NO;
1135
            } else {
1136
                $dataPost['is_adult'] = $dataPost['is_adult'] == User::IS_ADULT_YES ? User::IS_ADULT_YES : User::IS_ADULT_NO;
1137
            }
1138
 
1139
 
1140
 
1141
            $form = new SignupForm($this->config);
1142
            $form->setData($dataPost);
1143
 
1144
            if ($form->isValid()) {
1145
                $dataPost = (array) $form->getData();
1146
 
1147
                $email = $dataPost['email'];
1148
 
1149
                $userMapper = UserMapper::getInstance($this->adapter);
1150
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1151
                if ($user) {
1152
                    $this->logger->err('Registro ' . $email . '- Email ya  existe ', ['ip' => Functions::getUserIP()]);
1153
 
1154
 
1155
 
1156
                    return new JsonModel([
1157
                        'success' => false,
1158
                        'data' => 'ERROR_EMAIL_IS_REGISTERED'
1159
                    ]);
1160
                } else {
1161
 
1162
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
1163
 
1164
 
1165
                    if ($user_share_invitation) {
1166
                        $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
1167
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE) {
1168
                            $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1169
 
1170
                            $user = new User();
1171
                            $user->network_id           = $currentNetwork->id;
1172
                            $user->email                = $dataPost['email'];
1173
                            $user->first_name           = $dataPost['first_name'];
1174
                            $user->last_name            = $dataPost['last_name'];
1175
                            $user->usertype_id          = UserType::USER;
1176
                            $user->password             = $password_hash;
1177
                            $user->password_updated_on  = date('Y-m-d H:i:s');
1178
                            $user->status               = User::STATUS_ACTIVE;
1179
                            $user->blocked              = User::BLOCKED_NO;
1180
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
1181
                            $user->login_attempt        = 0;
1182
                            $user->is_adult             = $dataPost['is_adult'];
1183
                            $user->request_access       = User::REQUEST_ACCESS_APPROVED;
1184
 
1185
 
1186
 
1187
 
1188
 
1189
                            if ($userMapper->insert($user)) {
1190
 
1191
                                $userPassword = new UserPassword();
1192
                                $userPassword->user_id = $user->id;
1193
                                $userPassword->password = $password_hash;
1194
 
1195
                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1196
                                $userPasswordMapper->insert($userPassword);
1197
 
1198
 
1199
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1200
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1201
 
1202
                                if ($connection) {
1203
 
1204
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1205
                                        $connectionMapper->approve($connection);
1206
                                    }
1207
                                } else {
1208
                                    $connection = new Connection();
1209
                                    $connection->request_from = $user->id;
1210
                                    $connection->request_to = $userRedirect->id;
1211
                                    $connection->status = Connection::STATUS_ACCEPTED;
1212
 
1213
                                    $connectionMapper->insert($connection);
1214
                                }
1215
 
1216
 
1217
                                $this->cache->removeItem('user_share_invitation');
1218
 
1219
 
1220
 
1221
                                $data = [
1222
                                    'success'   => true,
1223
                                    'data'      => $this->url()->fromRoute('home'),
1224
                                ];
1225
 
1226
 
1227
                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1228
 
1229
                                return new JsonModel($data);
1230
                            }
1231
                        }
1232
                    }
1233
 
1234
 
1235
 
1236
 
1237
                    $timestamp = time();
1238
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);
1239
 
1240
                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1241
 
1242
                    $user = new User();
1243
                    $user->network_id           = $currentNetwork->id;
1244
                    $user->email                = $dataPost['email'];
1245
                    $user->first_name           = $dataPost['first_name'];
1246
                    $user->last_name            = $dataPost['last_name'];
1247
                    $user->usertype_id          = UserType::USER;
1248
                    $user->password             = $password_hash;
1249
                    $user->password_updated_on  = date('Y-m-d H:i:s');
1250
                    $user->activation_key       = $activation_key;
1251
                    $user->status               = User::STATUS_INACTIVE;
1252
                    $user->blocked              = User::BLOCKED_NO;
1253
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
1254
                    $user->login_attempt        = 0;
1255
 
1256
                    if ($currentNetwork->default == Network::DEFAULT_YES) {
1257
                        $user->request_access = User::REQUEST_ACCESS_APPROVED;
1258
                    } else {
1259
                        $user->request_access = User::REQUEST_ACCESS_PENDING;
1260
                    }
1261
 
1262
 
1263
 
1264
                    if ($userMapper->insert($user)) {
1265
 
1266
                        $userPassword = new UserPassword();
1267
                        $userPassword->user_id = $user->id;
1268
                        $userPassword->password = $password_hash;
1269
 
1270
                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1271
                        $userPasswordMapper->insert($userPassword);
1272
 
1273
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1274
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
1275
                        if ($emailTemplate) {
1276
                            $arrayCont = [
1277
                                'firstname'             => $user->first_name,
1278
                                'lastname'              => $user->last_name,
1279
                                'other_user_firstname'  => '',
1280
                                'other_user_lastname'   => '',
1281
                                'company_name'          => '',
1282
                                'group_name'            => '',
1283
                                'content'               => '',
1284
                                'code'                  => '',
1285
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
1286
                            ];
1287
 
1288
                            $email = new QueueEmail($this->adapter);
1289
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1290
                        }
1291
                        $flashMessenger = $this->plugin('FlashMessenger');
1292
                        $flashMessenger->addSuccessMessage('LABEL_REGISTRATION_DONE');
1293
 
1294
                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1295
 
1296
                        return new JsonModel([
1297
                            'success' => true,
1298
                        ]);
1299
                    } else {
1300
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);
1301
 
1302
                        return new JsonModel([
1303
                            'success' => false,
1304
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1305
                        ]);
1306
                    }
1307
                }
1308
            } else {
1309
 
1310
                $form_messages =  $form->getMessages('captcha');
1311
                if (!empty($form_messages)) {
1312
                    return new JsonModel([
1313
                        'success'   => false,
1314
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1315
                    ]);
1316
                }
1317
 
1318
                $messages = [];
1319
 
1320
                $form_messages = (array) $form->getMessages();
1321
                foreach ($form_messages  as $fieldname => $field_messages) {
1322
                    $messages[$fieldname] = array_values($field_messages);
1323
                }
1324
 
1325
                return new JsonModel([
1326
                    'success'   => false,
1327
                    'data'   => $messages
1328
                ]);
1329
            }
1330
        } else if ($request->isGet()) {
1331
 
1332
            if (empty($_SESSION['aes'])) {
1333
                $_SESSION['aes'] = Functions::generatePassword(16);
1334
            }
1335
 
1336
            if ($this->config['leaderslinked.runmode.sandbox']) {
1337
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1338
            } else {
1339
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1340
            }
1341
 
1342
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
1343
 
1344
            return new JsonModel([
1345
                'site_key'  => $site_key,
1346
                'aes'       => $_SESSION['aes'],
1347
                'defaultNetwork' => $currentNetwork->default,
1348
            ]);
1349
        }
1350
 
1351
        return new JsonModel([
1352
            'success' => false,
1353
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1354
        ]);
1355
    }
1356
 
1357
    public function activateAccountAction()
1358
    {
1359
 
1360
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1361
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1362
 
1363
 
1364
 
1365
        $request = $this->getRequest();
1366
        if ($request->isGet()) {
1367
            $code   =  Functions::sanitizeFilterString($this->params()->fromRoute('code'));
1368
            $userMapper = UserMapper::getInstance($this->adapter);
1369
            $user = $userMapper->fetchOneByActivationKeyAndNetworkId($code, $currentNetwork->id);
1370
 
1371
            $flashMessenger = $this->plugin('FlashMessenger');
1372
 
1373
            if ($user) {
1374
                if (User::EMAIL_VERIFIED_YES == $user->email_verified) {
1375
 
1376
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1377
 
1378
                    $flashMessenger->addErrorMessage('ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED');
1379
                } else {
1380
 
1381
                    if ($userMapper->activateAccount((int) $user->id)) {
1382
 
1383
                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1384
 
1385
 
1386
 
1387
                        $user_share_invitation = $this->cache->getItem('user_share_invitation');
1388
 
1389
                        if ($user_share_invitation) {
1390
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
1391
                            if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
1392
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1393
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1394
 
1395
                                if ($connection) {
1396
 
1397
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1398
                                        $connectionMapper->approve($connection);
1399
                                    }
1400
                                } else {
1401
                                    $connection = new Connection();
1402
                                    $connection->request_from = $user->id;
1403
                                    $connection->request_to = $userRedirect->id;
1404
                                    $connection->status = Connection::STATUS_ACCEPTED;
1405
 
1406
                                    $connectionMapper->insert($connection);
1407
                                }
1408
                            }
1409
                        }
1410
 
1411
 
1412
 
1413
                        $this->cache->removeItem('user_share_invitation');
1414
 
1415
 
1416
                        if ($currentNetwork->default == Network::DEFAULT_YES) {
1417
                            $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED');
1418
                        } else {
1419
 
1420
                            $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1421
                            $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_REQUEST_ACCESS_PENDING, $currentNetwork->id);
1422
 
1423
                            if ($emailTemplate) {
1424
                                $arrayCont = [
1425
                                    'firstname'             => $user->first_name,
1426
                                    'lastname'              => $user->last_name,
1427
                                    'other_user_firstname'  => '',
1428
                                    'other_user_lastname'   => '',
1429
                                    'company_name'          => '',
1430
                                    'group_name'            => '',
1431
                                    'content'               => '',
1432
                                    'code'                  => '',
1433
                                    'link'                  => '',
1434
                                ];
1435
 
1436
                                $email = new QueueEmail($this->adapter);
1437
                                $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1438
                            }
1439
 
1440
 
1441
                            $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED_WE_ARE_VERIFYING_YOUR_INFORMATION');
1442
                        }
1443
                    } else {
1444
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1445
 
1446
                        $flashMessenger->addErrorMessage('ERROR_THERE_WAS_AN_ERROR');
1447
                    }
1448
                }
1449
            } else {
1450
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);
1451
 
1452
                $flashMessenger->addErrorMessage('ERROR_ACTIVATION_CODE_IS_NOT_VALID');
1453
            }
1454
 
1455
            return $this->redirect()->toRoute('home');
1456
        } else {
1457
            $response = [
1458
                'success' => false,
1459
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1460
            ];
1461
        }
1462
 
1463
        return new JsonModel($response);
1464
    }
1465
 
1466
 
1467
 
1468
    public function onroomAction()
1469
    {
1470
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1471
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1472
 
1473
 
1474
 
1475
        $request = $this->getRequest();
1476
 
1477
        if ($request->isPost()) {
1478
 
1479
            $dataPost = $request->getPost()->toArray();
1480
 
1481
 
1482
            $form = new  MoodleForm();
1483
            $form->setData($dataPost);
1484
            if ($form->isValid()) {
1485
 
1486
                $dataPost   = (array) $form->getData();
1487
                $username   = $dataPost['username'];
1488
                $password   = $dataPost['password'];
1489
                $timestamp  = $dataPost['timestamp'];
1490
                $rand       = $dataPost['rand'];
1491
                $data       = $dataPost['data'];
1492
 
1493
                $config_username    = $this->config['leaderslinked.moodle.username'];
1494
                $config_password    = $this->config['leaderslinked.moodle.password'];
1495
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1496
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
1497
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
1498
 
1499
 
1500
 
1501
 
1502
                if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1503
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
1504
                    exit;
1505
                }
1506
 
1507
                if ($username != $config_username) {
1508
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
1509
                    exit;
1510
                }
1511
 
1512
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1513
                if (!$dt) {
1514
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
1515
                    exit;
1516
                }
1517
 
1518
                $t0 = $dt->getTimestamp();
1519
                $t1 = strtotime('-5 minutes');
1520
                $t2 = strtotime('+5 minutes');
1521
 
1522
                if ($t0 < $t1 || $t0 > $t2) {
1523
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1524
                    //exit;
1525
                }
1526
 
1527
                if (!password_verify($username . '-' . $config_password . '-' . $rand . '-' . $timestamp, $password)) {
1528
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
1529
                    exit;
1530
                }
1531
 
1532
                if (empty($data)) {
1533
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
1534
                    exit;
1535
                }
1536
 
1537
                $data = base64_decode($data);
1538
                if (empty($data)) {
1539
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
1540
                    exit;
1541
                }
1542
 
1543
 
1544
                try {
1545
                    $rsa = Rsa::getInstance();
1546
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1547
                } catch (\Throwable $e) {
1548
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
1549
                    exit;
1550
                }
1551
 
1552
                $data = (array) json_decode($data);
1553
                if (empty($data)) {
1554
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
1555
                    exit;
1556
                }
1557
 
1558
                $email      = isset($data['email']) ? Functions::sanitizeFilterString($data['email']) : '';
1559
                $first_name = isset($data['first_name']) ? Functions::sanitizeFilterString($data['first_name']) : '';
1560
                $last_name  = isset($data['last_name']) ? Functions::sanitizeFilterString($data['last_name']) : '';
1561
 
1562
                if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
1563
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']);
1564
                    exit;
1565
                }
1566
 
1567
                $userMapper = UserMapper::getInstance($this->adapter);
1568
                $user = $userMapper->fetchOneByEmail($email);
1569
                if (!$user) {
1570
 
1571
 
1572
                    $user = new User();
1573
                    $user->network_id = $currentNetwork->id;
1574
                    $user->blocked = User::BLOCKED_NO;
1575
                    $user->email = $email;
1576
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1577
                    $user->first_name = $first_name;
1578
                    $user->last_name = $last_name;
1579
                    $user->login_attempt = 0;
1580
                    $user->password = '-NO-PASSWORD-';
1581
                    $user->usertype_id = UserType::USER;
1582
                    $user->status = User::STATUS_ACTIVE;
1583
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
1584
 
1585
                    if ($userMapper->insert($user)) {
1586
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]);
1587
                        exit;
1588
                    }
1589
 
1590
 
1591
 
1592
 
1593
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
1594
                    $content    = isset($data['avatar_content']) ? Functions::sanitizeFilterString($data['avatar_content']) : '';
1595
 
1596
                    if ($filename && $content) {
1597
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
1598
                        try {
1599
                            file_put_contents($source, base64_decode($content));
1600
                            if (file_exists($source)) {
1601
                                $target_path = $this->config['leaderslinked.fullpath.user'] . $user->uuid;
1602
                                list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
1603
 
1604
                                $target_filename    = 'user-' . uniqid() . '.png';
1605
                                $crop_to_dimensions = true;
1606
 
1607
                                if (!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
1608
                                    return new JsonModel([
1609
                                        'success'   => false,
1610
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1611
                                    ]);
1612
                                }
1613
 
1614
                                $user->image = $target_filename;
1615
                                $userMapper->updateImage($user);
1616
                            }
1617
                        } catch (\Throwable $e) {
1618
                        } finally {
1619
                            if (file_exists($source)) {
1620
                                unlink($source);
1621
                            }
1622
                        }
1623
                    }
1624
                }
1625
 
1626
                $auth = new AuthEmailAdapter($this->adapter);
1627
                $auth->setData($email);
1628
 
1629
                $result = $auth->authenticate();
1630
                if ($result->getCode() == AuthResult::SUCCESS) {
1631
                    return $this->redirect()->toRoute('dashboard');
1632
                } else {
1633
                    $message = $result->getMessages()[0];
1634
                    if (!in_array($message, [
1635
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1636
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1637
                        'ERROR_ENTERED_PASS_INCORRECT_1'
1638
                    ])) {
1639
                    }
1640
 
1641
                    switch ($message) {
1642
                        case 'ERROR_USER_NOT_FOUND':
1643
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1644
                            break;
1645
 
1646
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
1647
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1648
                            break;
1649
 
1650
                        case 'ERROR_USER_IS_BLOCKED':
1651
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1652
                            break;
1653
 
1654
                        case 'ERROR_USER_IS_INACTIVE':
1655
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1656
                            break;
1657
 
1658
 
1659
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1660
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1661
                            break;
1662
 
1663
 
1664
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
1665
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1666
                            break;
1667
 
1668
 
1669
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
1670
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1671
                            break;
1672
 
1673
 
1674
                        default:
1675
                            $message = 'ERROR_UNKNOWN';
1676
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1677
                            break;
1678
                    }
1679
 
1680
 
1681
 
1682
 
1683
                    return new JsonModel([
1684
                        'success'   => false,
1685
                        'data'   => $message
1686
                    ]);
1687
                }
1688
            } else {
1689
                $messages = [];
1690
 
1691
 
1692
 
1693
                $form_messages = (array) $form->getMessages();
1694
                foreach ($form_messages  as $fieldname => $field_messages) {
1695
 
1696
                    $messages[$fieldname] = array_values($field_messages);
1697
                }
1698
 
1699
                return new JsonModel([
1700
                    'success'   => false,
1701
                    'data'   => $messages
1702
                ]);
1703
            }
1704
        } else {
1705
            $data = [
1706
                'success' => false,
1707
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1708
            ];
1709
 
1710
            return new JsonModel($data);
1711
        }
1712
 
1713
        return new JsonModel($data);
1714
    }
1715
 
1716
    public function csrfAction()
1717
    {
1718
        $request = $this->getRequest();
1719
        if ($request->isGet()) {
95 efrain 1720
 
1721
            $jwtToken = null;
1722
            $headers = getallheaders();
1723
 
1724
 
1725
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
1726
 
1727
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
1728
 
1729
 
1730
                if (substr($token, 0, 6 ) == 'Bearer') {
1731
 
1732
                    $token = trim(substr($token, 7));
1733
 
1734
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
1735
                        $key = $this->config['leaderslinked.jwt.key'];
1736
 
1737
 
1738
                        try {
1739
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
1740
 
1741
 
1742
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
1743
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
1744
                            }
1745
 
1746
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
1747
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
1748
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
1749
                            if(!$jwtToken) {
1750
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
1751
                            }
1752
 
1753
                        } catch(\Exception $e) {
1754
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
1755
                        }
1756
                    } else {
1757
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
1758
                    }
1759
                } else {
1760
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
1761
                }
1762
            } else {
1763
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
1764
            }
1765
 
1766
            $jwtToken->csrf = md5(uniqid('CSFR-' . mt_rand(), true));
1767
            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
1768
            $jwtTokenMapper->update($jwtToken);
100 efrain 1769
 
1770
 
106 efrain 1771
           // error_log('token id = ' . $jwtToken->id . ' csrf = ' . $jwtToken->csrf);
1 efrain 1772
 
1773
 
1774
            return new JsonModel([
1775
                'success' => true,
99 efrain 1776
                'data' => $jwtToken->csrf
1 efrain 1777
            ]);
1778
        } else {
1779
            return new JsonModel([
1780
                'success' => false,
1781
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1782
            ]);
1783
        }
1784
    }
1785
 
1786
    public function impersonateAction()
1787
    {
1788
        $request = $this->getRequest();
1789
        if ($request->isGet()) {
1790
            $user_uuid  = Functions::sanitizeFilterString($this->params()->fromQuery('user_uuid'));
1791
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
1792
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
1793
            $password   = Functions::sanitizeFilterString($this->params()->fromQuery('password'));
1794
 
1795
 
1796
            if (!$user_uuid || !$rand || !$timestamp || !$password) {
1797
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
1798
            }
1799
 
1800
 
1801
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1802
            $currentUserPlugin->clearIdentity();
1803
 
1804
 
1805
            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
1806
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);
1807
 
1808
            $authService = new AuthenticationService();
1809
            $result = $authService->authenticate($authAdapter);
1810
 
1811
 
1812
            if ($result->getCode() == AuthResult::SUCCESS) {
1813
                return $this->redirect()->toRoute('dashboard');
1814
            } else {
1815
                throw new \Exception($result->getMessages()[0]);
1816
            }
1817
        }
1818
 
1819
        return new JsonModel([
1820
            'success' => false,
1821
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1822
        ]);
1823
    }
119 efrain 1824
 
1825
    public function autologinAction()
1826
    {
1827
        $email = 'santiago.olivera@leaderslinked.com';
1828
        $network_id = 1;
1829
 
1830
        $authAdapter = new AuthEmailAdapter($this->adapter);
1831
        $authAdapter->setData($email, $network_id);
1832
 
1833
        $authService = new AuthenticationService();
1834
        $result = $authService->authenticate($authAdapter);
1835
 
1836
 
1837
        if ($result->getCode() == AuthResult::SUCCESS) {
1838
            return $this->redirect()->toRoute('dashboard');
1839
        } else {
1840
            throw new \Exception($result->getMessages()[0]);
1841
        }
1842
 
1843
 
1844
    }
1 efrain 1845
}