Proyectos de Subversion LeadersLinked - Services

Rev

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