Proyectos de Subversion LeadersLinked - Services

Rev

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

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