Proyectos de Subversion LeadersLinked - Services

Rev

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