Proyectos de Subversion LeadersLinked - Services

Rev

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