Proyectos de Subversion LeadersLinked - Services

Rev

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

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