Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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