Proyectos de Subversion LeadersLinked - Services

Rev

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

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