Proyectos de Subversion LeadersLinked - Services

Rev

Rev 155 | Rev 180 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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