Proyectos de Subversion LeadersLinked - Services

Rev

Rev 18 | Rev 24 | 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\Db\Adapter\AdapterInterface;
13
use Laminas\Http\Header\SetCookie;
14
use Laminas\Mvc\Controller\AbstractActionController;
15
use Laminas\Log\LoggerInterface;
16
use Laminas\View\Model\ViewModel;
17
use Laminas\View\Model\JsonModel;
18
 
19
use LeadersLinked\Form\Auth\SigninForm;
20
use LeadersLinked\Form\Auth\ResetPasswordForm;
21
use LeadersLinked\Form\Auth\ForgotPasswordForm;
22
use LeadersLinked\Form\Auth\SignupForm;
23
 
24
use LeadersLinked\Mapper\ConnectionMapper;
25
use LeadersLinked\Mapper\EmailTemplateMapper;
26
use LeadersLinked\Mapper\NetworkMapper;
27
use LeadersLinked\Mapper\UserMapper;
28
 
29
use LeadersLinked\Model\User;
30
use LeadersLinked\Model\UserType;
31
use LeadersLinked\Library\QueueEmail;
32
use LeadersLinked\Library\Functions;
33
use LeadersLinked\Model\EmailTemplate;
34
use LeadersLinked\Mapper\UserPasswordMapper;
35
use LeadersLinked\Model\UserBrowser;
36
use LeadersLinked\Mapper\UserBrowserMapper;
37
use LeadersLinked\Mapper\UserIpMapper;
38
use LeadersLinked\Model\UserIp;
39
use LeadersLinked\Form\Auth\MoodleForm;
40
use LeadersLinked\Library\Rsa;
41
use LeadersLinked\Library\Image;
42
 
43
use LeadersLinked\Authentication\AuthAdapter;
44
use LeadersLinked\Authentication\AuthEmailAdapter;
45
 
46
use LeadersLinked\Model\UserPassword;
47
 
48
use LeadersLinked\Model\Connection;
49
use LeadersLinked\Authentication\AuthImpersonateAdapter;
50
use LeadersLinked\Model\Network;
51
use LeadersLinked\Cache\CacheInterface;
52
use LeadersLinked\Cache\CacheImpl;
53
use Laminas\Mvc\I18n\Translator;
23 efrain 54
use LeadersLinked\Model\JwtToken;
55
use LeadersLinked\Mapper\JwtTokenMapper;
56
use Firebase\JWT\JWT;
1 efrain 57
 
58
 
59
 
60
class AuthController extends AbstractActionController
61
{
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();
122
 
123
 
124
            $form = new  SigninForm($this->config);
125
            $dataPost = $request->getPost()->toArray();
126
 
127
            if (empty($_SESSION['aes'])) {
128
                return new JsonModel([
129
                    'success'   => false,
130
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
131
                ]);
132
            }
133
 
134
            if (!empty($dataPost['email'])) {
135
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
136
            }
137
 
138
 
139
            if (!empty($dataPost['password'])) {
140
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
18 efrain 141
            }
1 efrain 142
 
143
            $form->setData($dataPost);
144
 
145
            if ($form->isValid()) {
146
                $dataPost = (array) $form->getData();
147
 
148
                $email      = $dataPost['email'];
149
                $password   = $dataPost['password'];
150
                $remember   = $dataPost['remember'];
151
 
152
                $authAdapter = new AuthAdapter($this->adapter, $this->logger);
153
                $authAdapter->setData($email, $password, $currentNetwork->id);
154
                $authService = new AuthenticationService();
155
 
156
                $result = $authService->authenticate($authAdapter);
157
 
158
                if ($result->getCode() == AuthResult::SUCCESS) {
159
 
160
 
161
                    $userMapper = UserMapper::getInstance($this->adapter);
162
                    $user = $userMapper->fetchOneByEmail($email);
163
 
164
                    $navigator = get_browser(null, true);
165
                    $device_type    =  isset($navigator['device_type']) ? $navigator['device_type'] : '';
166
                    $platform       =  isset($navigator['platform']) ? $navigator['platform'] : '';
167
                    $browser        =  isset($navigator['browser']) ? $navigator['browser'] : '';
168
 
169
 
170
                    $istablet = isset($navigator['istablet']) ?  intval($navigator['istablet']) : 0;
171
                    $ismobiledevice = isset($navigator['ismobiledevice']) ? intval($navigator['ismobiledevice']) : 0;
172
                    $version = isset($navigator['version']) ? $navigator['version'] : '';
173
 
174
 
175
                    $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
176
                    $userBrowser = $userBrowserMapper->fetch($user->id, $device_type, $platform, $browser);
177
                    if ($userBrowser) {
178
                        $userBrowserMapper->update($userBrowser);
179
                    } else {
180
                        $userBrowser = new UserBrowser();
181
                        $userBrowser->user_id           = $user->id;
182
                        $userBrowser->browser           = $browser;
183
                        $userBrowser->platform          = $platform;
184
                        $userBrowser->device_type       = $device_type;
185
                        $userBrowser->is_tablet         = $istablet;
186
                        $userBrowser->is_mobile_device  = $ismobiledevice;
187
                        $userBrowser->version           = $version;
188
 
189
                        $userBrowserMapper->insert($userBrowser);
190
                    }
191
                    //
192
 
193
                    $ip = Functions::getUserIP();
194
                    $ip = $ip == '127.0.0.1' ? '148.240.211.148' : $ip;
195
 
196
                    $userIpMapper = UserIpMapper::getInstance($this->adapter);
197
                    $userIp = $userIpMapper->fetch($user->id, $ip);
198
                    if (empty($userIp)) {
199
 
200
                        if ($this->config['leaderslinked.runmode.sandbox']) {
201
                            $filename = $this->config['leaderslinked.geoip2.production_database'];
202
                        } else {
203
                            $filename = $this->config['leaderslinked.geoip2.sandbox_database'];
204
                        }
205
 
206
                        $reader = new GeoIp2Reader($filename); //GeoIP2-City.mmdb');
207
                        $record = $reader->city($ip);
208
                        if ($record) {
209
                            $userIp = new UserIp();
210
                            $userIp->user_id = $user->id;
211
                            $userIp->city = !empty($record->city->name) ? Functions::utf8_decode($record->city->name) : '';
212
                            $userIp->state_code = !empty($record->mostSpecificSubdivision->isoCode) ? Functions::utf8_decode($record->mostSpecificSubdivision->isoCode) : '';
213
                            $userIp->state_name = !empty($record->mostSpecificSubdivision->name) ? Functions::utf8_decode($record->mostSpecificSubdivision->name) : '';
214
                            $userIp->country_code = !empty($record->country->isoCode) ? Functions::utf8_decode($record->country->isoCode) : '';
215
                            $userIp->country_name = !empty($record->country->name) ? Functions::utf8_decode($record->country->name) : '';
216
                            $userIp->ip = $ip;
217
                            $userIp->latitude = !empty($record->location->latitude) ? $record->location->latitude : 0;
218
                            $userIp->longitude = !empty($record->location->longitude) ? $record->location->longitude : 0;
219
                            $userIp->postal_code = !empty($record->postal->code) ? $record->postal->code : '';
220
 
221
                            $userIpMapper->insert($userIp);
222
                        }
223
                    } else {
224
                        $userIpMapper->update($userIp);
225
                    }
226
 
227
                    if ($remember) {
228
                        $expired = time() + 365 * 24 * 60 * 60;
229
 
230
                        $cookieEmail = new SetCookie('email', $email, $expired);
231
                    } else {
232
                        $expired = time() - 7200;
233
                        $cookieEmail = new SetCookie('email', '', $expired);
234
                    }
235
 
236
 
237
                    $response = $this->getResponse();
238
                    $response->getHeaders()->addHeader($cookieEmail);
239
 
240
 
241
 
242
 
243
 
244
 
245
 
246
                    $this->logger->info('Ingreso a LeadersLiked', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
247
 
248
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
249
 
250
                    if ($user_share_invitation) {
251
                        $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
252
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
253
                            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
254
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
255
 
256
                            if ($connection) {
257
 
258
                                if ($connection->status != Connection::STATUS_ACCEPTED) {
259
                                    $connectionMapper->approve($connection);
260
                                }
261
                            } else {
262
                                $connection = new Connection();
263
                                $connection->request_from = $user->id;
264
                                $connection->request_to = $userRedirect->id;
265
                                $connection->status = Connection::STATUS_ACCEPTED;
266
 
267
                                $connectionMapper->insert($connection);
268
                            }
269
                        }
270
                    }
271
 
272
 
273
 
274
                    $data = [
275
                        'success'   => true,
276
                        'data'      => $this->url()->fromRoute('dashboard'),
277
                    ];
278
 
279
                    $this->cache->removeItem('user_share_invitation');
280
                } else {
281
 
282
                    $message = $result->getMessages()[0];
283
                    if (!in_array($message, [
284
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
285
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
286
                        'ERROR_ENTERED_PASS_INCORRECT_1', 'ERROR_USER_REQUEST_ACCESS_IS_PENDING', 'ERROR_USER_REQUEST_ACCESS_IS_REJECTED'
287
 
288
 
289
                    ])) {
290
                    }
291
 
292
                    switch ($message) {
293
                        case 'ERROR_USER_NOT_FOUND':
294
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
295
                            break;
296
 
297
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
298
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
299
                            break;
300
 
301
                        case 'ERROR_USER_IS_BLOCKED':
302
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
303
                            break;
304
 
305
                        case 'ERROR_USER_IS_INACTIVE':
306
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
307
                            break;
308
 
309
 
310
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
311
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
312
                            break;
313
 
314
 
315
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
316
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
317
                            break;
318
 
319
 
320
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
321
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
322
                            break;
323
 
324
 
325
                        case 'ERROR_USER_REQUEST_ACCESS_IS_PENDING':
326
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Falta verificar que pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
327
                            break;
328
 
329
                        case  'ERROR_USER_REQUEST_ACCESS_IS_REJECTED':
330
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Rechazado por no pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
331
                            break;
332
 
333
 
334
                        default:
335
                            $message = 'ERROR_UNKNOWN';
336
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
337
                            break;
338
                    }
339
 
340
 
341
 
342
 
343
                    $data = [
344
                        'success'   => false,
345
                        'data'   => $message
346
                    ];
347
                }
348
 
349
                return new JsonModel($data);
350
            } else {
351
                $messages = [];
352
 
353
 
354
 
355
                $form_messages = (array) $form->getMessages();
356
                foreach ($form_messages  as $fieldname => $field_messages) {
357
 
358
                    $messages[$fieldname] = array_values($field_messages);
359
                }
360
 
361
                return new JsonModel([
362
                    'success'   => false,
363
                    'data'   => $messages
364
                ]);
365
            }
366
        } else if ($request->isGet()) {
367
 
23 efrain 368
            $aes = Functions::generatePassword(16);
1 efrain 369
 
23 efrain 370
            $jwtToken = new JwtToken();
371
            $jwtToken->aes = $aes;
372
 
373
            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
374
            if($jwtTokenMapper->insert($jwtToken)) {
375
                $jwtToken = $jwtTokenMapper->fetchOne($jwtToken->id);
1 efrain 376
            }
23 efrain 377
 
378
            $token = '';
379
 
380
            if(!empty($this->config['leaderslinked.jwt.key'])) {
381
                $issuedAt   = new \DateTimeImmutable();
382
                $expire     = $issuedAt->modify('+24 hours')->getTimestamp();
383
                $serverName = $_SERVER['HTTP_HOST'];
384
                $payload = [
385
                    'iat'  => $issuedAt->getTimestamp(),
386
                    'iss'  => $serverName,
387
                    'nbf'  => $issuedAt->getTimestamp(),
388
                    'exp'  => $expire,
389
                    'uuid' => $jwtToken->uuid,
390
                ];
391
 
392
 
393
                $key = $this->config['leaderslinked.jwt.key'];
394
                $token = JWT::encode($payload, $key, 'HS256');
395
            }
396
 
397
 
398
 
1 efrain 399
 
23 efrain 400
 
1 efrain 401
            if ($this->config['leaderslinked.runmode.sandbox']) {
402
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
403
            } else {
404
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
405
            }
406
 
407
 
408
            $access_usign_social_networks = $this->config['leaderslinked.runmode.access_usign_social_networks'];
409
 
410
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
411
            if ($sandbox) {
412
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
413
            } else {
414
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
415
            }
416
 
417
 
418
            $data = [
23 efrain 419
                'google_map_key'                => $google_map_key,
420
                'email'                         => '',
421
                'remember'                      => false,
422
                'site_key'                      => $site_key,
423
                'theme_id'                      => $currentNetwork->theme_id,
424
                'aes'                           => $aes,
425
                'jwt'                           => $token,
426
                'defaultNetwork'                => $currentNetwork->default,
427
                'access_usign_social_networks'  => $access_usign_social_networks && $currentNetwork->default == Network::DEFAULT_YES ? 'y' : 'n',
428
                'logo_url'                      => $this->url()->fromRoute('storage-network', ['type' => 'logo']),
429
                'navbar_url'                    => $this->url()->fromRoute('storage-network', ['type' => 'navbar']),
430
                'favico_url'                    => $this->url()->fromRoute('storage-network', ['type' => 'favico']),
431
                'intro'                         => $currentNetwork->intro,
432
                'is_logged_in'                  => false
1 efrain 433
 
434
            ];
435
 
436
        } else {
437
            $data = [
438
                'success' => false,
439
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
440
            ];
441
 
442
            return new JsonModel($data);
443
        }
444
 
445
        return new JsonModel($data);
446
    }
447
 
448
    public function facebookAction()
449
    {
450
 
451
        $request = $this->getRequest();
452
        if ($request->isGet()) {
453
            /*
454
          //  try {
455
                $app_id = $this->config['leaderslinked.facebook.app_id'];
456
                $app_password = $this->config['leaderslinked.facebook.app_password'];
457
                $app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];
458
                //$app_url_auth = $this->config['leaderslinked.facebook.app_url_auth'];
459
                //$redirect_url = $this->config['leaderslinked.facebook.app_redirect_url'];
460
 
461
                [facebook]
462
                app_id=343770226993130
463
                app_password=028ee729090fd591e50a17a786666c12
464
                app_graph_version=v17
465
                app_redirect_url=https://leaderslinked.com/oauth/facebook
466
 
467
                https://www.facebook.com/v17.0/dialog/oauth?client_id=343770226993130&redirect_uri= https://dev.leaderslinked.com/oauth/facebook&state=AE12345678
468
 
469
 
470
                $s = 'https://www.facebook.com/v17.0/dialog/oauth' .
471
                    '?client_id='
472
                    '&redirect_uri={"https://www.domain.com/login"}
473
                    '&state={"{st=state123abc,ds=123456789}"}
474
 
475
                $fb = new \Facebook\Facebook([
476
                    'app_id' => $app_id,
477
                    'app_secret' => $app_password,
478
                    'default_graph_version' => $app_graph_version,
479
                ]);
480
 
481
                $app_url_auth =  $this->url()->fromRoute('oauth/facebook', [], ['force_canonical' => true]);
482
                $helper = $fb->getRedirectLoginHelper();
483
                $permissions = ['email', 'public_profile']; // Optional permissions
484
                $facebookUrl = $helper->getLoginUrl($app_url_auth, $permissions);
485
 
486
 
487
 
488
                return new JsonModel([
489
                    'success' => false,
490
                    'data' => $facebookUrl
491
                ]);
492
            } catch (\Throwable $e) {
493
                return new JsonModel([
494
                    'success' => false,
495
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_FACEBOOK'
496
                ]);
497
            }*/
498
        } else {
499
            return new JsonModel([
500
                'success' => false,
501
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
502
            ]);
503
        }
504
    }
505
 
506
    public function twitterAction()
507
    {
508
        $request = $this->getRequest();
509
        if ($request->isGet()) {
510
 
511
            try {
512
                if ($this->config['leaderslinked.runmode.sandbox']) {
513
 
514
                    $twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];
515
                    $twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];
516
                } else {
517
                    $twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];
518
                    $twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];
519
                }
520
 
521
                /*
522
                 echo '$twitter_api_key = ' . $twitter_api_key . PHP_EOL;
523
                 echo '$twitter_api_secret = ' . $twitter_api_secret . PHP_EOL;
524
                 exit;
525
                 */
526
 
527
                //Twitter
528
                //$redirect_url =  $this->url()->fromRoute('oauth/twitter', [], ['force_canonical' => true]);
529
                $redirect_url = $this->config['leaderslinked.twitter.app_redirect_url'];
530
                $twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret);
531
                $request_token =  $twitter->oauth('oauth/request_token', ['oauth_callback' => $redirect_url]);
532
                $twitterUrl = $twitter->url('oauth/authorize', ['oauth_token' => $request_token['oauth_token']]);
533
 
534
                $twitterSession = new \Laminas\Session\Container('twitter');
535
                $twitterSession->oauth_token = $request_token['oauth_token'];
536
                $twitterSession->oauth_token_secret = $request_token['oauth_token_secret'];
537
 
538
                return new JsonModel([
539
                    'success' => true,
540
                    'data' =>  $twitterUrl
541
                ]);
542
            } catch (\Throwable $e) {
543
                return new JsonModel([
544
                    'success' => false,
545
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_TWITTER'
546
                ]);
547
            }
548
        } else {
549
            return new JsonModel([
550
                'success' => false,
551
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
552
            ]);
553
        }
554
    }
555
 
556
    public function googleAction()
557
    {
558
        $request = $this->getRequest();
559
        if ($request->isGet()) {
560
 
561
            try {
562
 
563
 
564
                //Google
565
                $google = new \Google_Client();
566
                $google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');
567
                $google->setAccessType("offline");        // offline access
568
 
569
                $google->setIncludeGrantedScopes(true);   // incremental auth
570
 
571
                $google->addScope('profile');
572
                $google->addScope('email');
573
 
574
                // $redirect_url =  $this->url()->fromRoute('oauth/google', [], ['force_canonical' => true]);
575
                $redirect_url = $this->config['leaderslinked.google_auth.app_redirect_url'];
576
 
577
                $google->setRedirectUri($redirect_url);
578
                $googleUrl = $google->createAuthUrl();
579
 
580
                return new JsonModel([
581
                    'success' => true,
582
                    'data' =>  $googleUrl
583
                ]);
584
            } catch (\Throwable $e) {
585
                return new JsonModel([
586
                    'success' => false,
587
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_GOOGLE'
588
                ]);
589
            }
590
        } else {
591
            return new JsonModel([
592
                'success' => false,
593
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
594
            ]);
595
        }
596
    }
597
 
598
    public function signoutAction()
599
    {
600
        $currentUserPlugin = $this->plugin('currentUserPlugin');
601
        $currentUser = $currentUserPlugin->getRawUser();
602
        if ($currentUserPlugin->hasImpersonate()) {
603
 
604
 
605
            $userMapper = UserMapper::getInstance($this->adapter);
606
            $userMapper->leaveImpersonate($currentUser->id);
607
 
608
            $networkMapper = NetworkMapper::getInstance($this->adapter);
609
            $network = $networkMapper->fetchOne($currentUser->network_id);
610
 
611
 
612
            if (!$currentUser->one_time_password) {
613
                $one_time_password = Functions::generatePassword(25);
614
 
615
                $currentUser->one_time_password = $one_time_password;
616
 
617
                $userMapper = UserMapper::getInstance($this->adapter);
618
                $userMapper->updateOneTimePassword($currentUser, $one_time_password);
619
            }
620
 
621
 
622
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
623
            if ($sandbox) {
624
                $salt = $this->config['leaderslinked.backend.sandbox_salt'];
625
            } else {
626
                $salt = $this->config['leaderslinked.backend.production_salt'];
627
            }
628
 
629
            $rand = 1000 + mt_rand(1, 999);
630
            $timestamp = time();
631
            $password = md5($currentUser->one_time_password . '-' . $rand . '-' . $timestamp . '-' . $salt);
632
 
633
            $params = [
634
                'user_uuid' => $currentUser->uuid,
635
                'password' => $password,
636
                'rand' => $rand,
637
                'time' => $timestamp,
638
            ];
639
 
640
            $currentUserPlugin->clearIdentity();
641
 
642
            return new JsonModel([
643
                'success'   => true,
644
                'data'      => [
645
                    'message' => 'LABEL_SIGNOUT_SUCCESSFULLY',
646
                    'url' => 'https://' . $network->main_hostname . '/signin/impersonate' . '?' . http_build_query($params)
647
                ],
648
 
649
            ]);
650
 
651
 
652
           // $url = 'https://' . $network->main_hostname . '/signin/impersonate' . '?' . http_build_query($params);
653
           // return $this->redirect()->toUrl($url);
654
        } else {
655
 
656
 
657
            if ($currentUserPlugin->hasIdentity()) {
658
 
659
                $this->logger->info('Desconexión de LeadersLinked', ['user_id' => $currentUserPlugin->getUserId(), 'ip' => Functions::getUserIP()]);
660
            }
661
 
662
            $currentUserPlugin->clearIdentity();
663
 
664
           // return $this->redirect()->toRoute('home');
665
 
666
            return new JsonModel([
667
                'success'   => true,
668
                'data'      => [
669
                    'message' => 'LABEL_SIGNOUT_SUCCESSFULLY',
670
                    'url' => '',
671
                ],
672
 
673
            ]);
674
        }
675
    }
676
 
677
 
678
    public function resetPasswordAction()
679
    {
680
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
681
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
682
 
683
 
684
        $flashMessenger = $this->plugin('FlashMessenger');
685
        $code =  Functions::sanitizeFilterString($this->params()->fromRoute('code', ''));
686
 
687
        $userMapper = UserMapper::getInstance($this->adapter);
688
        $user = $userMapper->fetchOneByPasswordResetKeyAndNetworkId($code, $currentNetwork->id);
689
        if (!$user) {
690
            $this->logger->err('Restablecer contraseña - Error código no existe', ['ip' => Functions::getUserIP()]);
691
 
692
            return new JsonModel([
693
                'success'   => true,
694
                'data'      => 'ERROR_PASSWORD_RECOVER_CODE_IS_INVALID'
695
            ]);
696
 
697
        }
698
 
699
 
700
 
701
        $password_generated_on = strtotime($user->password_generated_on);
702
        $expiry_time = $password_generated_on + $this->config['leaderslinked.security.reset_password_expired'];
703
        if (time() > $expiry_time) {
704
            $this->logger->err('Restablecer contraseña - Error código expirado', ['ip' => Functions::getUserIP()]);
705
 
706
            return new JsonModel([
707
                'success'   => true,
708
                'data'      => 'ERROR_PASSWORD_RECOVER_CODE_HAS_EXPIRED'
709
            ]);
710
        }
711
 
712
        $request = $this->getRequest();
713
        if ($request->isPost()) {
714
            $dataPost = $request->getPost()->toArray();
715
            if (empty($_SESSION['aes'])) {
716
                return new JsonModel([
717
                    'success'   => false,
718
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
719
                ]);
720
 
721
 
722
            }
723
 
724
            if (!empty($dataPost['password'])) {
725
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
726
            }
727
            if (!empty($dataPost['confirmation'])) {
728
                $dataPost['confirmation'] = CryptoJsAes::decrypt($dataPost['confirmation'], $_SESSION['aes']);
729
            }
730
 
731
 
732
 
733
            $form = new ResetPasswordForm($this->config);
734
            $form->setData($dataPost);
735
 
736
            if ($form->isValid()) {
737
                $data = (array) $form->getData();
738
                $password = $data['password'];
739
 
740
 
741
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
742
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);
743
 
744
                $oldPassword = false;
745
                foreach ($userPasswords as $userPassword) {
746
                    if (password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password)) {
747
                        $oldPassword = true;
748
                        break;
749
                    }
750
                }
751
 
752
                if ($oldPassword) {
753
                    $this->logger->err('Restablecer contraseña - Error contraseña ya utilizada anteriormente', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
754
 
755
                    return new JsonModel([
756
                        'success'   => false,
757
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
758
 
759
                    ]);
760
                } else {
761
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
762
 
763
 
764
                    $result = $userMapper->updatePassword($user, $password_hash);
765
                    if ($result) {
766
 
767
                        $userPassword = new UserPassword();
768
                        $userPassword->user_id = $user->id;
769
                        $userPassword->password = $password_hash;
770
                        $userPasswordMapper->insert($userPassword);
771
 
772
 
773
                        $this->logger->info('Restablecer contraseña realizado', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
774
 
775
 
776
                        $flashMessenger->addSuccessMessage('LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED');
777
 
778
                        return new JsonModel([
779
                            'success'   => true,
780
                            'data'      => [
781
                                'message' => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED',
782
                                'redirect' => $this->url()->fromRoute('home'),
783
                            ],
784
 
785
                        ]);
786
                    } else {
787
                        $this->logger->err('Restablecer contraseña - Error desconocido', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
788
 
789
                        return new JsonModel([
790
                            'success'   => false,
791
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
792
 
793
                        ]);
794
                    }
795
                }
796
            } else {
797
                $form_messages =  $form->getMessages('captcha');
798
                if (!empty($form_messages)) {
799
                    return new JsonModel([
800
                        'success'   => false,
801
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
802
                    ]);
803
                }
804
 
805
                $messages = [];
806
 
807
                $form_messages = (array) $form->getMessages();
808
                foreach ($form_messages  as $fieldname => $field_messages) {
809
                    $messages[$fieldname] = array_values($field_messages);
810
                }
811
 
812
                return new JsonModel([
813
                    'success'   => false,
814
                    'data'   => $messages
815
                ]);
816
            }
817
        } else if ($request->isGet()) {
818
 
819
            if (empty($_SESSION['aes'])) {
820
                $_SESSION['aes'] = Functions::generatePassword(16);
821
            }
822
 
823
            if ($this->config['leaderslinked.runmode.sandbox']) {
824
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
825
            } else {
826
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
827
            }
828
 
829
 
830
            return new JsonModel([
831
                'code' => $code,
832
                'site_key' => $site_key,
833
                'aes'       => $_SESSION['aes'],
834
                'defaultNetwork' => $currentNetwork->default,
835
            ]);
836
 
837
        }
838
 
839
 
840
 
841
        return new JsonModel([
842
            'success' => false,
843
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
844
        ]);
845
    }
846
 
847
    public function forgotPasswordAction()
848
    {
849
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
850
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
851
 
852
 
853
 
854
        $request = $this->getRequest();
855
        if ($request->isPost()) {
856
            $dataPost = $request->getPost()->toArray();
857
            if (empty($_SESSION['aes'])) {
858
                return new JsonModel([
859
                    'success'   => false,
860
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
861
                ]);
862
            }
863
 
864
            if (!empty($dataPost['email'])) {
865
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
866
            }
867
 
868
            $form = new ForgotPasswordForm($this->config);
869
            $form->setData($dataPost);
870
 
871
            if ($form->isValid()) {
872
                $dataPost = (array) $form->getData();
873
                $email      = $dataPost['email'];
874
 
875
                $userMapper = UserMapper::getInstance($this->adapter);
876
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
877
                if (!$user) {
878
                    $this->logger->err('Olvidó contraseña ' . $email . '- Email no existe ', ['ip' => Functions::getUserIP()]);
879
 
880
                    return new JsonModel([
881
                        'success' => false,
882
                        'data' =>  'ERROR_EMAIL_IS_NOT_REGISTERED'
883
                    ]);
884
                } else {
885
                    if ($user->status == User::STATUS_INACTIVE) {
886
                        return new JsonModel([
887
                            'success' => false,
888
                            'data' =>  'ERROR_USER_IS_INACTIVE'
889
                        ]);
890
                    } else if ($user->email_verified == User::EMAIL_VERIFIED_NO) {
891
                        $this->logger->err('Olvidó contraseña - Email no verificado ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
892
 
893
                        return new JsonModel([
894
                            'success' => false,
895
                            'data' => 'ERROR_EMAIL_HAS_NOT_BEEN_VERIFIED'
896
                        ]);
897
                    } else {
898
                        $password_reset_key = md5($user->email . time());
899
                        $userMapper->updatePasswordResetKey((int) $user->id, $password_reset_key);
900
 
901
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
902
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RESET_PASSWORD, $currentNetwork->id);
903
                        if ($emailTemplate) {
904
                            $arrayCont = [
905
                                'firstname'             => $user->first_name,
906
                                'lastname'              => $user->last_name,
907
                                'other_user_firstname'  => '',
908
                                'other_user_lastname'   => '',
909
                                'company_name'          => '',
910
                                'group_name'            => '',
911
                                'content'               => '',
912
                                'code'                  => '',
913
                                'link'                  => $this->url()->fromRoute('reset-password', ['code' => $password_reset_key], ['force_canonical' => true])
914
                            ];
915
 
916
                            $email = new QueueEmail($this->adapter);
917
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
918
                        }
919
                        $flashMessenger = $this->plugin('FlashMessenger');
920
                        $flashMessenger->addSuccessMessage('LABEL_RECOVERY_LINK_WAS_SENT_TO_YOUR_EMAIL');
921
 
922
                        $this->logger->info('Olvidó contraseña - Se envio link de recuperación ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
923
 
924
                        return new JsonModel([
925
                            'success' => true,
926
                        ]);
927
                    }
928
                }
929
            } else {
930
 
931
 
932
                $form_messages =  $form->getMessages('captcha');
933
 
934
 
935
 
936
                if (!empty($form_messages)) {
937
                    return new JsonModel([
938
                        'success'   => false,
939
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
940
                    ]);
941
                }
942
 
943
                $messages = [];
944
                $form_messages = (array) $form->getMessages();
945
                foreach ($form_messages  as $fieldname => $field_messages) {
946
                    $messages[$fieldname] = array_values($field_messages);
947
                }
948
 
949
                return new JsonModel([
950
                    'success'   => false,
951
                    'data'      => $messages
952
                ]);
953
            }
954
        } else  if ($request->isGet()) {
955
 
956
            if (empty($_SESSION['aes'])) {
957
                $_SESSION['aes'] = Functions::generatePassword(16);
958
            }
959
 
960
            if ($this->config['leaderslinked.runmode.sandbox']) {
961
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
962
            } else {
963
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
964
            }
965
 
966
            return new JsonModel([
967
                'site_key'  => $site_key,
968
                'aes'       => $_SESSION['aes'],
969
                'defaultNetwork' => $currentNetwork->default,
970
            ]);
971
        }
972
 
973
        return new JsonModel([
974
            'success' => false,
975
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
976
        ]);
977
    }
978
 
979
    public function signupAction()
980
    {
981
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
982
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
983
 
984
 
985
        $request = $this->getRequest();
986
        if ($request->isPost()) {
987
            $dataPost = $request->getPost()->toArray();
988
 
989
            if (empty($_SESSION['aes'])) {
990
                return new JsonModel([
991
                    'success'   => false,
992
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
993
                ]);
994
            }
995
 
996
            if (!empty($dataPost['email'])) {
997
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
998
            }
999
 
1000
            if (!empty($dataPost['password'])) {
1001
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
1002
            }
1003
 
1004
            if (!empty($dataPost['confirmation'])) {
1005
                $dataPost['confirmation'] = CryptoJsAes::decrypt($dataPost['confirmation'], $_SESSION['aes']);
1006
            }
1007
 
1008
            if (empty($dataPost['is_adult'])) {
1009
                $dataPost['is_adult'] = User::IS_ADULT_NO;
1010
            } else {
1011
                $dataPost['is_adult'] = $dataPost['is_adult'] == User::IS_ADULT_YES ? User::IS_ADULT_YES : User::IS_ADULT_NO;
1012
            }
1013
 
1014
 
1015
 
1016
            $form = new SignupForm($this->config);
1017
            $form->setData($dataPost);
1018
 
1019
            if ($form->isValid()) {
1020
                $dataPost = (array) $form->getData();
1021
 
1022
                $email = $dataPost['email'];
1023
 
1024
                $userMapper = UserMapper::getInstance($this->adapter);
1025
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1026
                if ($user) {
1027
                    $this->logger->err('Registro ' . $email . '- Email ya  existe ', ['ip' => Functions::getUserIP()]);
1028
 
1029
 
1030
 
1031
                    return new JsonModel([
1032
                        'success' => false,
1033
                        'data' => 'ERROR_EMAIL_IS_REGISTERED'
1034
                    ]);
1035
                } else {
1036
 
1037
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
1038
 
1039
 
1040
                    if ($user_share_invitation) {
1041
                        $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
1042
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE) {
1043
                            $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1044
 
1045
                            $user = new User();
1046
                            $user->network_id           = $currentNetwork->id;
1047
                            $user->email                = $dataPost['email'];
1048
                            $user->first_name           = $dataPost['first_name'];
1049
                            $user->last_name            = $dataPost['last_name'];
1050
                            $user->usertype_id          = UserType::USER;
1051
                            $user->password             = $password_hash;
1052
                            $user->password_updated_on  = date('Y-m-d H:i:s');
1053
                            $user->status               = User::STATUS_ACTIVE;
1054
                            $user->blocked              = User::BLOCKED_NO;
1055
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
1056
                            $user->login_attempt        = 0;
1057
                            $user->is_adult             = $dataPost['is_adult'];
1058
                            $user->request_access       = User::REQUEST_ACCESS_APPROVED;
1059
 
1060
 
1061
 
1062
 
1063
 
1064
                            if ($userMapper->insert($user)) {
1065
 
1066
                                $userPassword = new UserPassword();
1067
                                $userPassword->user_id = $user->id;
1068
                                $userPassword->password = $password_hash;
1069
 
1070
                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1071
                                $userPasswordMapper->insert($userPassword);
1072
 
1073
 
1074
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1075
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1076
 
1077
                                if ($connection) {
1078
 
1079
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1080
                                        $connectionMapper->approve($connection);
1081
                                    }
1082
                                } else {
1083
                                    $connection = new Connection();
1084
                                    $connection->request_from = $user->id;
1085
                                    $connection->request_to = $userRedirect->id;
1086
                                    $connection->status = Connection::STATUS_ACCEPTED;
1087
 
1088
                                    $connectionMapper->insert($connection);
1089
                                }
1090
 
1091
 
1092
                                $this->cache->removeItem('user_share_invitation');
1093
 
1094
 
1095
 
1096
                                $data = [
1097
                                    'success'   => true,
1098
                                    'data'      => $this->url()->fromRoute('home'),
1099
                                ];
1100
 
1101
 
1102
                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1103
 
1104
                                return new JsonModel($data);
1105
                            }
1106
                        }
1107
                    }
1108
 
1109
 
1110
 
1111
 
1112
                    $timestamp = time();
1113
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);
1114
 
1115
                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1116
 
1117
                    $user = new User();
1118
                    $user->network_id           = $currentNetwork->id;
1119
                    $user->email                = $dataPost['email'];
1120
                    $user->first_name           = $dataPost['first_name'];
1121
                    $user->last_name            = $dataPost['last_name'];
1122
                    $user->usertype_id          = UserType::USER;
1123
                    $user->password             = $password_hash;
1124
                    $user->password_updated_on  = date('Y-m-d H:i:s');
1125
                    $user->activation_key       = $activation_key;
1126
                    $user->status               = User::STATUS_INACTIVE;
1127
                    $user->blocked              = User::BLOCKED_NO;
1128
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
1129
                    $user->login_attempt        = 0;
1130
 
1131
                    if ($currentNetwork->default == Network::DEFAULT_YES) {
1132
                        $user->request_access = User::REQUEST_ACCESS_APPROVED;
1133
                    } else {
1134
                        $user->request_access = User::REQUEST_ACCESS_PENDING;
1135
                    }
1136
 
1137
 
1138
 
1139
                    if ($userMapper->insert($user)) {
1140
 
1141
                        $userPassword = new UserPassword();
1142
                        $userPassword->user_id = $user->id;
1143
                        $userPassword->password = $password_hash;
1144
 
1145
                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1146
                        $userPasswordMapper->insert($userPassword);
1147
 
1148
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1149
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
1150
                        if ($emailTemplate) {
1151
                            $arrayCont = [
1152
                                'firstname'             => $user->first_name,
1153
                                'lastname'              => $user->last_name,
1154
                                'other_user_firstname'  => '',
1155
                                'other_user_lastname'   => '',
1156
                                'company_name'          => '',
1157
                                'group_name'            => '',
1158
                                'content'               => '',
1159
                                'code'                  => '',
1160
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
1161
                            ];
1162
 
1163
                            $email = new QueueEmail($this->adapter);
1164
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1165
                        }
1166
                        $flashMessenger = $this->plugin('FlashMessenger');
1167
                        $flashMessenger->addSuccessMessage('LABEL_REGISTRATION_DONE');
1168
 
1169
                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1170
 
1171
                        return new JsonModel([
1172
                            'success' => true,
1173
                        ]);
1174
                    } else {
1175
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);
1176
 
1177
                        return new JsonModel([
1178
                            'success' => false,
1179
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1180
                        ]);
1181
                    }
1182
                }
1183
            } else {
1184
 
1185
                $form_messages =  $form->getMessages('captcha');
1186
                if (!empty($form_messages)) {
1187
                    return new JsonModel([
1188
                        'success'   => false,
1189
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1190
                    ]);
1191
                }
1192
 
1193
                $messages = [];
1194
 
1195
                $form_messages = (array) $form->getMessages();
1196
                foreach ($form_messages  as $fieldname => $field_messages) {
1197
                    $messages[$fieldname] = array_values($field_messages);
1198
                }
1199
 
1200
                return new JsonModel([
1201
                    'success'   => false,
1202
                    'data'   => $messages
1203
                ]);
1204
            }
1205
        } else if ($request->isGet()) {
1206
 
1207
            if (empty($_SESSION['aes'])) {
1208
                $_SESSION['aes'] = Functions::generatePassword(16);
1209
            }
1210
 
1211
            if ($this->config['leaderslinked.runmode.sandbox']) {
1212
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1213
            } else {
1214
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1215
            }
1216
 
1217
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
1218
 
1219
            return new JsonModel([
1220
                'site_key'  => $site_key,
1221
                'aes'       => $_SESSION['aes'],
1222
                'defaultNetwork' => $currentNetwork->default,
1223
            ]);
1224
        }
1225
 
1226
        return new JsonModel([
1227
            'success' => false,
1228
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1229
        ]);
1230
    }
1231
 
1232
    public function activateAccountAction()
1233
    {
1234
 
1235
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1236
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1237
 
1238
 
1239
 
1240
        $request = $this->getRequest();
1241
        if ($request->isGet()) {
1242
            $code   =  Functions::sanitizeFilterString($this->params()->fromRoute('code'));
1243
            $userMapper = UserMapper::getInstance($this->adapter);
1244
            $user = $userMapper->fetchOneByActivationKeyAndNetworkId($code, $currentNetwork->id);
1245
 
1246
            $flashMessenger = $this->plugin('FlashMessenger');
1247
 
1248
            if ($user) {
1249
                if (User::EMAIL_VERIFIED_YES == $user->email_verified) {
1250
 
1251
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1252
 
1253
                    $flashMessenger->addErrorMessage('ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED');
1254
                } else {
1255
 
1256
                    if ($userMapper->activateAccount((int) $user->id)) {
1257
 
1258
                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1259
 
1260
 
1261
 
1262
                        $user_share_invitation = $this->cache->getItem('user_share_invitation');
1263
 
1264
                        if ($user_share_invitation) {
1265
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
1266
                            if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
1267
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1268
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1269
 
1270
                                if ($connection) {
1271
 
1272
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1273
                                        $connectionMapper->approve($connection);
1274
                                    }
1275
                                } else {
1276
                                    $connection = new Connection();
1277
                                    $connection->request_from = $user->id;
1278
                                    $connection->request_to = $userRedirect->id;
1279
                                    $connection->status = Connection::STATUS_ACCEPTED;
1280
 
1281
                                    $connectionMapper->insert($connection);
1282
                                }
1283
                            }
1284
                        }
1285
 
1286
 
1287
 
1288
                        $this->cache->removeItem('user_share_invitation');
1289
 
1290
 
1291
                        if ($currentNetwork->default == Network::DEFAULT_YES) {
1292
                            $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED');
1293
                        } else {
1294
 
1295
                            $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1296
                            $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_REQUEST_ACCESS_PENDING, $currentNetwork->id);
1297
 
1298
                            if ($emailTemplate) {
1299
                                $arrayCont = [
1300
                                    'firstname'             => $user->first_name,
1301
                                    'lastname'              => $user->last_name,
1302
                                    'other_user_firstname'  => '',
1303
                                    'other_user_lastname'   => '',
1304
                                    'company_name'          => '',
1305
                                    'group_name'            => '',
1306
                                    'content'               => '',
1307
                                    'code'                  => '',
1308
                                    'link'                  => '',
1309
                                ];
1310
 
1311
                                $email = new QueueEmail($this->adapter);
1312
                                $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1313
                            }
1314
 
1315
 
1316
                            $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED_WE_ARE_VERIFYING_YOUR_INFORMATION');
1317
                        }
1318
                    } else {
1319
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1320
 
1321
                        $flashMessenger->addErrorMessage('ERROR_THERE_WAS_AN_ERROR');
1322
                    }
1323
                }
1324
            } else {
1325
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);
1326
 
1327
                $flashMessenger->addErrorMessage('ERROR_ACTIVATION_CODE_IS_NOT_VALID');
1328
            }
1329
 
1330
            return $this->redirect()->toRoute('home');
1331
        } else {
1332
            $response = [
1333
                'success' => false,
1334
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1335
            ];
1336
        }
1337
 
1338
        return new JsonModel($response);
1339
    }
1340
 
1341
 
1342
 
1343
    public function onroomAction()
1344
    {
1345
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1346
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1347
 
1348
 
1349
 
1350
        $request = $this->getRequest();
1351
 
1352
        if ($request->isPost()) {
1353
 
1354
            $dataPost = $request->getPost()->toArray();
1355
 
1356
 
1357
            $form = new  MoodleForm();
1358
            $form->setData($dataPost);
1359
            if ($form->isValid()) {
1360
 
1361
                $dataPost   = (array) $form->getData();
1362
                $username   = $dataPost['username'];
1363
                $password   = $dataPost['password'];
1364
                $timestamp  = $dataPost['timestamp'];
1365
                $rand       = $dataPost['rand'];
1366
                $data       = $dataPost['data'];
1367
 
1368
                $config_username    = $this->config['leaderslinked.moodle.username'];
1369
                $config_password    = $this->config['leaderslinked.moodle.password'];
1370
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1371
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
1372
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
1373
 
1374
 
1375
 
1376
 
1377
                if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1378
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
1379
                    exit;
1380
                }
1381
 
1382
                if ($username != $config_username) {
1383
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
1384
                    exit;
1385
                }
1386
 
1387
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1388
                if (!$dt) {
1389
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
1390
                    exit;
1391
                }
1392
 
1393
                $t0 = $dt->getTimestamp();
1394
                $t1 = strtotime('-5 minutes');
1395
                $t2 = strtotime('+5 minutes');
1396
 
1397
                if ($t0 < $t1 || $t0 > $t2) {
1398
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1399
                    //exit;
1400
                }
1401
 
1402
                if (!password_verify($username . '-' . $config_password . '-' . $rand . '-' . $timestamp, $password)) {
1403
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
1404
                    exit;
1405
                }
1406
 
1407
                if (empty($data)) {
1408
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
1409
                    exit;
1410
                }
1411
 
1412
                $data = base64_decode($data);
1413
                if (empty($data)) {
1414
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
1415
                    exit;
1416
                }
1417
 
1418
 
1419
                try {
1420
                    $rsa = Rsa::getInstance();
1421
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1422
                } catch (\Throwable $e) {
1423
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
1424
                    exit;
1425
                }
1426
 
1427
                $data = (array) json_decode($data);
1428
                if (empty($data)) {
1429
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
1430
                    exit;
1431
                }
1432
 
1433
                $email      = isset($data['email']) ? Functions::sanitizeFilterString($data['email']) : '';
1434
                $first_name = isset($data['first_name']) ? Functions::sanitizeFilterString($data['first_name']) : '';
1435
                $last_name  = isset($data['last_name']) ? Functions::sanitizeFilterString($data['last_name']) : '';
1436
 
1437
                if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
1438
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']);
1439
                    exit;
1440
                }
1441
 
1442
                $userMapper = UserMapper::getInstance($this->adapter);
1443
                $user = $userMapper->fetchOneByEmail($email);
1444
                if (!$user) {
1445
 
1446
 
1447
                    $user = new User();
1448
                    $user->network_id = $currentNetwork->id;
1449
                    $user->blocked = User::BLOCKED_NO;
1450
                    $user->email = $email;
1451
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1452
                    $user->first_name = $first_name;
1453
                    $user->last_name = $last_name;
1454
                    $user->login_attempt = 0;
1455
                    $user->password = '-NO-PASSWORD-';
1456
                    $user->usertype_id = UserType::USER;
1457
                    $user->status = User::STATUS_ACTIVE;
1458
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
1459
 
1460
                    if ($userMapper->insert($user)) {
1461
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]);
1462
                        exit;
1463
                    }
1464
 
1465
 
1466
 
1467
 
1468
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
1469
                    $content    = isset($data['avatar_content']) ? Functions::sanitizeFilterString($data['avatar_content']) : '';
1470
 
1471
                    if ($filename && $content) {
1472
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
1473
                        try {
1474
                            file_put_contents($source, base64_decode($content));
1475
                            if (file_exists($source)) {
1476
                                $target_path = $this->config['leaderslinked.fullpath.user'] . $user->uuid;
1477
                                list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
1478
 
1479
                                $target_filename    = 'user-' . uniqid() . '.png';
1480
                                $crop_to_dimensions = true;
1481
 
1482
                                if (!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
1483
                                    return new JsonModel([
1484
                                        'success'   => false,
1485
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1486
                                    ]);
1487
                                }
1488
 
1489
                                $user->image = $target_filename;
1490
                                $userMapper->updateImage($user);
1491
                            }
1492
                        } catch (\Throwable $e) {
1493
                        } finally {
1494
                            if (file_exists($source)) {
1495
                                unlink($source);
1496
                            }
1497
                        }
1498
                    }
1499
                }
1500
 
1501
                $auth = new AuthEmailAdapter($this->adapter);
1502
                $auth->setData($email);
1503
 
1504
                $result = $auth->authenticate();
1505
                if ($result->getCode() == AuthResult::SUCCESS) {
1506
                    return $this->redirect()->toRoute('dashboard');
1507
                } else {
1508
                    $message = $result->getMessages()[0];
1509
                    if (!in_array($message, [
1510
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1511
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1512
                        'ERROR_ENTERED_PASS_INCORRECT_1'
1513
                    ])) {
1514
                    }
1515
 
1516
                    switch ($message) {
1517
                        case 'ERROR_USER_NOT_FOUND':
1518
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1519
                            break;
1520
 
1521
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
1522
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1523
                            break;
1524
 
1525
                        case 'ERROR_USER_IS_BLOCKED':
1526
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1527
                            break;
1528
 
1529
                        case 'ERROR_USER_IS_INACTIVE':
1530
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1531
                            break;
1532
 
1533
 
1534
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1535
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1536
                            break;
1537
 
1538
 
1539
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
1540
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1541
                            break;
1542
 
1543
 
1544
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
1545
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1546
                            break;
1547
 
1548
 
1549
                        default:
1550
                            $message = 'ERROR_UNKNOWN';
1551
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1552
                            break;
1553
                    }
1554
 
1555
 
1556
 
1557
 
1558
                    return new JsonModel([
1559
                        'success'   => false,
1560
                        'data'   => $message
1561
                    ]);
1562
                }
1563
            } else {
1564
                $messages = [];
1565
 
1566
 
1567
 
1568
                $form_messages = (array) $form->getMessages();
1569
                foreach ($form_messages  as $fieldname => $field_messages) {
1570
 
1571
                    $messages[$fieldname] = array_values($field_messages);
1572
                }
1573
 
1574
                return new JsonModel([
1575
                    'success'   => false,
1576
                    'data'   => $messages
1577
                ]);
1578
            }
1579
        } else {
1580
            $data = [
1581
                'success' => false,
1582
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1583
            ];
1584
 
1585
            return new JsonModel($data);
1586
        }
1587
 
1588
        return new JsonModel($data);
1589
    }
1590
 
1591
    public function csrfAction()
1592
    {
1593
        $request = $this->getRequest();
1594
        if ($request->isGet()) {
1595
 
1596
            $token = md5(uniqid('CSFR-' . mt_rand(), true));
1597
            $_SESSION['token'] = $token;
1598
 
1599
 
1600
            return new JsonModel([
1601
                'success' => true,
1602
                'data' => $token
1603
            ]);
1604
        } else {
1605
            return new JsonModel([
1606
                'success' => false,
1607
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1608
            ]);
1609
        }
1610
    }
1611
 
1612
    public function impersonateAction()
1613
    {
1614
        $request = $this->getRequest();
1615
        if ($request->isGet()) {
1616
            $user_uuid  = Functions::sanitizeFilterString($this->params()->fromQuery('user_uuid'));
1617
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
1618
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
1619
            $password   = Functions::sanitizeFilterString($this->params()->fromQuery('password'));
1620
 
1621
 
1622
            if (!$user_uuid || !$rand || !$timestamp || !$password) {
1623
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
1624
            }
1625
 
1626
 
1627
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1628
            $currentUserPlugin->clearIdentity();
1629
 
1630
 
1631
            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
1632
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);
1633
 
1634
            $authService = new AuthenticationService();
1635
            $result = $authService->authenticate($authAdapter);
1636
 
1637
 
1638
            if ($result->getCode() == AuthResult::SUCCESS) {
1639
                return $this->redirect()->toRoute('dashboard');
1640
            } else {
1641
                throw new \Exception($result->getMessages()[0]);
1642
            }
1643
        }
1644
 
1645
        return new JsonModel([
1646
            'success' => false,
1647
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1648
        ]);
1649
    }
1650
}