Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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