Proyectos de Subversion LeadersLinked - Services

Rev

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

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