Proyectos de Subversion LeadersLinked - Services

Rev

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