Proyectos de Subversion LeadersLinked - Services

Rev

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