Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

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