Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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