Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 4458 | Rev 5751 | 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
 
379
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
380
            $remember   = $email ? true : false;
381
 
382
            $form = new SigninForm($this->config);
383
            $form->setData([
384
                'email'     => $email,
385
                'remember'  => $remember,
386
            ]);
387
            $this->layout()->setTemplate('layout/auth.phtml');
388
            $viewModel = new ViewModel();
389
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
390
            $viewModel->setVariables([
391
                'form'      =>  $form,
392
                'site_key'  => $site_key,
393
                'aes'       => $_SESSION['aes'],
4419 efrain 394
                'defaultNetwork' => $currentNetwork->default,
1 www 395
            ]);
396
 
397
            return $viewModel ;
398
 
399
        } else {
400
            $data = [
401
                'success' => false,
402
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
403
            ];
404
 
405
            return new JsonModel($data);
406
        }
407
 
408
        return new JsonModel($data);
409
 
410
    }
411
 
412
    public function facebookAction()
413
    {
414
        $request = $this->getRequest();
415
        if($request->isGet()) {
416
 
417
            try {
418
                $app_id = $this->config['leaderslinked.facebook.app_id'];
419
                $app_password = $this->config['leaderslinked.facebook.app_password'];
420
                $app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];
421
                //$app_url_auth = $this->config['leaderslinked.facebook.app_url_auth'];
422
                //$redirect_url = $this->config['leaderslinked.facebook.app_redirect_url'];
423
 
424
 
425
 
426
                $fb = new \Facebook\Facebook([
427
                    'app_id' => $app_id,
428
                    'app_secret' => $app_password,
429
                    'default_graph_version' => $app_graph_version,
430
                ]);
431
 
432
                $app_url_auth =  $this->url()->fromRoute('oauth/facebook', [], ['force_canonical' => true]);
433
                $helper = $fb->getRedirectLoginHelper();
434
                $permissions = ['email', 'public_profile']; // Optional permissions
435
                $facebookUrl = $helper->getLoginUrl($app_url_auth, $permissions);
436
 
4458 efrain 437
 
438
 
1 www 439
                return new JsonModel([
4458 efrain 440
                    'success' => false,
1 www 441
                    'data' => $facebookUrl
442
                ]);
443
            } catch (\Throwable $e) {
444
                return new JsonModel([
445
                    'success' => false,
446
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_FACEBOOK'
447
                ]);
448
            }
449
 
450
        } else {
451
            return new JsonModel([
452
                'success' => false,
453
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
454
            ]);
455
        }
456
    }
457
 
458
    public function twitterAction()
459
    {
460
        $request = $this->getRequest();
461
        if($request->isGet()) {
462
 
463
            try {
464
                if($this->config['leaderslinked.runmode.sandbox']) {
465
 
466
                    $twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];
467
                    $twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];
468
 
469
                } else {
470
                    $twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];
471
                    $twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];
472
                }
473
 
474
                /*
475
                 echo '$twitter_api_key = ' . $twitter_api_key . PHP_EOL;
476
                 echo '$twitter_api_secret = ' . $twitter_api_secret . PHP_EOL;
477
                 exit;
478
                 */
479
 
480
                //Twitter
481
                //$redirect_url =  $this->url()->fromRoute('oauth/twitter', [], ['force_canonical' => true]);
482
                $redirect_url = $this->config['leaderslinked.twitter.app_redirect_url'];
483
                $twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret);
484
                $request_token =  $twitter->oauth('oauth/request_token', ['oauth_callback' => $redirect_url ]);
485
                $twitterUrl = $twitter->url('oauth/authorize', [ 'oauth_token' => $request_token['oauth_token'] ]);
486
 
487
                $twitterSession = new \Laminas\Session\Container('twitter');
488
                $twitterSession->oauth_token = $request_token['oauth_token'];
489
                $twitterSession->oauth_token_secret = $request_token['oauth_token_secret'];
490
 
491
                return new JsonModel([
492
                    'success' => true,
493
                    'data' =>  $twitterUrl
494
                ]);
495
            } catch (\Throwable $e) {
496
                return new JsonModel([
497
                    'success' => false,
498
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_TWITTER'
499
                ]);
500
            }
501
 
502
        } else {
503
            return new JsonModel([
504
                'success' => false,
505
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
506
            ]);
507
        }
508
 
509
 
510
    }
511
 
512
    public function googleAction()
513
    {
514
        $request = $this->getRequest();
515
        if($request->isGet()) {
516
 
517
            try {
518
 
519
 
520
                //Google
521
                $google = new \Google_Client();
522
                $google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');
523
                $google->setAccessType("offline");        // offline access
524
 
525
                $google->setIncludeGrantedScopes(true);   // incremental auth
526
 
527
                $google->addScope('profile');
528
                $google->addScope('email');
529
 
530
                // $redirect_url =  $this->url()->fromRoute('oauth/google', [], ['force_canonical' => true]);
531
                $redirect_url = $this->config['leaderslinked.google_auth.app_redirect_url'];
532
 
533
                $google->setRedirectUri($redirect_url);
534
                $googleUrl = $google->createAuthUrl();
535
 
536
                return new JsonModel([
537
                    'success' => true,
538
                    'data' =>  $googleUrl
539
                ]);
540
            } catch (\Throwable $e) {
541
                return new JsonModel([
542
                    'success' => false,
543
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_GOOGLE'
544
                ]);
545
            }
546
 
547
        } else {
548
            return new JsonModel([
549
                'success' => false,
550
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
551
            ]);
552
        }
553
    }
554
 
555
    public function signoutAction()
556
    {
3639 efrain 557
        $currentUserPlugin = $this->plugin('currentUserPlugin');
558
        $currentUser = $currentUserPlugin->getRawUser();
559
        if($currentUserPlugin->hasImpersonate()) {
560
 
561
 
562
            $userMapper = UserMapper::getInstance($this->adapter);
563
            $userMapper->leaveImpersonate($currentUser->id);
564
 
565
            $networkMapper = NetworkMapper::getInstance($this->adapter);
566
            $network = $networkMapper->fetchOne($currentUser->network_id);
567
 
568
 
569
            if(!$currentUser->one_time_password) {
570
                $one_time_password = Functions::generatePassword(25);
571
 
572
                $currentUser->one_time_password = $one_time_password;
573
 
574
                $userMapper = UserMapper::getInstance($this->adapter);
575
                $userMapper->updateOneTimePassword($currentUser, $one_time_password);
576
            }
577
 
578
 
579
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
580
            if($sandbox) {
581
                $salt = $this->config['leaderslinked.backend.sandbox_salt'];
582
            } else {
583
                $salt = $this->config['leaderslinked.backend.production_salt'];
584
            }
585
 
586
 
587
 
588
 
589
            $rand = 1000 + mt_rand(1, 999);
590
            $timestamp = time();
591
            $password = md5($currentUser->one_time_password . '-' . $rand . '-' . $timestamp . '-' . $salt);
592
 
593
            $params = [
594
                'user_uuid' => $currentUser->uuid,
595
                'password' => $password,
596
                'rand' => $rand,
597
                'time' => $timestamp,
598
            ];
599
 
600
            $currentUserPlugin->clearIdentity();
601
            $url = 'https://'. $network->main_hostname . '/signin/impersonate' . '?' . http_build_query($params);
602
            return $this->redirect()->toUrl($url);
603
 
604
 
605
 
606
        } else {
607
 
608
 
609
            if($currentUserPlugin->hasIdentity()) {
610
 
611
                $this->logger->info('Desconexión de LeadersLinked', ['user_id' => $currentUserPlugin->getUserId(), 'ip' => Functions::getUserIP()]);
612
            }
613
 
3671 efrain 614
            $currentUserPlugin->clearIdentity();
615
 
3639 efrain 616
            return $this->redirect()->toRoute('home');
1 www 617
        }
618
    }
619
 
620
 
621
    public function resetPasswordAction()
622
    {
3650 efrain 623
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 624
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
625
 
626
 
1 www 627
        $flashMessenger = $this->plugin('FlashMessenger');
628
        $code = filter_var($this->params()->fromRoute('code', ''), FILTER_SANITIZE_STRING);
629
 
630
        $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 631
        $user = $userMapper->fetchOneByPasswordResetKeyAndNetworkId($code, $currentNetwork->id);
1 www 632
        if(!$user) {
633
            $this->logger->err('Restablecer contraseña - Error código no existe', ['ip' => Functions::getUserIP()]);
634
 
635
            $flashMessenger->addErrorMessage('ERROR_PASSWORD_RECOVER_CODE_IS_INVALID');
636
            return $this->redirect()->toRoute('forgot-password');
637
        }
638
 
3649 efrain 639
 
640
 
1 www 641
        $password_generated_on = strtotime($user->password_generated_on);
642
        $expiry_time = $password_generated_on + $this->config['leaderslinked.security.reset_password_expired'];
643
        if (time() > $expiry_time) {
644
            $this->logger->err('Restablecer contraseña - Error código expirado', ['ip' => Functions::getUserIP()]);
645
 
646
            $flashMessenger->addErrorMessage('ERROR_PASSWORD_RECOVER_CODE_HAS_EXPIRED');
647
            return $this->redirect()->toRoute('forgot-password');
648
        }
649
 
650
        $request = $this->getRequest();
651
        if($request->isPost()) {
652
            $dataPost = $request->getPost()->toArray();
653
            if(empty($_SESSION['aes'])) {
654
                return new JsonModel([
655
                    'success'   => false,
656
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
657
                ]);
658
            }
659
 
660
            if(!empty( $dataPost['password'])) {
661
                $dataPost['password'] = CryptoJsAes::decrypt( $dataPost['password'], $_SESSION['aes']);
662
            }
663
            if(!empty( $dataPost['confirmation'])) {
664
                $dataPost['confirmation'] = CryptoJsAes::decrypt( $dataPost['confirmation'], $_SESSION['aes']);
665
            }
666
 
667
 
668
 
669
            $form = new ResetPasswordForm($this->config);
670
            $form->setData($dataPost);
671
 
672
            if($form->isValid()) {
673
                $data = (array) $form->getData();
674
                $password = $data['password'];
675
 
676
 
677
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
678
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);
679
 
680
                $oldPassword = false;
681
                foreach($userPasswords as $userPassword)
682
                {
683
                    if(password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password))
684
                    {
685
                        $oldPassword = true;
686
                        break;
687
                    }
688
                }
689
 
690
                if($oldPassword) {
691
                    $this->logger->err('Restablecer contraseña - Error contraseña ya utilizada anteriormente', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
692
 
693
                    return new JsonModel([
694
                        'success'   => false,
695
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
696
 
697
                    ]);
698
                } else {
699
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
700
 
701
 
702
                    $result = $userMapper->updatePassword($user, $password_hash);
703
                    if($result) {
704
 
705
                        $userPassword = new UserPassword();
706
                        $userPassword->user_id = $user->id;
707
                        $userPassword->password = $password_hash;
708
                        $userPasswordMapper->insert($userPassword);
709
 
710
 
711
                        $this->logger->info('Restablecer contraseña realizado', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
712
 
713
 
714
                        $flashMessenger->addSuccessMessage('LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED');
715
 
716
                        return new JsonModel([
717
                            'success'   => true,
718
                            'data'      => $this->url()->fromRoute('home')
719
 
720
                        ]);
721
                    } else {
722
                        $this->logger->err('Restablecer contraseña - Error desconocido', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
723
 
724
                        return new JsonModel([
725
                            'success'   => true,
726
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
727
 
728
                        ]);
729
                    }
730
                }
731
 
732
            } else {
733
                $form_messages =  $form->getMessages('captcha');
734
                if(!empty($form_messages)) {
735
                    return new JsonModel([
736
                        'success'   => false,
737
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
738
                    ]);
739
                }
740
 
741
                $messages = [];
742
 
743
                $form_messages = (array) $form->getMessages();
744
                foreach($form_messages  as $fieldname => $field_messages)
745
                {
746
                    $messages[$fieldname] = array_values($field_messages);
747
                }
748
 
749
                return new JsonModel([
750
                    'success'   => false,
751
                    'data'   => $messages
752
                ]);
753
            }
754
 
755
        }
756
 
757
        if($request->isGet()) {
758
 
759
            if(empty($_SESSION['aes'])) {
760
                $_SESSION['aes'] = Functions::generatePassword(16);
761
            }
762
 
763
            if($this->config['leaderslinked.runmode.sandbox']) {
764
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
765
            } else {
766
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
767
            }
768
 
769
 
770
            $form = new ResetPasswordForm($this->config);
771
 
772
            $this->layout()->setTemplate('layout/auth.phtml');
773
            $viewModel = new ViewModel();
774
            $viewModel->setTemplate('leaders-linked/auth/reset-password.phtml');
775
            $viewModel->setVariables([
776
                'code' => $code,
777
                'form' => $form,
778
                'site_key' => $site_key,
779
                'aes'       => $_SESSION['aes'],
4422 efrain 780
                'defaultNetwork' => $currentNetwork->default,
1 www 781
            ]);
782
 
783
            return $viewModel;
784
        }
785
 
786
 
787
 
788
        return new JsonModel([
789
            'success' => false,
790
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
791
        ]);
792
    }
793
 
794
    public function forgotPasswordAction()
795
    {
3650 efrain 796
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 797
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
798
 
799
 
800
 
1 www 801
        $request = $this->getRequest();
802
        if($request->isPost()) {
803
            $dataPost = $request->getPost()->toArray();
804
            if(empty($_SESSION['aes'])) {
805
                return new JsonModel([
806
                    'success'   => false,
807
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
808
                ]);
809
            }
810
 
811
            if(!empty( $dataPost['email'])) {
812
                $dataPost['email'] = CryptoJsAes::decrypt( $dataPost['email'], $_SESSION['aes']);
813
            }
814
 
815
            $form = new ForgotPasswordForm($this->config);
816
            $form->setData($dataPost);
817
 
818
            if($form->isValid()) {
819
                $dataPost = (array) $form->getData();
820
                $email      = $dataPost['email'];
821
 
822
                $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 823
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1 www 824
                if(!$user) {
825
                    $this->logger->err('Olvidó contraseña ' . $email . '- Email no existe ', ['ip' => Functions::getUserIP()]);
826
 
827
                    return new JsonModel([
828
                        'success' => false,
829
                        'data' =>  'ERROR_EMAIL_IS_NOT_REGISTERED'
830
                    ]);
831
                } else {
832
                    if($user->status == User::STATUS_INACTIVE) {
833
                        return new JsonModel([
834
                            'success' => false,
835
                            'data' =>  'ERROR_USER_IS_INACTIVE'
836
                        ]);
837
                    } else if ($user->email_verified == User::EMAIL_VERIFIED_NO) {
838
                        $this->logger->err('Olvidó contraseña - Email no verificado ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
839
 
840
                        return new JsonModel([
841
                            'success' => false,
842
                            'data' => 'ERROR_EMAIL_HAS_NOT_BEEN_VERIFIED'
843
                        ]);
844
                    } else {
845
                        $password_reset_key = md5($user->email. time());
846
                        $userMapper->updatePasswordResetKey((int) $user->id, $password_reset_key);
847
 
848
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3649 efrain 849
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RESET_PASSWORD, $currentNetwork->id);
1 www 850
                        if($emailTemplate) {
851
                            $arrayCont = [
852
                                'firstname'             => $user->first_name,
853
                                'lastname'              => $user->last_name,
854
                                'other_user_firstname'  => '',
855
                                'other_user_lastname'   => '',
856
                                'company_name'          => '',
857
                                'group_name'            => '',
858
                                'content'               => '',
859
                                'code'                  => '',
860
                                'link'                  => $this->url()->fromRoute('reset-password', ['code' => $password_reset_key], ['force_canonical' => true])
861
                            ];
862
 
863
                            $email = new QueueEmail($this->adapter);
864
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
865
                        }
866
                        $flashMessenger = $this->plugin('FlashMessenger');
867
                        $flashMessenger->addSuccessMessage('LABEL_RECOVERY_LINK_WAS_SENT_TO_YOUR_EMAIL');
868
 
869
                        $this->logger->info('Olvidó contraseña - Se envio link de recuperación ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
870
 
871
                        return new JsonModel([
872
                            'success' => true,
873
                        ]);
874
                    }
875
                }
876
 
877
            } else {
878
 
879
 
880
                $form_messages =  $form->getMessages('captcha');
881
 
882
 
883
 
884
                if(!empty($form_messages)) {
885
                    return new JsonModel([
886
                        'success'   => false,
887
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
888
                    ]);
889
                }
890
 
891
                $messages = [];
892
                $form_messages = (array) $form->getMessages();
893
                foreach($form_messages  as $fieldname => $field_messages)
894
                {
895
                    $messages[$fieldname] = array_values($field_messages);
896
                }
897
 
898
                return new JsonModel([
899
                    'success'   => false,
900
                    'data'      => $messages
901
                ]);
902
            }
903
        }
904
 
905
        /*
906
        if($request->isGet())  {
907
            if(empty($_SESSION['aes'])) {
908
                $_SESSION['aes'] = Functions::generatePassword(16);
909
            }
910
 
911
            if($this->config['leaderslinked.runmode.sandbox']) {
912
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
913
            } else {
914
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
915
            }
916
 
917
 
918
            $form = new ForgotPasswordForm($this->config);
919
 
920
            $this->layout()->setTemplate('layout/auth.phtml');
921
            $viewModel = new ViewModel();
922
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
923
            $viewModel->setVariables([
924
                'form' => $form,
925
                'site_key' => $site_key,
926
                'aes' => $_SESSION['aes'],
927
            ]);
928
 
929
            return $viewModel ;
930
        }
931
        */
932
 
933
        if($request->isGet())  {
934
 
935
            if(empty($_SESSION['aes'])) {
936
                $_SESSION['aes'] = Functions::generatePassword(16);
937
            }
938
 
939
            if($this->config['leaderslinked.runmode.sandbox']) {
940
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
941
            } else {
942
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
943
            }
944
 
945
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
946
            $remember   = $email ? true : false;
947
 
948
            $form = new SigninForm($this->config);
949
            $form->setData([
950
                'email'     => $email,
951
                'remember'  => $remember,
952
            ]);
953
            $this->layout()->setTemplate('layout/auth.phtml');
954
            $viewModel = new ViewModel();
955
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
956
            $viewModel->setVariables([
957
                'form'      =>  $form,
958
                'site_key'  => $site_key,
959
                'aes'       => $_SESSION['aes'],
4422 efrain 960
                'defaultNetwork' => $currentNetwork->default,
1 www 961
            ]);
962
 
963
            return $viewModel ;
964
 
965
        }
966
 
967
        return new JsonModel([
968
            'success' => false,
969
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
970
        ]);
971
    }
972
 
973
    public function signupAction()
974
    {
3650 efrain 975
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 976
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
977
 
978
 
1 www 979
        $request = $this->getRequest();
980
        if($request->isPost()) {
981
            $dataPost = $request->getPost()->toArray();
982
 
983
            if(empty($_SESSION['aes'])) {
984
                return new JsonModel([
985
                    'success'   => false,
986
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
987
                ]);
988
            }
989
 
990
            if(!empty( $dataPost['email'])) {
991
                $dataPost['email'] = CryptoJsAes::decrypt( $dataPost['email'], $_SESSION['aes']);
992
            }
993
 
994
            if(!empty( $dataPost['password'])) {
995
                $dataPost['password'] = CryptoJsAes::decrypt( $dataPost['password'], $_SESSION['aes']);
996
            }
997
 
998
            if(!empty( $dataPost['confirmation'])) {
999
                $dataPost['confirmation'] = CryptoJsAes::decrypt( $dataPost['confirmation'], $_SESSION['aes']);
1000
            }
1001
 
4398 efrain 1002
            if(empty($dataPost['is_adult'])) {
1003
                $dataPost['is_adult'] = User::IS_ADULT_NO;
1004
            } else {
1005
                $dataPost['is_adult'] = $dataPost['is_adult'] == User::IS_ADULT_YES ? User::IS_ADULT_YES : User::IS_ADULT_NO;
1006
            }
1 www 1007
 
4398 efrain 1008
 
1009
 
1 www 1010
            $form = new SignupForm($this->config);
1011
            $form->setData($dataPost);
1012
 
1013
            if($form->isValid()) {
1014
                $dataPost = (array) $form->getData();
1015
 
1016
                $email = $dataPost['email'];
1017
 
1018
                $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 1019
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1 www 1020
                if($user) {
1021
                    $this->logger->err('Registro ' . $email . '- Email ya  existe ', ['ip' => Functions::getUserIP()]);
1022
 
1023
 
1024
 
1025
                    return new JsonModel([
1026
                        'success' => false,
1027
                        'data' => 'ERROR_EMAIL_IS_REGISTERED'
1028
                    ]);
1029
                } else {
3298 efrain 1030
 
3364 efrain 1031
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
1032
 
3298 efrain 1033
 
3364 efrain 1034
                    if($user_share_invitation) {
1035
                        $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
3298 efrain 1036
                        if($userRedirect && $userRedirect->status == User::STATUS_ACTIVE) {
1037
                            $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1038
 
1039
                            $user = new User();
3649 efrain 1040
                            $user->network_id           = $currentNetwork->id;
3298 efrain 1041
                            $user->email                = $dataPost['email'];
1042
                            $user->first_name           = $dataPost['first_name'];
1043
                            $user->last_name            = $dataPost['last_name'];
1044
                            $user->usertype_id          = UserType::USER;
1045
                            $user->password             = $password_hash;
1046
                            $user->password_updated_on  = date('Y-m-d H:i:s');
1047
                            $user->status               = User::STATUS_ACTIVE;
1048
                            $user->blocked              = User::BLOCKED_NO;
1049
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
1050
                            $user->login_attempt        = 0;
4398 efrain 1051
                            $user->is_adult             = $dataPost['is_adult'];
4776 efrain 1052
                            $user->request_access       = User::REQUEST_ACCESS_APPROVED;
3298 efrain 1053
 
4776 efrain 1054
 
3298 efrain 1055
 
4776 efrain 1056
 
1057
 
3298 efrain 1058
                            if($userMapper->insert($user)) {
1059
 
1060
                                $userPassword = new UserPassword();
1061
                                $userPassword->user_id = $user->id;
1062
                                $userPassword->password = $password_hash;
1063
 
1064
                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1065
                                $userPasswordMapper->insert($userPassword);
1066
 
1067
 
1068
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1069
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1070
 
1071
                                if($connection) {
1072
 
1073
                                    if($connection->status != Connection::STATUS_ACCEPTED) {
1074
                                        $connectionMapper->approve($connection);
1075
                                    }
1076
 
1077
                                } else {
1078
                                    $connection = new Connection();
1079
                                    $connection->request_from = $user->id;
1080
                                    $connection->request_to = $userRedirect->id;
1081
                                    $connection->status = Connection::STATUS_ACCEPTED;
1082
 
1083
                                    $connectionMapper->insert($connection);
1084
                                }
1085
 
1086
 
3364 efrain 1087
                                $this->cache->removeItem('user_share_invitation');
1088
 
3298 efrain 1089
 
1090
 
3364 efrain 1091
                                $data = [
1092
                                    'success'   => true,
1093
                                    'data'      => $this->url()->fromRoute('home'),
1094
                                ];
1095
 
3298 efrain 1096
 
1097
                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1098
 
1099
                                return new JsonModel($data);
1100
                            }
1101
                        }
1102
                    }
1103
 
1104
 
1105
 
1106
 
1 www 1107
                    $timestamp = time();
1108
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);
1109
 
1110
                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1111
 
1112
                    $user = new User();
3649 efrain 1113
                    $user->network_id           = $currentNetwork->id;
1 www 1114
                    $user->email                = $dataPost['email'];
1115
                    $user->first_name           = $dataPost['first_name'];
1116
                    $user->last_name            = $dataPost['last_name'];
1117
                    $user->usertype_id          = UserType::USER;
1118
                    $user->password             = $password_hash;
1119
                    $user->password_updated_on  = date('Y-m-d H:i:s');
1120
                    $user->activation_key       = $activation_key;
1121
                    $user->status               = User::STATUS_INACTIVE;
1122
                    $user->blocked              = User::BLOCKED_NO;
1123
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
1124
                    $user->login_attempt        = 0;
4776 efrain 1125
 
1126
                    if($currentNetwork->default == Network::DEFAULT_YES) {
1127
                        $user->request_access = User::REQUEST_ACCESS_APPROVED;
1128
                    } else {
1129
                        $user->request_access = User::REQUEST_ACCESS_PENDING;
1130
                    }
1131
 
3671 efrain 1132
 
1 www 1133
 
1134
                    if($userMapper->insert($user)) {
1135
 
1136
                        $userPassword = new UserPassword();
1137
                        $userPassword->user_id = $user->id;
1138
                        $userPassword->password = $password_hash;
1139
 
1140
                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1141
                        $userPasswordMapper->insert($userPassword);
1142
 
1143
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3649 efrain 1144
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
1 www 1145
                        if($emailTemplate) {
1146
                            $arrayCont = [
1147
                                'firstname'             => $user->first_name,
1148
                                'lastname'              => $user->last_name,
1149
                                'other_user_firstname'  => '',
1150
                                'other_user_lastname'   => '',
1151
                                'company_name'          => '',
1152
                                'group_name'            => '',
1153
                                'content'               => '',
1154
                                'code'                  => '',
3298 efrain 1155
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
1 www 1156
                            ];
1157
 
1158
                            $email = new QueueEmail($this->adapter);
1159
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1160
                        }
1161
                        $flashMessenger = $this->plugin('FlashMessenger');
1162
                        $flashMessenger->addSuccessMessage('LABEL_REGISTRATION_DONE');
1163
 
1164
                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1165
 
1166
                        return new JsonModel([
1167
                            'success' => true,
1168
                        ]);
1169
 
1170
                    } else {
1171
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);
1172
 
1173
                        return new JsonModel([
1174
                            'success' => false,
1175
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1176
                        ]);
1177
                    }
1178
                }
1179
 
1180
 
1181
 
1182
            } else {
1183
 
1184
                $form_messages =  $form->getMessages('captcha');
1185
                if(!empty($form_messages)) {
1186
                    return new JsonModel([
1187
                        'success'   => false,
1188
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1189
                    ]);
1190
                }
1191
 
1192
                $messages = [];
1193
 
1194
                $form_messages = (array) $form->getMessages();
1195
                foreach($form_messages  as $fieldname => $field_messages)
1196
                {
1197
                    $messages[$fieldname] = array_values($field_messages);
1198
                }
1199
 
1200
                return new JsonModel([
1201
                    'success'   => false,
1202
                    'data'   => $messages
1203
                ]);
1204
            }
1205
        }
1206
        /*
1207
        if($request->isGet())  {
1208
            if(empty($_SESSION['aes'])) {
1209
                $_SESSION['aes'] = Functions::generatePassword(16);
1210
            }
1211
 
1212
            if($this->config['leaderslinked.runmode.sandbox']) {
1213
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1214
            } else {
1215
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1216
            }
1217
 
1218
 
1219
            $form = new SignupForm($this->config);
1220
 
1221
            $this->layout()->setTemplate('layout/auth.phtml');
1222
            $viewModel = new ViewModel();
1223
            $viewModel->setTemplate('leaders-linked/auth/signup.phtml');
1224
            $viewModel->setVariables([
1225
                'form' => $form,
1226
                'site_key' => $site_key,
1227
                'aes' =>  $_SESSION['aes'],
1228
            ]);
1229
 
1230
            return $viewModel ;
1231
        } */
1232
 
1233
 
1234
        if($request->isGet())  {
1235
 
1236
            if(empty($_SESSION['aes'])) {
1237
                $_SESSION['aes'] = Functions::generatePassword(16);
1238
            }
1239
 
1240
            if($this->config['leaderslinked.runmode.sandbox']) {
1241
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1242
            } else {
1243
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1244
            }
1245
 
1246
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
1247
            $remember   = $email ? true : false;
1248
 
1249
            $form = new SigninForm($this->config);
1250
            $form->setData([
1251
                'email'     => $email,
1252
                'remember'  => $remember,
1253
            ]);
1254
            $this->layout()->setTemplate('layout/auth.phtml');
1255
            $viewModel = new ViewModel();
1256
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
1257
            $viewModel->setVariables([
1258
                'form'      =>  $form,
1259
                'site_key'  => $site_key,
1260
                'aes'       => $_SESSION['aes'],
4419 efrain 1261
                'defaultNetwork' => $currentNetwork->default,
1 www 1262
            ]);
1263
 
1264
            return $viewModel ;
1265
 
1266
        }
1267
 
1268
        return new JsonModel([
1269
            'success' => false,
1270
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1271
        ]);
1272
 
1273
 
1274
    }
1275
 
1276
    public function activateAccountAction()
1277
    {
1278
 
3650 efrain 1279
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 1280
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1281
 
1282
 
1283
 
1 www 1284
        $request = $this->getRequest();
1285
        if($request->isGet()) {
1286
            $code   = filter_var($this->params()->fromRoute('code'), FILTER_SANITIZE_STRING);
1287
            $userMapper = UserMapper::getInstance($this->adapter);
3759 efrain 1288
            $user = $userMapper->fetchOneByActivationKeyAndNetworkId($code, $currentNetwork->id);
1 www 1289
 
1290
            $flashMessenger = $this->plugin('FlashMessenger');
1291
 
1292
            if($user) {
1293
                if(User::EMAIL_VERIFIED_YES == $user->email_verified) {
3671 efrain 1294
 
1 www 1295
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1296
 
1297
                    $flashMessenger->addErrorMessage('ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED');
1298
                } else {
3671 efrain 1299
 
1 www 1300
                    if($userMapper->activateAccount((int) $user->id)) {
3728 efrain 1301
 
1 www 1302
                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1303
 
4776 efrain 1304
 
3298 efrain 1305
 
3364 efrain 1306
                        $user_share_invitation = $this->cache->getItem('user_share_invitation');
3298 efrain 1307
 
3364 efrain 1308
                        if($user_share_invitation) {
1309
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
3298 efrain 1310
                            if($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
1311
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1312
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1313
 
1314
                                if($connection) {
1315
 
1316
                                    if($connection->status != Connection::STATUS_ACCEPTED) {
1317
                                        $connectionMapper->approve($connection);
1318
                                    }
1319
 
1320
                                } else {
1321
                                    $connection = new Connection();
1322
                                    $connection->request_from = $user->id;
1323
                                    $connection->request_to = $userRedirect->id;
1324
                                    $connection->status = Connection::STATUS_ACCEPTED;
1325
 
1326
                                    $connectionMapper->insert($connection);
1327
                                }
1328
                            }
1329
                        }
1330
 
3364 efrain 1331
 
3298 efrain 1332
 
3364 efrain 1333
                        $this->cache->removeItem('user_share_invitation');
4776 efrain 1334
 
1335
 
1336
                        if($currentNetwork->default == Network::DEFAULT_YES) {
1337
                            $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED');
1338
                        } else {
1339
 
1340
                            $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1341
                            $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_REQUEST_ACCESS_PENDING, $currentNetwork->id);
1342
 
1343
                            if($emailTemplate) {
1344
                                $arrayCont = [
1345
                                    'firstname'             => $user->first_name,
1346
                                    'lastname'              => $user->last_name,
1347
                                    'other_user_firstname'  => '',
1348
                                    'other_user_lastname'   => '',
1349
                                    'company_name'          => '',
1350
                                    'group_name'            => '',
1351
                                    'content'               => '',
1352
                                    'code'                  => '',
1353
                                    'link'                  => '',
1354
                                ];
1355
 
1356
                                $email = new QueueEmail($this->adapter);
1357
                                $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1358
                            }
1359
 
1360
 
1361
                            $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED_WE_ARE_VERIFYING_YOUR_INFORMATION');
1362
                        }
3729 efrain 1363
 
3298 efrain 1364
 
1 www 1365
                    } else {
1366
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1367
 
1368
                        $flashMessenger->addErrorMessage('ERROR_THERE_WAS_AN_ERROR');
1369
                    }
1370
                }
1371
            } else {
1372
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);
1373
 
1374
                $flashMessenger->addErrorMessage('ERROR_ACTIVATION_CODE_IS_NOT_VALID');
1375
            }
1376
 
3729 efrain 1377
            return $this->redirect()->toRoute('home');
1378
 
1 www 1379
 
3298 efrain 1380
 
1 www 1381
        } else {
1382
            $response = [
1383
                'success' => false,
1384
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1385
            ];
1386
        }
1387
 
1388
        return new JsonModel($response);
1389
 
1390
    }
1391
 
1392
 
1393
 
1394
    public function onroomAction()
1395
    {
3650 efrain 1396
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 1397
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1398
 
1399
 
1400
 
1 www 1401
        $request = $this->getRequest();
1402
 
1403
        if($request->isPost()) {
1404
 
1405
            $dataPost = $request->getPost()->toArray();
1406
 
1407
 
1408
            $form = new  MoodleForm();
1409
            $form->setData($dataPost);
1410
            if($form->isValid()) {
1411
 
1412
                $dataPost   = (array) $form->getData();
1413
                $username   = $dataPost['username'];
1414
                $password   = $dataPost['password'];
1415
                $timestamp  = $dataPost['timestamp'];
1416
                $rand       = $dataPost['rand'];
1417
                $data       = $dataPost['data'];
1418
 
1419
                $config_username    = $this->config['leaderslinked.moodle.username'];
1420
                $config_password    = $this->config['leaderslinked.moodle.password'];
1421
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1422
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
1423
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
1424
 
1425
 
1426
 
1427
 
1428
                if(empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1429
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']) ;
1430
                    exit;
1431
                }
1432
 
1433
                if($username != $config_username) {
1434
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']) ;
1435
                    exit;
1436
                }
1437
 
1438
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1439
                if(!$dt) {
1440
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']) ;
1441
                    exit;
1442
                }
1443
 
1444
                $t0 = $dt->getTimestamp();
1445
                $t1 = strtotime('-5 minutes');
1446
                $t2 = strtotime('+5 minutes');
1447
 
1448
                if($t0 < $t1 || $t0 > $t2) {
1449
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1450
                    //exit;
1451
                }
1452
 
1453
                if(!password_verify( $username.'-'. $config_password . '-' . $rand. '-' . $timestamp, $password)) {
1454
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']) ;
1455
                    exit;
1456
                }
1457
 
1458
                if(empty($data)) {
1459
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']) ;
1460
                    exit;
1461
                }
1462
 
1463
                $data = base64_decode($data);
1464
                if(empty($data)) {
1465
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']) ;
1466
                    exit;
1467
                }
1468
 
1469
 
1470
                try {
1471
                    $rsa = Rsa::getInstance();
1472
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1473
                } catch (\Throwable $e)
1474
                {
1475
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']) ;
1476
                    exit;
1477
                }
1478
 
1479
                $data = (array) json_decode($data);
1480
                if(empty($data)) {
1481
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']) ;
1482
                    exit;
1483
                }
1484
 
1485
                $email      = trim(isset($data['email']) ? filter_var($data['email'], FILTER_SANITIZE_EMAIL) : '');
1486
                $first_name = trim(isset($data['first_name']) ? filter_var($data['first_name'], FILTER_SANITIZE_STRING) : '');
1487
                $last_name  = trim(isset($data['last_name']) ? filter_var($data['last_name'], FILTER_SANITIZE_STRING) : '');
1488
 
1489
                if(!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
1490
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']) ;
1491
                    exit;
1492
                }
1493
 
1494
                $userMapper = UserMapper::getInstance($this->adapter);
1495
                $user = $userMapper->fetchOneByEmail($email);
1496
                if(!$user) {
1497
 
1498
 
1499
                    $user = new User();
3649 efrain 1500
                    $user->network_id = $currentNetwork->id;
1 www 1501
                    $user->blocked = User::BLOCKED_NO;
1502
                    $user->email = $email;
1503
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1504
                    $user->first_name = $first_name;
1505
                    $user->last_name = $last_name;
1506
                    $user->login_attempt = 0;
1507
                    $user->password = '-NO-PASSWORD-';
1508
                    $user->usertype_id = UserType::USER;
1509
                    $user->status = User::STATUS_ACTIVE;
1510
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
1511
 
1512
                    if($userMapper->insert($user)) {
1513
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]) ;
1514
                        exit;
1515
                    }
1516
 
1517
 
1518
 
1519
 
1520
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
1521
                    $content    = trim(isset($data['avatar_content']) ? filter_var($data['avatar_content'], FILTER_SANITIZE_STRING) : '');
1522
 
1523
                    if($filename && $content) {
1524
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
1525
                        try {
1526
                            file_put_contents($source, base64_decode($content));
1527
                            if (file_exists($source)) {
1528
                                $target_path = $this->config['leaderslinked.fullpath.user'] . $user->uuid;
1529
                                list( $target_width, $target_height ) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
1530
 
1531
                                $target_filename    = 'user-' . uniqid() . '.png';
1532
                                $crop_to_dimensions = true;
1533
 
1534
                                if(!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
1535
                                    return new JsonModel([
1536
                                        'success'   => false,
1537
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1538
                                    ]);
1539
                                }
1540
 
1541
                                $user->image = $target_filename;
1542
                                $userMapper->updateImage($user);
1543
                            }
1544
                        } catch(\Throwable $e) {
1545
 
1546
                        } finally {
1547
                            if(file_exists($source)) {
1548
                                unlink($source);
1549
                            }
1550
                        }
1551
                    }
1552
 
1553
                }
1554
 
1555
                $auth = new AuthEmailAdapter($this->adapter);
1556
                $auth->setData($email);
1557
 
1558
                $result = $auth->authenticate();
1559
                if($result->getCode() == AuthResult::SUCCESS) {
1560
                    return $this->redirect()->toRoute('dashboard');
1561
 
1562
 
1563
                } else {
1564
                    $message = $result->getMessages()[0];
1565
                    if(!in_array($message, ['ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1566
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1567
                        'ERROR_ENTERED_PASS_INCORRECT_1'])) {
1568
 
1569
 
1570
                    }
1571
 
1572
                    switch($message)
1573
                    {
1574
                        case 'ERROR_USER_NOT_FOUND' :
1575
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1576
                            break;
1577
 
1578
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED' :
1579
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1580
                            break;
1581
 
1582
                        case 'ERROR_USER_IS_BLOCKED' :
1583
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1584
                            break;
1585
 
1586
                        case 'ERROR_USER_IS_INACTIVE' :
1587
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1588
                            break;
1589
 
1590
 
1591
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1592
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1593
                            break;
1594
 
1595
 
1596
                        case 'ERROR_ENTERED_PASS_INCORRECT_2' :
1597
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1598
                            break;
1599
 
1600
 
1601
                        case 'ERROR_ENTERED_PASS_INCORRECT_1' :
1602
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1603
                            break;
1604
 
1605
 
1606
                        default :
1607
                            $message = 'ERROR_UNKNOWN';
1608
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1609
                            break;
1610
 
1611
 
1612
                    }
1613
 
1614
 
1615
 
1616
 
1617
                    return new JsonModel( [
1618
                        'success'   => false,
1619
                        'data'   => $message
1620
                    ]);
1621
                }
1622
 
1623
 
1624
 
1625
 
1626
            } else {
1627
                $messages = [];
1628
 
1629
 
1630
 
1631
                $form_messages = (array) $form->getMessages();
1632
                foreach($form_messages  as $fieldname => $field_messages)
1633
                {
1634
 
1635
                    $messages[$fieldname] = array_values($field_messages);
1636
                }
1637
 
1638
                return new JsonModel([
1639
                    'success'   => false,
1640
                    'data'   => $messages
1641
                ]);
1642
            }
1643
 
1644
        } else {
1645
            $data = [
1646
                'success' => false,
1647
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1648
            ];
1649
 
1650
            return new JsonModel($data);
1651
        }
1652
 
1653
        return new JsonModel($data);
1654
    }
1655
 
210 efrain 1656
    public function csrfAction()
1657
    {
1658
        $request = $this->getRequest();
1659
        if($request->isGet()) {
1660
 
1661
            $token = md5(uniqid('CSFR-' . mt_rand(), true));
1662
            $_SESSION['token'] = $token;
1663
 
1664
 
1665
            return new JsonModel([
1666
                'success' => true,
1667
                'data' => $token
1668
            ]);
1669
 
1670
 
1671
        } else {
1672
            return new JsonModel([
1673
                'success' => false,
1674
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1675
            ]);
1676
        }
1677
 
1678
 
1679
    }
3639 efrain 1680
 
1681
    public function impersonateAction()
1682
    {
1683
        $request = $this->getRequest();
1684
        if($request->isGet()) {
1685
            $user_uuid  = filter_var($this->params()->fromQuery('user_uuid'), FILTER_SANITIZE_STRING);
1686
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
1687
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
1688
            $password   = filter_var($this->params()->fromQuery('password'), FILTER_SANITIZE_STRING);
1689
 
1690
 
1691
            if(!$user_uuid || !$rand || !$timestamp || !$password ) {
1692
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
1693
            }
1694
 
1695
 
3650 efrain 1696
            $currentUserPlugin = $this->plugin('currentUserPlugin');
3639 efrain 1697
            $currentUserPlugin->clearIdentity();
1698
 
1699
 
1700
            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
1701
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);
1702
 
1703
            $authService = new AuthenticationService();
1704
            $result = $authService->authenticate($authAdapter);
1705
 
1706
 
1707
            if($result->getCode() == AuthResult::SUCCESS) {
1708
                return $this->redirect()->toRoute('dashboard');
1709
            } else {
1710
                throw new \Exception($result->getMessages()[0]);
1711
            }
1712
        }
1713
 
1714
        return new JsonModel([
1715
            'success' => false,
1716
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1717
        ]);
1718
    }
1 www 1719
 
1720
}