Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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