Proyectos de Subversion LeadersLinked - Services

Rev

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