Proyectos de Subversion LeadersLinked - Services

Rev

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