Proyectos de Subversion LeadersLinked - Services

Rev

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