Proyectos de Subversion LeadersLinked - Services

Rev

Rev 344 | Rev 605 | 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'];
385 www 1282
                            $user->timezone             = $dataPost['timezone'];
1 efrain 1283
                            $user->usertype_id          = UserType::USER;
1284
                            $user->password             = $password_hash;
1285
                            $user->password_updated_on  = date('Y-m-d H:i:s');
1286
                            $user->status               = User::STATUS_ACTIVE;
1287
                            $user->blocked              = User::BLOCKED_NO;
1288
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
1289
                            $user->login_attempt        = 0;
1290
                            $user->is_adult             = $dataPost['is_adult'];
1291
                            $user->request_access       = User::REQUEST_ACCESS_APPROVED;
1292
 
1293
 
1294
 
1295
 
1296
 
1297
                            if ($userMapper->insert($user)) {
1298
 
1299
                                $userPassword = new UserPassword();
1300
                                $userPassword->user_id = $user->id;
1301
                                $userPassword->password = $password_hash;
1302
 
1303
                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1304
                                $userPasswordMapper->insert($userPassword);
1305
 
1306
 
1307
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1308
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1309
 
1310
                                if ($connection) {
1311
 
1312
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1313
                                        $connectionMapper->approve($connection);
1314
                                    }
1315
                                } else {
1316
                                    $connection = new Connection();
1317
                                    $connection->request_from = $user->id;
1318
                                    $connection->request_to = $userRedirect->id;
1319
                                    $connection->status = Connection::STATUS_ACCEPTED;
1320
 
1321
                                    $connectionMapper->insert($connection);
1322
                                }
1323
 
1324
 
1325
                                $this->cache->removeItem('user_share_invitation');
1326
 
1327
 
249 efrain 1328
 
1329
                                if($content_type == 'feed') {
1330
                                    $url = $this->url()->fromRoute('dashboard', ['feed' => $content_uuid ]);
1331
 
1332
                                }
1333
                                else if($content_type == 'post') {
1334
                                    $url = $this->url()->fromRoute('post', ['id' => $content_uuid ]);
1335
                                }
1336
                                else {
1337
                                    $url = $this->url()->fromRoute('dashboard');
1338
                                }
1339
 
1340
                                $hostname = empty($_SERVER['HTTP_HOST']) ?  '' : $_SERVER['HTTP_HOST'];
1341
 
1342
                                $networkMapper = NetworkMapper::getInstance($this->adapter);
1343
                                $network = $networkMapper->fetchOneByHostnameForFrontend($hostname);
1344
 
1345
                                if(!$network) {
1346
                                    $network = $networkMapper->fetchOneByDefault();
1347
                                }
1348
 
1349
                                $hostname = trim($network->main_hostname);
1350
                                $url = 'https://' . $hostname . $url;
1351
 
1 efrain 1352
 
1353
                                $data = [
1354
                                    'success'   => true,
249 efrain 1355
                                    'data'      => $url
1 efrain 1356
                                ];
1357
 
1358
 
1359
                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1360
 
1361
                                return new JsonModel($data);
1362
                            }
1363
                        }
1364
                    }
1365
 
1366
 
1367
 
1368
 
1369
                    $timestamp = time();
1370
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);
1371
 
1372
                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1373
 
1374
                    $user = new User();
1375
                    $user->network_id           = $currentNetwork->id;
1376
                    $user->email                = $dataPost['email'];
1377
                    $user->first_name           = $dataPost['first_name'];
1378
                    $user->last_name            = $dataPost['last_name'];
1379
                    $user->usertype_id          = UserType::USER;
1380
                    $user->password             = $password_hash;
1381
                    $user->password_updated_on  = date('Y-m-d H:i:s');
1382
                    $user->activation_key       = $activation_key;
1383
                    $user->status               = User::STATUS_INACTIVE;
1384
                    $user->blocked              = User::BLOCKED_NO;
1385
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
1386
                    $user->login_attempt        = 0;
1387
 
1388
                    if ($currentNetwork->default == Network::DEFAULT_YES) {
1389
                        $user->request_access = User::REQUEST_ACCESS_APPROVED;
1390
                    } else {
1391
                        $user->request_access = User::REQUEST_ACCESS_PENDING;
1392
                    }
1393
 
257 efrain 1394
                    $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
1395
                    $externalCredentials->completeDataFromNewUser($user);
1 efrain 1396
 
1397
                    if ($userMapper->insert($user)) {
1398
 
1399
                        $userPassword = new UserPassword();
1400
                        $userPassword->user_id = $user->id;
1401
                        $userPassword->password = $password_hash;
1402
 
1403
                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1404
                        $userPasswordMapper->insert($userPassword);
1405
 
1406
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1407
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
1408
                        if ($emailTemplate) {
1409
                            $arrayCont = [
1410
                                'firstname'             => $user->first_name,
1411
                                'lastname'              => $user->last_name,
1412
                                'other_user_firstname'  => '',
1413
                                'other_user_lastname'   => '',
1414
                                'company_name'          => '',
1415
                                'group_name'            => '',
1416
                                'content'               => '',
1417
                                'code'                  => '',
1418
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
1419
                            ];
1420
 
1421
                            $email = new QueueEmail($this->adapter);
1422
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1423
                        }
1424
 
1425
                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1426
 
1427
                        return new JsonModel([
1428
                            'success' => true,
180 efrain 1429
                            'data' => 'LABEL_REGISTRATION_DONE'
1 efrain 1430
                        ]);
1431
                    } else {
1432
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);
1433
 
1434
                        return new JsonModel([
1435
                            'success' => false,
1436
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1437
                        ]);
1438
                    }
1439
                }
1440
            } else {
1441
 
1442
                $form_messages =  $form->getMessages('captcha');
1443
                if (!empty($form_messages)) {
1444
                    return new JsonModel([
1445
                        'success'   => false,
1446
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1447
                    ]);
1448
                }
1449
 
1450
                $messages = [];
1451
 
1452
                $form_messages = (array) $form->getMessages();
1453
                foreach ($form_messages  as $fieldname => $field_messages) {
1454
                    $messages[$fieldname] = array_values($field_messages);
1455
                }
1456
 
1457
                return new JsonModel([
1458
                    'success'   => false,
1459
                    'data'   => $messages
1460
                ]);
1461
            }
1462
        } else if ($request->isGet()) {
1463
 
1464
            if (empty($_SESSION['aes'])) {
1465
                $_SESSION['aes'] = Functions::generatePassword(16);
1466
            }
1467
 
1468
            if ($this->config['leaderslinked.runmode.sandbox']) {
1469
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1470
            } else {
1471
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1472
            }
1473
 
1474
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
1475
 
1476
            return new JsonModel([
1477
                'site_key'  => $site_key,
1478
                'aes'       => $_SESSION['aes'],
1479
                'defaultNetwork' => $currentNetwork->default,
1480
            ]);
1481
        }
1482
 
1483
        return new JsonModel([
1484
            'success' => false,
1485
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1486
        ]);
1487
    }
1488
 
1489
    public function activateAccountAction()
1490
    {
1491
 
1492
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1493
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1494
 
1495
 
1496
 
1497
        $request = $this->getRequest();
1498
        if ($request->isGet()) {
1499
            $code   =  Functions::sanitizeFilterString($this->params()->fromRoute('code'));
1500
            $userMapper = UserMapper::getInstance($this->adapter);
1501
            $user = $userMapper->fetchOneByActivationKeyAndNetworkId($code, $currentNetwork->id);
1502
 
1503
 
180 efrain 1504
 
1 efrain 1505
            if ($user) {
1506
                if (User::EMAIL_VERIFIED_YES == $user->email_verified) {
180 efrain 1507
 
1 efrain 1508
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
180 efrain 1509
 
1510
                    $response = [
1511
                        'success' => false,
1512
                        'data' => 'ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED'
1513
                    ];
1514
 
1515
                    return new JsonModel($response);
1 efrain 1516
                } else {
1517
 
1518
                    if ($userMapper->activateAccount((int) $user->id)) {
1519
 
1520
                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1521
 
1522
 
1523
 
1524
                        $user_share_invitation = $this->cache->getItem('user_share_invitation');
1525
 
1526
                        if ($user_share_invitation) {
1527
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
1528
                            if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
1529
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1530
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1531
 
1532
                                if ($connection) {
1533
 
1534
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1535
                                        $connectionMapper->approve($connection);
1536
                                    }
1537
                                } else {
1538
                                    $connection = new Connection();
1539
                                    $connection->request_from = $user->id;
1540
                                    $connection->request_to = $userRedirect->id;
1541
                                    $connection->status = Connection::STATUS_ACCEPTED;
1542
 
1543
                                    $connectionMapper->insert($connection);
1544
                                }
1545
                            }
1546
                        }
1547
 
1548
 
1549
 
1550
                        $this->cache->removeItem('user_share_invitation');
1551
 
1552
 
1553
                        if ($currentNetwork->default == Network::DEFAULT_YES) {
180 efrain 1554
 
1555
                            $response = [
1556
                                'success' => true,
1557
                                'data' => 'LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED'
1558
                            ];
1559
 
1560
                            return new JsonModel($response);
1561
 
1562
 
1 efrain 1563
                        } else {
1564
 
1565
                            $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1566
                            $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_REQUEST_ACCESS_PENDING, $currentNetwork->id);
1567
 
1568
                            if ($emailTemplate) {
1569
                                $arrayCont = [
1570
                                    'firstname'             => $user->first_name,
1571
                                    'lastname'              => $user->last_name,
1572
                                    'other_user_firstname'  => '',
1573
                                    'other_user_lastname'   => '',
1574
                                    'company_name'          => '',
1575
                                    'group_name'            => '',
1576
                                    'content'               => '',
1577
                                    'code'                  => '',
1578
                                    'link'                  => '',
1579
                                ];
1580
 
1581
                                $email = new QueueEmail($this->adapter);
1582
                                $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1583
                            }
180 efrain 1584
 
1585
                            $response = [
1586
                                'success' => true,
1587
                                'data' => 'LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED_WE_ARE_VERIFYING_YOUR_INFORMATION'
1588
                            ];
1589
 
1590
                            return new JsonModel($response);
1 efrain 1591
 
1592
 
1593
                        }
1594
                    } else {
1595
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
180 efrain 1596
 
1597
                        $response = [
1598
                            'success' => false,
1599
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1600
                        ];
1601
 
1602
                        return new JsonModel($response);
1 efrain 1603
 
1604
                    }
1605
                }
1606
            } else {
180 efrain 1607
 
1608
 
1 efrain 1609
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);
1610
 
180 efrain 1611
                $response = [
1612
                    'success' => false,
1613
                    'data' =>'ERROR_ACTIVATION_CODE_IS_NOT_VALID'
1614
                ];
1615
 
1616
                return new JsonModel($response);
1617
 
1618
 
1619
 
1 efrain 1620
            }
1621
 
180 efrain 1622
 
1 efrain 1623
        } else {
1624
            $response = [
1625
                'success' => false,
1626
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1627
            ];
1628
        }
1629
 
1630
        return new JsonModel($response);
1631
    }
283 www 1632
 
1 efrain 1633
    public function onroomAction()
1634
    {
1635
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1636
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
283 www 1637
 
1638
 
1639
 
1 efrain 1640
        $request = $this->getRequest();
283 www 1641
 
1 efrain 1642
        if ($request->isPost()) {
283 www 1643
 
1 efrain 1644
            $dataPost = $request->getPost()->toArray();
283 www 1645
 
1646
 
1 efrain 1647
            $form = new  MoodleForm();
1648
            $form->setData($dataPost);
1649
            if ($form->isValid()) {
283 www 1650
 
1 efrain 1651
                $dataPost   = (array) $form->getData();
1652
                $username   = $dataPost['username'];
1653
                $password   = $dataPost['password'];
1654
                $timestamp  = $dataPost['timestamp'];
1655
                $rand       = $dataPost['rand'];
1656
                $data       = $dataPost['data'];
283 www 1657
 
1 efrain 1658
                $config_username    = $this->config['leaderslinked.moodle.username'];
1659
                $config_password    = $this->config['leaderslinked.moodle.password'];
1660
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1661
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
1662
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
283 www 1663
 
1664
 
1665
 
1666
 
1 efrain 1667
                if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1668
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
1669
                    exit;
1670
                }
283 www 1671
 
1 efrain 1672
                if ($username != $config_username) {
1673
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
1674
                    exit;
1675
                }
283 www 1676
 
1 efrain 1677
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1678
                if (!$dt) {
1679
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
1680
                    exit;
1681
                }
283 www 1682
 
1 efrain 1683
                $t0 = $dt->getTimestamp();
1684
                $t1 = strtotime('-5 minutes');
1685
                $t2 = strtotime('+5 minutes');
283 www 1686
 
1 efrain 1687
                if ($t0 < $t1 || $t0 > $t2) {
1688
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1689
                    //exit;
1690
                }
283 www 1691
 
1 efrain 1692
                if (!password_verify($username . '-' . $config_password . '-' . $rand . '-' . $timestamp, $password)) {
1693
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
1694
                    exit;
1695
                }
283 www 1696
 
1 efrain 1697
                if (empty($data)) {
1698
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
1699
                    exit;
1700
                }
283 www 1701
 
1 efrain 1702
                $data = base64_decode($data);
1703
                if (empty($data)) {
1704
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
1705
                    exit;
1706
                }
283 www 1707
 
1708
 
1 efrain 1709
                try {
1710
                    $rsa = Rsa::getInstance();
1711
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1712
                } catch (\Throwable $e) {
1713
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
1714
                    exit;
1715
                }
283 www 1716
 
1 efrain 1717
                $data = (array) json_decode($data);
1718
                if (empty($data)) {
1719
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
1720
                    exit;
1721
                }
283 www 1722
 
1 efrain 1723
                $email      = isset($data['email']) ? Functions::sanitizeFilterString($data['email']) : '';
1724
                $first_name = isset($data['first_name']) ? Functions::sanitizeFilterString($data['first_name']) : '';
1725
                $last_name  = isset($data['last_name']) ? Functions::sanitizeFilterString($data['last_name']) : '';
283 www 1726
 
1 efrain 1727
                if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
1728
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']);
1729
                    exit;
1730
                }
283 www 1731
 
1 efrain 1732
                $userMapper = UserMapper::getInstance($this->adapter);
1733
                $user = $userMapper->fetchOneByEmail($email);
1734
                if (!$user) {
283 www 1735
 
1736
 
1 efrain 1737
                    $user = new User();
1738
                    $user->network_id = $currentNetwork->id;
1739
                    $user->blocked = User::BLOCKED_NO;
1740
                    $user->email = $email;
1741
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1742
                    $user->first_name = $first_name;
1743
                    $user->last_name = $last_name;
1744
                    $user->login_attempt = 0;
1745
                    $user->password = '-NO-PASSWORD-';
1746
                    $user->usertype_id = UserType::USER;
1747
                    $user->status = User::STATUS_ACTIVE;
1748
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
283 www 1749
 
1 efrain 1750
                    if ($userMapper->insert($user)) {
1751
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]);
1752
                        exit;
1753
                    }
266 efrain 1754
 
1755
                    $user = $userMapper->fetchOne($user->id);
283 www 1756
 
1757
 
1758
 
1759
 
1 efrain 1760
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
1761
                    $content    = isset($data['avatar_content']) ? Functions::sanitizeFilterString($data['avatar_content']) : '';
283 www 1762
 
1 efrain 1763
                    if ($filename && $content) {
1764
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
1765
                        try {
266 efrain 1766
 
1767
 
1 efrain 1768
                            file_put_contents($source, base64_decode($content));
1769
                            if (file_exists($source)) {
1770
                                list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
283 www 1771
 
1 efrain 1772
                                $target_filename    = 'user-' . uniqid() . '.png';
1773
                                $crop_to_dimensions = true;
283 www 1774
 
266 efrain 1775
                                $image = Image::getInstance($this->config);
1776
                                $target_path    = $image->getStorage()->getPathUser();
1777
                                $unlink_source  = true;
1778
 
283 www 1779
 
334 www 1780
                                if (!$image->uploadProcessChangeSize($source, $target_path, $user->uuid, $target_filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
1 efrain 1781
                                    return new JsonModel([
1782
                                        'success'   => false,
1783
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1784
                                    ]);
1785
                                }
283 www 1786
 
1 efrain 1787
                                $user->image = $target_filename;
1788
                                $userMapper->updateImage($user);
1789
                            }
1790
                        } catch (\Throwable $e) {
1791
                        } finally {
1792
                            if (file_exists($source)) {
1793
                                unlink($source);
1794
                            }
1795
                        }
1796
                    }
1797
                }
283 www 1798
 
1 efrain 1799
                $auth = new AuthEmailAdapter($this->adapter);
1800
                $auth->setData($email);
283 www 1801
 
1 efrain 1802
                $result = $auth->authenticate();
1803
                if ($result->getCode() == AuthResult::SUCCESS) {
1804
                    return $this->redirect()->toRoute('dashboard');
1805
                } else {
1806
                    $message = $result->getMessages()[0];
1807
                    if (!in_array($message, [
1808
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1809
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1810
                        'ERROR_ENTERED_PASS_INCORRECT_1'
1811
                    ])) {
1812
                    }
283 www 1813
 
1 efrain 1814
                    switch ($message) {
1815
                        case 'ERROR_USER_NOT_FOUND':
1816
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1817
                            break;
283 www 1818
 
1 efrain 1819
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
1820
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1821
                            break;
283 www 1822
 
1 efrain 1823
                        case 'ERROR_USER_IS_BLOCKED':
1824
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1825
                            break;
283 www 1826
 
1 efrain 1827
                        case 'ERROR_USER_IS_INACTIVE':
1828
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1829
                            break;
283 www 1830
 
1831
 
1 efrain 1832
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1833
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1834
                            break;
283 www 1835
 
1836
 
1 efrain 1837
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
1838
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1839
                            break;
283 www 1840
 
1841
 
1 efrain 1842
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
1843
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1844
                            break;
283 www 1845
 
1846
 
1 efrain 1847
                        default:
1848
                            $message = 'ERROR_UNKNOWN';
1849
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1850
                            break;
1851
                    }
283 www 1852
 
1853
 
1854
 
1855
 
1 efrain 1856
                    return new JsonModel([
1857
                        'success'   => false,
1858
                        'data'   => $message
1859
                    ]);
1860
                }
1861
            } else {
1862
                $messages = [];
283 www 1863
 
1864
 
1865
 
1866
                $form_messages = (array) $form->getMessages();
1867
                foreach ($form_messages  as $fieldname => $field_messages) {
1868
 
1869
                    $messages[$fieldname] = array_values($field_messages);
1870
                }
1871
 
1872
                return new JsonModel([
1873
                    'success'   => false,
1874
                    'data'   => $messages
1875
                ]);
1876
            }
1877
        } else {
1878
            $data = [
1879
                'success' => false,
1880
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1881
            ];
1882
 
1883
            return new JsonModel($data);
1884
        }
1885
 
1886
        return new JsonModel($data);
1887
    }
1 efrain 1888
 
1889
 
1890
 
283 www 1891
    public function cesamsAction()
1892
    {
1893
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1894
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1895
 
1896
        $request = $this->getRequest();
1897
 
1898
        if ($request->isPost()) {
1899
 
1900
            $dataPost = $request->getPost()->toArray();
1901
 
1902
 
1903
            $form = new  MoodleForm();
1904
            $form->setData($dataPost);
1905
            if ($form->isValid()) {
1906
 
1907
                $dataPost   = (array) $form->getData();
1908
                $username   = $dataPost['username'];
1909
                $password   = $dataPost['password'];
1910
                $timestamp  = $dataPost['timestamp'];
1911
                $rand       = $dataPost['rand'];
1912
                $data       = $dataPost['data'];
1913
 
1914
                $config_username    = $this->config['leaderslinked.moodle.username'];
1915
                $config_password    = $this->config['leaderslinked.moodle.password'];
1916
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1917
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
291 www 1918
                //$config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
283 www 1919
 
1920
                if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1921
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
1922
                    exit;
1923
                }
1924
 
1925
                if ($username != $config_username) {
1926
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
1927
                    exit;
1928
                }
1929
 
1930
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1931
                if (!$dt) {
1932
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
1933
                    exit;
1934
                }
1935
 
1936
                $dt = \DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s',  gmdate('Y-m-d\TH:i:s'));
1937
                $dtMax = $dt->add(\DateInterval::createFromDateString('5 minutes'));
1938
                $dtMin = $dt->sub(\DateInterval::createFromDateString('5 minutes'));
1939
 
1940
 
1941
                $t0 = $dt->getTimestamp();
1942
                $t1 = $dtMin->getTimestamp();
1943
                $t2 = $dtMax->getTimestamp();
1944
                if ($t0 < $t1 || $t0 > $t2) {
301 www 1945
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1946
                    exit;
283 www 1947
                }
1948
 
1949
                if (!password_verify($username . '-' . $config_password . '-' . $rand . '-' . $timestamp, $password)) {
1950
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
1951
                    exit;
1952
                }
1953
 
1954
                if (empty($data)) {
1955
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
1956
                    exit;
1957
                }
1958
 
1959
                $data = base64_decode($data);
1960
                if (empty($data)) {
1961
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
1962
                    exit;
1963
                }
1964
 
1965
                try {
1966
                    $rsa = Rsa::getInstance();
1967
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1968
                } catch (\Throwable $e) {
1969
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
1970
                    exit;
1971
                }
1972
 
1973
                $data = (array) json_decode($data);
1974
                if (empty($data)) {
1975
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
1976
                    exit;
1977
                }
1978
 
1979
                $email      = isset($data['email']) ? Functions::sanitizeFilterString($data['email']) : '';
1980
                $first_name = isset($data['first_name']) ? Functions::sanitizeFilterString($data['first_name']) : '';
1981
                $last_name  = isset($data['last_name']) ? Functions::sanitizeFilterString($data['last_name']) : '';
1982
                $password   = isset($data['password']) ? Functions::sanitizeFilterString($data['password']) : '';
1983
 
1984
                if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name) || empty($password)) {
1985
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']);
1986
                    exit;
1987
                }
1988
 
1989
                $userMapper = UserMapper::getInstance($this->adapter);
1990
                $user = $userMapper->fetchOneByEmail($email);
1991
                if (!$user) {
1992
 
1993
                    $user = new User();
1994
                    $user->network_id = $currentNetwork->id;
1995
                    $user->blocked = User::BLOCKED_NO;
1996
                    $user->email = $email;
1997
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1998
                    $user->first_name = $first_name;
1999
                    $user->last_name = $last_name;
2000
                    $user->login_attempt = 0;
2001
                    $user->password = password_hash($password, PASSWORD_DEFAULT);
2002
                    $user->usertype_id = UserType::USER;
2003
                    $user->status = User::STATUS_ACTIVE;
2004
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
2005
 
2006
                    if ($userMapper->insert($user)) {
2007
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]);
2008
                        exit;
2009
                    }
2010
 
2011
                    $user = $userMapper->fetchOne($user->id);
2012
 
2013
                    $userPassword = new UserPassword();
2014
                    $userPassword->user_id = $user->id;
2015
                    $userPassword->password = password_hash($password, PASSWORD_DEFAULT);
2016
 
2017
                    $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
2018
                    $userPasswordMapper->insert($userPassword);
2019
 
2020
                    $userDefaultForConnection = $userMapper->fetchOneDefaultForConnection();
2021
                    if($userDefaultForConnection) {
2022
 
2023
                        $connection = new Connection();
2024
                        $connection->request_from = $userDefaultForConnection->id;
2025
                        $connection->request_to = $user->id;
2026
                        $connection->status = Connection::STATUS_ACCEPTED;
2027
 
2028
                        $connectionMapper = ConnectionMapper::getInstance($this->adapter);
2029
                        $connectionMapper->insert($connection);
2030
                    }
2031
                }
2032
 
2033
                return new JsonModel([
2034
                    'success'   => true,
2035
                    'data'   => $user->uuid
2036
                ]);
2037
 
2038
            } else {
2039
                $messages = [];
2040
 
2041
 
2042
 
1 efrain 2043
                $form_messages = (array) $form->getMessages();
2044
                foreach ($form_messages  as $fieldname => $field_messages) {
2045
 
2046
                    $messages[$fieldname] = array_values($field_messages);
2047
                }
2048
 
2049
                return new JsonModel([
2050
                    'success'   => false,
2051
                    'data'   => $messages
2052
                ]);
2053
            }
2054
        } else {
2055
            $data = [
2056
                'success' => false,
2057
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2058
            ];
2059
 
2060
            return new JsonModel($data);
2061
        }
2062
 
2063
        return new JsonModel($data);
2064
    }
2065
 
2066
    public function csrfAction()
2067
    {
2068
        $request = $this->getRequest();
2069
        if ($request->isGet()) {
95 efrain 2070
 
2071
            $jwtToken = null;
2072
            $headers = getallheaders();
2073
 
279 efrain 2074
 
95 efrain 2075
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
2076
 
2077
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
2078
 
2079
 
2080
                if (substr($token, 0, 6 ) == 'Bearer') {
2081
 
2082
                    $token = trim(substr($token, 7));
2083
 
2084
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
2085
                        $key = $this->config['leaderslinked.jwt.key'];
2086
 
2087
 
2088
                        try {
2089
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
2090
 
2091
 
2092
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
2093
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
2094
                            }
2095
 
2096
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
2097
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2098
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
2099
                            if(!$jwtToken) {
2100
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
2101
                            }
2102
 
2103
                        } catch(\Exception $e) {
2104
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
2105
                        }
2106
                    } else {
2107
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
2108
                    }
2109
                } else {
2110
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
2111
                }
2112
            } else {
2113
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
279 efrain 2114
            }
95 efrain 2115
 
2116
            $jwtToken->csrf = md5(uniqid('CSFR-' . mt_rand(), true));
2117
            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2118
            $jwtTokenMapper->update($jwtToken);
278 efrain 2119
 
100 efrain 2120
 
106 efrain 2121
           // error_log('token id = ' . $jwtToken->id . ' csrf = ' . $jwtToken->csrf);
1 efrain 2122
 
2123
 
2124
            return new JsonModel([
2125
                'success' => true,
99 efrain 2126
                'data' => $jwtToken->csrf
1 efrain 2127
            ]);
2128
        } else {
2129
            return new JsonModel([
2130
                'success' => false,
2131
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2132
            ]);
2133
        }
2134
    }
2135
 
2136
    public function impersonateAction()
2137
    {
2138
        $request = $this->getRequest();
2139
        if ($request->isGet()) {
2140
            $user_uuid  = Functions::sanitizeFilterString($this->params()->fromQuery('user_uuid'));
2141
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
2142
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
2143
            $password   = Functions::sanitizeFilterString($this->params()->fromQuery('password'));
2144
 
2145
 
2146
            if (!$user_uuid || !$rand || !$timestamp || !$password) {
2147
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
2148
            }
2149
 
2150
 
2151
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2152
            $currentUserPlugin->clearIdentity();
2153
 
2154
 
2155
            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
2156
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);
2157
 
2158
            $authService = new AuthenticationService();
2159
            $result = $authService->authenticate($authAdapter);
2160
 
2161
 
2162
            if ($result->getCode() == AuthResult::SUCCESS) {
2163
                return $this->redirect()->toRoute('dashboard');
2164
            } else {
2165
                throw new \Exception($result->getMessages()[0]);
2166
            }
2167
        }
2168
 
2169
        return new JsonModel([
2170
            'success' => false,
2171
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2172
        ]);
2173
    }
119 efrain 2174
 
340 www 2175
 
2176
 
2177
    public function debugAction()
2178
    {
2179
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
2180
        $currentNetwork = $currentNetworkPlugin->getNetwork();
2181
 
2182
        $request = $this->getRequest();
2183
 
2184
        if ($request->isPost()) {
2185
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
2186
            $currentNetwork = $currentNetworkPlugin->getNetwork();
2187
 
2188
            $jwtToken = null;
2189
            $headers = getallheaders();
2190
 
2191
 
2192
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
2193
 
2194
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
2195
 
2196
 
2197
                if (substr($token, 0, 6 ) == 'Bearer') {
2198
 
2199
                    $token = trim(substr($token, 7));
2200
 
2201
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
2202
                        $key = $this->config['leaderslinked.jwt.key'];
2203
 
2204
 
2205
                        try {
2206
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
2207
 
2208
 
2209
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
2210
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
2211
                            }
2212
 
2213
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
2214
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2215
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
2216
                            if(!$jwtToken) {
2217
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
2218
                            }
2219
 
2220
                        } catch(\Exception $e) {
2221
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
2222
                        }
2223
                    } else {
2224
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
2225
                    }
2226
                } else {
2227
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
2228
                }
2229
            } else {
2230
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
2231
            }
2232
 
2233
 
2234
 
2235
            $form = new  SigninDebugForm($this->config);
2236
            $dataPost = $request->getPost()->toArray();
2237
 
2238
            if (empty($_SESSION['aes'])) {
2239
                return new JsonModel([
2240
                    'success'   => false,
2241
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
2242
                ]);
2243
            }
2244
 
2245
            error_log(print_r($dataPost, true));
2246
 
2247
            $aes = $_SESSION['aes'];
2248
            error_log('aes : ' . $aes);
2249
 
2250
 
2251
            unset( $_SESSION['aes'] );
2252
 
2253
            if (!empty($dataPost['email'])) {
2254
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $aes);
2255
            }
2256
 
2257
 
2258
            if (!empty($dataPost['password'])) {
2259
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $aes);
2260
            }
2261
 
341 www 2262
 
340 www 2263
            error_log(print_r($dataPost, true));
2264
 
2265
            $form->setData($dataPost);
2266
 
2267
            if ($form->isValid()) {
2268
 
2269
                $dataPost = (array) $form->getData();
2270
 
2271
 
2272
                $email      = $dataPost['email'];
2273
                $password   = $dataPost['password'];
2274
 
2275
 
2276
 
2277
 
2278
 
2279
                $authAdapter = new AuthAdapter($this->adapter, $this->logger);
2280
                $authAdapter->setData($email, $password, $currentNetwork->id);
2281
                $authService = new AuthenticationService();
2282
 
2283
                $result = $authService->authenticate($authAdapter);
2284
 
2285
                if ($result->getCode() == AuthResult::SUCCESS) {
2286
 
2287
                    $identity = $result->getIdentity();
2288
 
2289
 
2290
                    $userMapper = UserMapper::getInstance($this->adapter);
2291
                    $user = $userMapper->fetchOne($identity['user_id']);
2292
 
2293
 
2294
                    if($token) {
2295
                        $jwtToken->user_id = $user->id;
2296
                        $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2297
                        $jwtTokenMapper->update($jwtToken);
2298
                    }
2299
 
2300
 
2301
                    $navigator = get_browser(null, true);
2302
                    $device_type    =  isset($navigator['device_type']) ? $navigator['device_type'] : '';
2303
                    $platform       =  isset($navigator['platform']) ? $navigator['platform'] : '';
2304
                    $browser        =  isset($navigator['browser']) ? $navigator['browser'] : '';
2305
 
2306
 
2307
                    $istablet = isset($navigator['istablet']) ?  intval($navigator['istablet']) : 0;
2308
                    $ismobiledevice = isset($navigator['ismobiledevice']) ? intval($navigator['ismobiledevice']) : 0;
2309
                    $version = isset($navigator['version']) ? $navigator['version'] : '';
2310
 
2311
 
2312
                    $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
2313
                    $userBrowser = $userBrowserMapper->fetch($user->id, $device_type, $platform, $browser);
2314
                    if ($userBrowser) {
2315
                        $userBrowserMapper->update($userBrowser);
2316
                    } else {
2317
                        $userBrowser = new UserBrowser();
2318
                        $userBrowser->user_id           = $user->id;
2319
                        $userBrowser->browser           = $browser;
2320
                        $userBrowser->platform          = $platform;
2321
                        $userBrowser->device_type       = $device_type;
2322
                        $userBrowser->is_tablet         = $istablet;
2323
                        $userBrowser->is_mobile_device  = $ismobiledevice;
2324
                        $userBrowser->version           = $version;
2325
 
2326
                        $userBrowserMapper->insert($userBrowser);
2327
                    }
2328
                    //
2329
 
2330
                    $ip = Functions::getUserIP();
2331
                    $ip = $ip == '127.0.0.1' ? '148.240.211.148' : $ip;
2332
 
2333
                    $userIpMapper = UserIpMapper::getInstance($this->adapter);
2334
                    $userIp = $userIpMapper->fetch($user->id, $ip);
2335
                    if (empty($userIp)) {
2336
 
2337
                        if ($this->config['leaderslinked.runmode.sandbox']) {
2338
                            $filename = $this->config['leaderslinked.geoip2.production_database'];
2339
                        } else {
2340
                            $filename = $this->config['leaderslinked.geoip2.sandbox_database'];
2341
                        }
2342
 
2343
                        $reader = new GeoIp2Reader($filename); //GeoIP2-City.mmdb');
2344
                        $record = $reader->city($ip);
2345
                        if ($record) {
2346
                            $userIp = new UserIp();
2347
                            $userIp->user_id = $user->id;
2348
                            $userIp->city = !empty($record->city->name) ? Functions::utf8_decode($record->city->name) : '';
2349
                            $userIp->state_code = !empty($record->mostSpecificSubdivision->isoCode) ? Functions::utf8_decode($record->mostSpecificSubdivision->isoCode) : '';
2350
                            $userIp->state_name = !empty($record->mostSpecificSubdivision->name) ? Functions::utf8_decode($record->mostSpecificSubdivision->name) : '';
2351
                            $userIp->country_code = !empty($record->country->isoCode) ? Functions::utf8_decode($record->country->isoCode) : '';
2352
                            $userIp->country_name = !empty($record->country->name) ? Functions::utf8_decode($record->country->name) : '';
2353
                            $userIp->ip = $ip;
2354
                            $userIp->latitude = !empty($record->location->latitude) ? $record->location->latitude : 0;
2355
                            $userIp->longitude = !empty($record->location->longitude) ? $record->location->longitude : 0;
2356
                            $userIp->postal_code = !empty($record->postal->code) ? $record->postal->code : '';
2357
 
2358
                            $userIpMapper->insert($userIp);
2359
                        }
2360
                    } else {
2361
                        $userIpMapper->update($userIp);
2362
                    }
2363
 
2364
                    /*
2365
                     if ($remember) {
2366
                     $expired = time() + 365 * 24 * 60 * 60;
2367
 
2368
                     $cookieEmail = new SetCookie('email', $email, $expired);
2369
                     } else {
2370
                     $expired = time() - 7200;
2371
                     $cookieEmail = new SetCookie('email', '', $expired);
2372
                     }
2373
 
2374
 
2375
                     $response = $this->getResponse();
2376
                     $response->getHeaders()->addHeader($cookieEmail);
2377
                     */
2378
 
2379
 
2380
 
2381
 
2382
 
2383
                    $this->logger->info('Ingreso a LeadersLiked', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
2384
 
2385
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
2386
 
2387
                    $url =  $this->url()->fromRoute('dashboard');
2388
 
2389
                    if ($user_share_invitation && is_array($user_share_invitation)) {
2390
 
2391
                        $content_uuid = $user_share_invitation['code'];
2392
                        $content_type = $user_share_invitation['type'];
2393
                        $content_user = $user_share_invitation['user'];
2394
 
2395
 
2396
 
2397
                        $userRedirect = $userMapper->fetchOneByUuid($content_user);
2398
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
2399
                            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
2400
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
2401
 
2402
                            if ($connection) {
2403
 
2404
                                if ($connection->status != Connection::STATUS_ACCEPTED) {
2405
                                    $connectionMapper->approve($connection);
2406
                                }
2407
                            } else {
2408
                                $connection = new Connection();
2409
                                $connection->request_from = $user->id;
2410
                                $connection->request_to = $userRedirect->id;
2411
                                $connection->status = Connection::STATUS_ACCEPTED;
2412
 
2413
                                $connectionMapper->insert($connection);
2414
                            }
2415
                        }
2416
 
2417
                        if($content_type == 'feed') {
2418
                            $url = $this->url()->fromRoute('dashboard', ['feed' => $content_uuid ]);
2419
 
2420
                        }
2421
                        else if($content_type == 'post') {
2422
                            $url = $this->url()->fromRoute('post', ['id' => $content_uuid ]);
2423
                        }
2424
                        else {
2425
                            $url = $this->url()->fromRoute('dashboard');
2426
                        }
2427
 
2428
                    }
2429
 
2430
 
2431
                    $hostname = empty($_SERVER['HTTP_HOST']) ?  '' : $_SERVER['HTTP_HOST'];
2432
 
2433
                    $networkMapper = NetworkMapper::getInstance($this->adapter);
2434
                    $network = $networkMapper->fetchOneByHostnameForFrontend($hostname);
2435
 
2436
                    if(!$network) {
2437
                        $network = $networkMapper->fetchOneByDefault();
2438
                    }
2439
 
2440
                    $hostname = trim($network->main_hostname);
2441
                    $url = 'https://' . $hostname . $url;
2442
 
2443
 
2444
                    $data = [
2445
                        'redirect'  => $url,
2446
                        'uuid'      => $user->uuid,
2447
                    ];
2448
 
2449
 
2450
 
2451
 
2452
                    if($currentNetwork->xmpp_active) {
2453
                        $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
2454
                        $externalCredentials->getUserBy($user->id);
2455
 
2456
 
2457
                        $data['xmpp_domain'] = $currentNetwork->xmpp_domain;
2458
                        $data['xmpp_hostname'] = $currentNetwork->xmpp_hostname;
2459
                        $data['xmpp_port'] = $currentNetwork->xmpp_port;
2460
                        $data['xmpp_username'] = $externalCredentials->getUsernameXmpp();
2461
                        $data['xmpp_pasword'] = $externalCredentials->getPasswordXmpp();
2462
                        $data['inmail_username'] = $externalCredentials->getUsernameInmail();
2463
                        $data['inmail_pasword'] = $externalCredentials->getPasswordInmail();
2464
 
2465
                    }
2466
 
2467
                    $data = [
2468
                        'success'   => true,
2469
                        'data'      => $data
2470
                    ];
2471
 
2472
 
2473
                    $this->cache->removeItem('user_share_invitation');
2474
                } else {
2475
 
2476
                    $message = $result->getMessages()[0];
2477
                    if (!in_array($message, [
2478
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
2479
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
2480
                        'ERROR_ENTERED_PASS_INCORRECT_1', 'ERROR_USER_REQUEST_ACCESS_IS_PENDING', 'ERROR_USER_REQUEST_ACCESS_IS_REJECTED'
2481
 
2482
 
2483
                    ])) {
2484
                    }
2485
 
2486
                    switch ($message) {
2487
                        case 'ERROR_USER_NOT_FOUND':
2488
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
2489
                            break;
2490
 
2491
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
2492
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
2493
                            break;
2494
 
2495
                        case 'ERROR_USER_IS_BLOCKED':
2496
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
2497
                            break;
2498
 
2499
                        case 'ERROR_USER_IS_INACTIVE':
2500
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
2501
                            break;
2502
 
2503
 
2504
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
2505
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
2506
                            break;
2507
 
2508
 
2509
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
2510
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
2511
                            break;
2512
 
2513
 
2514
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
2515
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
2516
                            break;
2517
 
2518
 
2519
                        case 'ERROR_USER_REQUEST_ACCESS_IS_PENDING':
2520
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Falta verificar que pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
2521
                            break;
2522
 
2523
                        case  'ERROR_USER_REQUEST_ACCESS_IS_REJECTED':
2524
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Rechazado por no pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
2525
                            break;
2526
 
2527
 
2528
                        default:
2529
                            $message = 'ERROR_UNKNOWN';
2530
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
2531
                            break;
2532
                    }
2533
 
2534
 
2535
 
2536
 
2537
                    $data = [
2538
                        'success'   => false,
2539
                        'data'   => $message
2540
                    ];
2541
                }
2542
 
2543
                return new JsonModel($data);
2544
            } else {
2545
                $messages = [];
2546
 
2547
 
2548
 
2549
                $form_messages = (array) $form->getMessages();
2550
                foreach ($form_messages  as $fieldname => $field_messages) {
2551
 
2552
                    $messages[$fieldname] = array_values($field_messages);
2553
                }
2554
 
2555
                return new JsonModel([
2556
                    'success'   => false,
2557
                    'data'   => $messages
2558
                ]);
2559
            }
2560
        } else if ($request->isGet()) {
2561
 
2562
            $aes = '';
2563
            $jwtToken = null;
2564
            $headers = getallheaders();
2565
 
2566
 
2567
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
2568
 
2569
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
2570
 
2571
 
2572
                if (substr($token, 0, 6 ) == 'Bearer') {
2573
 
2574
                    $token = trim(substr($token, 7));
2575
 
2576
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
2577
                        $key = $this->config['leaderslinked.jwt.key'];
2578
 
2579
 
2580
                        try {
2581
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
2582
 
2583
 
2584
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
2585
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
2586
                            }
2587
 
2588
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
2589
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2590
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
2591
                        } catch(\Exception $e) {
2592
                            //Token invalido
2593
                        }
2594
                    }
2595
                }
2596
            }
344 www 2597
 
340 www 2598
 
2599
            if(!$jwtToken) {
2600
 
2601
                $aes = Functions::generatePassword(16);
2602
 
2603
                $jwtToken = new JwtToken();
2604
                $jwtToken->aes = $aes;
2605
 
2606
                $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
2607
                if($jwtTokenMapper->insert($jwtToken)) {
2608
                    $jwtToken = $jwtTokenMapper->fetchOne($jwtToken->id);
2609
                }
2610
 
2611
                $token = '';
2612
 
2613
                if(!empty($this->config['leaderslinked.jwt.key'])) {
2614
                    $issuedAt   = new \DateTimeImmutable();
2615
                    $expire     = $issuedAt->modify('+365 days')->getTimestamp();
2616
                    $serverName = $_SERVER['HTTP_HOST'];
2617
                    $payload = [
2618
                        'iat'  => $issuedAt->getTimestamp(),
2619
                        'iss'  => $serverName,
2620
                        'nbf'  => $issuedAt->getTimestamp(),
2621
                        'exp'  => $expire,
2622
                        'uuid' => $jwtToken->uuid,
2623
                    ];
2624
 
2625
 
2626
                    $key = $this->config['leaderslinked.jwt.key'];
2627
                    $token = JWT::encode($payload, $key, 'HS256');
2628
                }
2629
            }
2630
 
2631
 
2632
 
2633
 
2634
 
2635
 
2636
 
2637
            if ($this->config['leaderslinked.runmode.sandbox']) {
2638
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
2639
            } else {
2640
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
2641
            }
2642
 
2643
 
2644
            $access_usign_social_networks = $this->config['leaderslinked.runmode.access_usign_social_networks'];
2645
 
2646
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
2647
            if ($sandbox) {
2648
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
2649
            } else {
2650
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
2651
            }
2652
 
2653
 
2654
            $parts = explode('.', $currentNetwork->main_hostname);
2655
            if($parts[1] === 'com') {
2656
                $replace_main = false;
2657
            } else {
2658
                $replace_main = true;
2659
            }
2660
 
2661
 
2662
            $storage = Storage::getInstance($this->config, $this->adapter);
2663
            $path = $storage->getPathNetwork();
2664
 
2665
            if($currentNetwork->logo) {
2666
                $logo_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->logo);
2667
            } else {
2668
                $logo_url = '';
2669
            }
2670
 
2671
            if($currentNetwork->navbar) {
2672
                $navbar_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->navbar);
2673
            } else {
2674
                $navbar_url = '';
2675
            }
2676
 
2677
            if($currentNetwork->favico) {
2678
                $favico_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->favico);
2679
            } else {
2680
                $favico_url = '';
2681
            }
2682
 
2683
 
2684
 
2685
 
2686
            $data = [
2687
                'google_map_key'                => $google_map_key,
2688
                'email'                         => '',
2689
                'remember'                      => false,
2690
                'site_key'                      => $site_key,
2691
                'theme_id'                      => $currentNetwork->theme_id,
2692
                'aes'                           => $aes,
2693
                'jwt'                           => $token,
2694
                'defaultNetwork'                => $currentNetwork->default,
2695
                'access_usign_social_networks'  => $access_usign_social_networks && $currentNetwork->default == Network::DEFAULT_YES ? 'y' : 'n',
2696
                'logo_url'                      => $logo_url,
2697
                'navbar_url'                    => $navbar_url,
2698
                'favico_url'                    => $favico_url,
2699
                'intro'                         => $currentNetwork->intro ? $currentNetwork->intro : '',
2700
                'is_logged_in'                  => $jwtToken->user_id ? true : false,
2701
 
2702
            ];
2703
 
2704
            if($currentNetwork->default == Network::DEFAULT_YES) {
2705
 
2706
 
2707
 
2708
                $currentUserPlugin = $this->plugin('currentUserPlugin');
2709
                if ($currentUserPlugin->hasIdentity()) {
2710
 
2711
 
2712
                    $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
2713
                    $externalCredentials->getUserBy($currentUserPlugin->getUserId());
2714
 
2715
 
2716
                    if($currentNetwork->xmpp_active) {
2717
                        $data['xmpp_domain']      = $currentNetwork->xmpp_domain;
2718
                        $data['xmpp_hostname']    = $currentNetwork->xmpp_hostname;
2719
                        $data['xmpp_port']        = $currentNetwork->xmpp_port;
2720
                        $data['xmpp_username']    = $externalCredentials->getUsernameXmpp();
2721
                        $data['xmpp_password']    = $externalCredentials->getPasswordXmpp();
2722
                        $data['inmail_username']    = $externalCredentials->getUsernameInmail();
2723
                        $data['inmail_password']    = $externalCredentials->getPasswordInmail();
2724
                    }
2725
                }
2726
            }
2727
 
2728
            $data = [
2729
                'success' => true,
2730
                'data' =>  $data
2731
            ];
2732
 
2733
        } else {
2734
            $data = [
2735
                'success' => false,
2736
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2737
            ];
2738
 
2739
            return new JsonModel($data);
2740
        }
2741
 
2742
        return new JsonModel($data);
2743
    }
257 efrain 2744
 
2745
 
2746
 
1 efrain 2747
}