Proyectos de Subversion LeadersLinked - Services

Rev

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