Proyectos de Subversion LeadersLinked - Services

Rev

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