Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 3728 | Rev 3759 | 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
 
3671 efrain 596
            $currentUserPlugin->clearIdentity();
597
 
3639 efrain 598
            return $this->redirect()->toRoute('home');
1 www 599
        }
600
    }
601
 
602
 
603
    public function resetPasswordAction()
604
    {
3650 efrain 605
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 606
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
607
 
608
 
1 www 609
        $flashMessenger = $this->plugin('FlashMessenger');
610
        $code = filter_var($this->params()->fromRoute('code', ''), FILTER_SANITIZE_STRING);
611
 
612
        $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 613
        $user = $userMapper->fetchOneByPasswordResetKeyAndNetworkId($code, $currentNetwork->id);
1 www 614
        if(!$user) {
615
            $this->logger->err('Restablecer contraseña - Error código no existe', ['ip' => Functions::getUserIP()]);
616
 
617
            $flashMessenger->addErrorMessage('ERROR_PASSWORD_RECOVER_CODE_IS_INVALID');
618
            return $this->redirect()->toRoute('forgot-password');
619
        }
620
 
3649 efrain 621
 
622
 
1 www 623
        $password_generated_on = strtotime($user->password_generated_on);
624
        $expiry_time = $password_generated_on + $this->config['leaderslinked.security.reset_password_expired'];
625
        if (time() > $expiry_time) {
626
            $this->logger->err('Restablecer contraseña - Error código expirado', ['ip' => Functions::getUserIP()]);
627
 
628
            $flashMessenger->addErrorMessage('ERROR_PASSWORD_RECOVER_CODE_HAS_EXPIRED');
629
            return $this->redirect()->toRoute('forgot-password');
630
        }
631
 
632
        $request = $this->getRequest();
633
        if($request->isPost()) {
634
            $dataPost = $request->getPost()->toArray();
635
            if(empty($_SESSION['aes'])) {
636
                return new JsonModel([
637
                    'success'   => false,
638
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
639
                ]);
640
            }
641
 
642
            if(!empty( $dataPost['password'])) {
643
                $dataPost['password'] = CryptoJsAes::decrypt( $dataPost['password'], $_SESSION['aes']);
644
            }
645
            if(!empty( $dataPost['confirmation'])) {
646
                $dataPost['confirmation'] = CryptoJsAes::decrypt( $dataPost['confirmation'], $_SESSION['aes']);
647
            }
648
 
649
 
650
 
651
            $form = new ResetPasswordForm($this->config);
652
            $form->setData($dataPost);
653
 
654
            if($form->isValid()) {
655
                $data = (array) $form->getData();
656
                $password = $data['password'];
657
 
658
 
659
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
660
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);
661
 
662
                $oldPassword = false;
663
                foreach($userPasswords as $userPassword)
664
                {
665
                    if(password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password))
666
                    {
667
                        $oldPassword = true;
668
                        break;
669
                    }
670
                }
671
 
672
                if($oldPassword) {
673
                    $this->logger->err('Restablecer contraseña - Error contraseña ya utilizada anteriormente', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
674
 
675
                    return new JsonModel([
676
                        'success'   => false,
677
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
678
 
679
                    ]);
680
                } else {
681
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
682
 
683
 
684
                    $result = $userMapper->updatePassword($user, $password_hash);
685
                    if($result) {
686
 
687
                        $userPassword = new UserPassword();
688
                        $userPassword->user_id = $user->id;
689
                        $userPassword->password = $password_hash;
690
                        $userPasswordMapper->insert($userPassword);
691
 
692
 
693
                        $this->logger->info('Restablecer contraseña realizado', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
694
 
695
 
696
                        $flashMessenger->addSuccessMessage('LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED');
697
 
698
                        return new JsonModel([
699
                            'success'   => true,
700
                            'data'      => $this->url()->fromRoute('home')
701
 
702
                        ]);
703
                    } else {
704
                        $this->logger->err('Restablecer contraseña - Error desconocido', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
705
 
706
                        return new JsonModel([
707
                            'success'   => true,
708
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
709
 
710
                        ]);
711
                    }
712
                }
713
 
714
            } else {
715
                $form_messages =  $form->getMessages('captcha');
716
                if(!empty($form_messages)) {
717
                    return new JsonModel([
718
                        'success'   => false,
719
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
720
                    ]);
721
                }
722
 
723
                $messages = [];
724
 
725
                $form_messages = (array) $form->getMessages();
726
                foreach($form_messages  as $fieldname => $field_messages)
727
                {
728
                    $messages[$fieldname] = array_values($field_messages);
729
                }
730
 
731
                return new JsonModel([
732
                    'success'   => false,
733
                    'data'   => $messages
734
                ]);
735
            }
736
 
737
        }
738
 
739
        if($request->isGet()) {
740
 
741
            if(empty($_SESSION['aes'])) {
742
                $_SESSION['aes'] = Functions::generatePassword(16);
743
            }
744
 
745
            if($this->config['leaderslinked.runmode.sandbox']) {
746
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
747
            } else {
748
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
749
            }
750
 
751
 
752
            $form = new ResetPasswordForm($this->config);
753
 
754
            $this->layout()->setTemplate('layout/auth.phtml');
755
            $viewModel = new ViewModel();
756
            $viewModel->setTemplate('leaders-linked/auth/reset-password.phtml');
757
            $viewModel->setVariables([
758
                'code' => $code,
759
                'form' => $form,
760
                'site_key' => $site_key,
761
                'aes'       => $_SESSION['aes'],
762
            ]);
763
 
764
            return $viewModel;
765
        }
766
 
767
 
768
 
769
        return new JsonModel([
770
            'success' => false,
771
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
772
        ]);
773
    }
774
 
775
    public function forgotPasswordAction()
776
    {
3650 efrain 777
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 778
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
779
 
780
 
781
 
1 www 782
        $request = $this->getRequest();
783
        if($request->isPost()) {
784
            $dataPost = $request->getPost()->toArray();
785
            if(empty($_SESSION['aes'])) {
786
                return new JsonModel([
787
                    'success'   => false,
788
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
789
                ]);
790
            }
791
 
792
            if(!empty( $dataPost['email'])) {
793
                $dataPost['email'] = CryptoJsAes::decrypt( $dataPost['email'], $_SESSION['aes']);
794
            }
795
 
796
            $form = new ForgotPasswordForm($this->config);
797
            $form->setData($dataPost);
798
 
799
            if($form->isValid()) {
800
                $dataPost = (array) $form->getData();
801
                $email      = $dataPost['email'];
802
 
803
                $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 804
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1 www 805
                if(!$user) {
806
                    $this->logger->err('Olvidó contraseña ' . $email . '- Email no existe ', ['ip' => Functions::getUserIP()]);
807
 
808
                    return new JsonModel([
809
                        'success' => false,
810
                        'data' =>  'ERROR_EMAIL_IS_NOT_REGISTERED'
811
                    ]);
812
                } else {
813
                    if($user->status == User::STATUS_INACTIVE) {
814
                        return new JsonModel([
815
                            'success' => false,
816
                            'data' =>  'ERROR_USER_IS_INACTIVE'
817
                        ]);
818
                    } else if ($user->email_verified == User::EMAIL_VERIFIED_NO) {
819
                        $this->logger->err('Olvidó contraseña - Email no verificado ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
820
 
821
                        return new JsonModel([
822
                            'success' => false,
823
                            'data' => 'ERROR_EMAIL_HAS_NOT_BEEN_VERIFIED'
824
                        ]);
825
                    } else {
826
                        $password_reset_key = md5($user->email. time());
827
                        $userMapper->updatePasswordResetKey((int) $user->id, $password_reset_key);
828
 
829
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3649 efrain 830
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RESET_PASSWORD, $currentNetwork->id);
1 www 831
                        if($emailTemplate) {
832
                            $arrayCont = [
833
                                'firstname'             => $user->first_name,
834
                                'lastname'              => $user->last_name,
835
                                'other_user_firstname'  => '',
836
                                'other_user_lastname'   => '',
837
                                'company_name'          => '',
838
                                'group_name'            => '',
839
                                'content'               => '',
840
                                'code'                  => '',
841
                                'link'                  => $this->url()->fromRoute('reset-password', ['code' => $password_reset_key], ['force_canonical' => true])
842
                            ];
843
 
844
                            $email = new QueueEmail($this->adapter);
845
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
846
                        }
847
                        $flashMessenger = $this->plugin('FlashMessenger');
848
                        $flashMessenger->addSuccessMessage('LABEL_RECOVERY_LINK_WAS_SENT_TO_YOUR_EMAIL');
849
 
850
                        $this->logger->info('Olvidó contraseña - Se envio link de recuperación ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
851
 
852
                        return new JsonModel([
853
                            'success' => true,
854
                        ]);
855
                    }
856
                }
857
 
858
            } else {
859
 
860
 
861
                $form_messages =  $form->getMessages('captcha');
862
 
863
 
864
 
865
                if(!empty($form_messages)) {
866
                    return new JsonModel([
867
                        'success'   => false,
868
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
869
                    ]);
870
                }
871
 
872
                $messages = [];
873
                $form_messages = (array) $form->getMessages();
874
                foreach($form_messages  as $fieldname => $field_messages)
875
                {
876
                    $messages[$fieldname] = array_values($field_messages);
877
                }
878
 
879
                return new JsonModel([
880
                    'success'   => false,
881
                    'data'      => $messages
882
                ]);
883
            }
884
        }
885
 
886
        /*
887
        if($request->isGet())  {
888
            if(empty($_SESSION['aes'])) {
889
                $_SESSION['aes'] = Functions::generatePassword(16);
890
            }
891
 
892
            if($this->config['leaderslinked.runmode.sandbox']) {
893
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
894
            } else {
895
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
896
            }
897
 
898
 
899
            $form = new ForgotPasswordForm($this->config);
900
 
901
            $this->layout()->setTemplate('layout/auth.phtml');
902
            $viewModel = new ViewModel();
903
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
904
            $viewModel->setVariables([
905
                'form' => $form,
906
                'site_key' => $site_key,
907
                'aes' => $_SESSION['aes'],
908
            ]);
909
 
910
            return $viewModel ;
911
        }
912
        */
913
 
914
        if($request->isGet())  {
915
 
916
            if(empty($_SESSION['aes'])) {
917
                $_SESSION['aes'] = Functions::generatePassword(16);
918
            }
919
 
920
            if($this->config['leaderslinked.runmode.sandbox']) {
921
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
922
            } else {
923
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
924
            }
925
 
926
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
927
            $remember   = $email ? true : false;
928
 
929
            $form = new SigninForm($this->config);
930
            $form->setData([
931
                'email'     => $email,
932
                'remember'  => $remember,
933
            ]);
934
            $this->layout()->setTemplate('layout/auth.phtml');
935
            $viewModel = new ViewModel();
936
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
937
            $viewModel->setVariables([
938
                'form'      =>  $form,
939
                'site_key'  => $site_key,
940
                'aes'       => $_SESSION['aes'],
941
            ]);
942
 
943
            return $viewModel ;
944
 
945
        }
946
 
947
        return new JsonModel([
948
            'success' => false,
949
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
950
        ]);
951
    }
952
 
953
    public function signupAction()
954
    {
3650 efrain 955
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 956
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
957
 
958
 
1 www 959
        $request = $this->getRequest();
960
        if($request->isPost()) {
961
            $dataPost = $request->getPost()->toArray();
962
 
963
            if(empty($_SESSION['aes'])) {
964
                return new JsonModel([
965
                    'success'   => false,
966
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
967
                ]);
968
            }
969
 
970
            if(!empty( $dataPost['email'])) {
971
                $dataPost['email'] = CryptoJsAes::decrypt( $dataPost['email'], $_SESSION['aes']);
972
            }
973
 
974
            if(!empty( $dataPost['password'])) {
975
                $dataPost['password'] = CryptoJsAes::decrypt( $dataPost['password'], $_SESSION['aes']);
976
            }
977
 
978
            if(!empty( $dataPost['confirmation'])) {
979
                $dataPost['confirmation'] = CryptoJsAes::decrypt( $dataPost['confirmation'], $_SESSION['aes']);
980
            }
981
 
982
 
983
            $form = new SignupForm($this->config);
984
            $form->setData($dataPost);
985
 
986
            if($form->isValid()) {
987
                $dataPost = (array) $form->getData();
988
 
989
                $email = $dataPost['email'];
990
 
991
                $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 992
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1 www 993
                if($user) {
994
                    $this->logger->err('Registro ' . $email . '- Email ya  existe ', ['ip' => Functions::getUserIP()]);
995
 
996
 
997
 
998
                    return new JsonModel([
999
                        'success' => false,
1000
                        'data' => 'ERROR_EMAIL_IS_REGISTERED'
1001
                    ]);
1002
                } else {
3298 efrain 1003
 
3364 efrain 1004
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
1005
 
3298 efrain 1006
 
3364 efrain 1007
                    if($user_share_invitation) {
1008
                        $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
3298 efrain 1009
                        if($userRedirect && $userRedirect->status == User::STATUS_ACTIVE) {
1010
                            $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1011
 
1012
                            $user = new User();
3649 efrain 1013
                            $user->network_id           = $currentNetwork->id;
3298 efrain 1014
                            $user->email                = $dataPost['email'];
1015
                            $user->first_name           = $dataPost['first_name'];
1016
                            $user->last_name            = $dataPost['last_name'];
1017
                            $user->usertype_id          = UserType::USER;
1018
                            $user->password             = $password_hash;
1019
                            $user->password_updated_on  = date('Y-m-d H:i:s');
1020
                            $user->status               = User::STATUS_ACTIVE;
1021
                            $user->blocked              = User::BLOCKED_NO;
1022
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
1023
                            $user->login_attempt        = 0;
1024
 
1025
 
1026
                            if($userMapper->insert($user)) {
1027
 
1028
                                $userPassword = new UserPassword();
1029
                                $userPassword->user_id = $user->id;
1030
                                $userPassword->password = $password_hash;
1031
 
1032
                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1033
                                $userPasswordMapper->insert($userPassword);
1034
 
1035
 
1036
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1037
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1038
 
1039
                                if($connection) {
1040
 
1041
                                    if($connection->status != Connection::STATUS_ACCEPTED) {
1042
                                        $connectionMapper->approve($connection);
1043
                                    }
1044
 
1045
                                } else {
1046
                                    $connection = new Connection();
1047
                                    $connection->request_from = $user->id;
1048
                                    $connection->request_to = $userRedirect->id;
1049
                                    $connection->status = Connection::STATUS_ACCEPTED;
1050
 
1051
                                    $connectionMapper->insert($connection);
1052
                                }
1053
 
1054
 
3364 efrain 1055
                                $this->cache->removeItem('user_share_invitation');
1056
 
3298 efrain 1057
 
1058
 
3364 efrain 1059
                                $data = [
1060
                                    'success'   => true,
1061
                                    'data'      => $this->url()->fromRoute('home'),
1062
                                ];
1063
 
3298 efrain 1064
 
1065
                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1066
 
1067
                                return new JsonModel($data);
1068
                            }
1069
                        }
1070
                    }
1071
 
1072
 
1073
 
1074
 
1 www 1075
                    $timestamp = time();
1076
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);
1077
 
1078
                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1079
 
1080
                    $user = new User();
3649 efrain 1081
                    $user->network_id           = $currentNetwork->id;
1 www 1082
                    $user->email                = $dataPost['email'];
1083
                    $user->first_name           = $dataPost['first_name'];
1084
                    $user->last_name            = $dataPost['last_name'];
1085
                    $user->usertype_id          = UserType::USER;
1086
                    $user->password             = $password_hash;
1087
                    $user->password_updated_on  = date('Y-m-d H:i:s');
1088
                    $user->activation_key       = $activation_key;
1089
                    $user->status               = User::STATUS_INACTIVE;
1090
                    $user->blocked              = User::BLOCKED_NO;
1091
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
1092
                    $user->login_attempt        = 0;
3671 efrain 1093
 
1 www 1094
 
1095
                    if($userMapper->insert($user)) {
1096
 
1097
                        $userPassword = new UserPassword();
1098
                        $userPassword->user_id = $user->id;
1099
                        $userPassword->password = $password_hash;
1100
 
1101
                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1102
                        $userPasswordMapper->insert($userPassword);
1103
 
1104
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3649 efrain 1105
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
1 www 1106
                        if($emailTemplate) {
1107
                            $arrayCont = [
1108
                                'firstname'             => $user->first_name,
1109
                                'lastname'              => $user->last_name,
1110
                                'other_user_firstname'  => '',
1111
                                'other_user_lastname'   => '',
1112
                                'company_name'          => '',
1113
                                'group_name'            => '',
1114
                                'content'               => '',
1115
                                'code'                  => '',
3298 efrain 1116
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
1 www 1117
                            ];
1118
 
1119
                            $email = new QueueEmail($this->adapter);
1120
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1121
                        }
1122
                        $flashMessenger = $this->plugin('FlashMessenger');
1123
                        $flashMessenger->addSuccessMessage('LABEL_REGISTRATION_DONE');
1124
 
1125
                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1126
 
1127
                        return new JsonModel([
1128
                            'success' => true,
1129
                        ]);
1130
 
1131
                    } else {
1132
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);
1133
 
1134
                        return new JsonModel([
1135
                            'success' => false,
1136
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1137
                        ]);
1138
                    }
1139
                }
1140
 
1141
 
1142
 
1143
            } else {
1144
 
1145
                $form_messages =  $form->getMessages('captcha');
1146
                if(!empty($form_messages)) {
1147
                    return new JsonModel([
1148
                        'success'   => false,
1149
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1150
                    ]);
1151
                }
1152
 
1153
                $messages = [];
1154
 
1155
                $form_messages = (array) $form->getMessages();
1156
                foreach($form_messages  as $fieldname => $field_messages)
1157
                {
1158
                    $messages[$fieldname] = array_values($field_messages);
1159
                }
1160
 
1161
                return new JsonModel([
1162
                    'success'   => false,
1163
                    'data'   => $messages
1164
                ]);
1165
            }
1166
        }
1167
        /*
1168
        if($request->isGet())  {
1169
            if(empty($_SESSION['aes'])) {
1170
                $_SESSION['aes'] = Functions::generatePassword(16);
1171
            }
1172
 
1173
            if($this->config['leaderslinked.runmode.sandbox']) {
1174
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1175
            } else {
1176
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1177
            }
1178
 
1179
 
1180
            $form = new SignupForm($this->config);
1181
 
1182
            $this->layout()->setTemplate('layout/auth.phtml');
1183
            $viewModel = new ViewModel();
1184
            $viewModel->setTemplate('leaders-linked/auth/signup.phtml');
1185
            $viewModel->setVariables([
1186
                'form' => $form,
1187
                'site_key' => $site_key,
1188
                'aes' =>  $_SESSION['aes'],
1189
            ]);
1190
 
1191
            return $viewModel ;
1192
        } */
1193
 
1194
 
1195
        if($request->isGet())  {
1196
 
1197
            if(empty($_SESSION['aes'])) {
1198
                $_SESSION['aes'] = Functions::generatePassword(16);
1199
            }
1200
 
1201
            if($this->config['leaderslinked.runmode.sandbox']) {
1202
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1203
            } else {
1204
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1205
            }
1206
 
1207
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
1208
            $remember   = $email ? true : false;
1209
 
1210
            $form = new SigninForm($this->config);
1211
            $form->setData([
1212
                'email'     => $email,
1213
                'remember'  => $remember,
1214
            ]);
1215
            $this->layout()->setTemplate('layout/auth.phtml');
1216
            $viewModel = new ViewModel();
1217
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
1218
            $viewModel->setVariables([
1219
                'form'      =>  $form,
1220
                'site_key'  => $site_key,
1221
                'aes'       => $_SESSION['aes'],
1222
            ]);
1223
 
1224
            return $viewModel ;
1225
 
1226
        }
1227
 
1228
        return new JsonModel([
1229
            'success' => false,
1230
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1231
        ]);
1232
 
1233
 
1234
    }
1235
 
1236
    public function activateAccountAction()
1237
    {
1238
 
3650 efrain 1239
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 1240
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1241
 
1242
 
1243
 
1 www 1244
        $request = $this->getRequest();
1245
        if($request->isGet()) {
1246
            $code   = filter_var($this->params()->fromRoute('code'), FILTER_SANITIZE_STRING);
1247
            $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 1248
            $user = $userMapper->fetchOneByActivationKeyAndNetwork_id($code, $currentNetwork->id);
1 www 1249
 
1250
            $flashMessenger = $this->plugin('FlashMessenger');
1251
 
1252
            if($user) {
1253
                if(User::EMAIL_VERIFIED_YES == $user->email_verified) {
3671 efrain 1254
 
1 www 1255
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1256
 
1257
                    $flashMessenger->addErrorMessage('ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED');
1258
                } else {
3671 efrain 1259
 
1 www 1260
                    if($userMapper->activateAccount((int) $user->id)) {
3728 efrain 1261
 
1 www 1262
                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1263
 
1264
                        $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED');
3298 efrain 1265
 
3364 efrain 1266
                        $user_share_invitation = $this->cache->getItem('user_share_invitation');
3298 efrain 1267
 
3364 efrain 1268
                        if($user_share_invitation) {
1269
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
3298 efrain 1270
                            if($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
1271
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1272
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1273
 
1274
                                if($connection) {
1275
 
1276
                                    if($connection->status != Connection::STATUS_ACCEPTED) {
1277
                                        $connectionMapper->approve($connection);
1278
                                    }
1279
 
1280
                                } else {
1281
                                    $connection = new Connection();
1282
                                    $connection->request_from = $user->id;
1283
                                    $connection->request_to = $userRedirect->id;
1284
                                    $connection->status = Connection::STATUS_ACCEPTED;
1285
 
1286
                                    $connectionMapper->insert($connection);
1287
                                }
1288
                            }
1289
                        }
1290
 
3364 efrain 1291
 
3298 efrain 1292
 
3364 efrain 1293
                        $this->cache->removeItem('user_share_invitation');
3729 efrain 1294
 
3298 efrain 1295
 
1 www 1296
                    } else {
1297
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1298
 
1299
                        $flashMessenger->addErrorMessage('ERROR_THERE_WAS_AN_ERROR');
1300
                    }
1301
                }
1302
            } else {
1303
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);
1304
 
1305
                $flashMessenger->addErrorMessage('ERROR_ACTIVATION_CODE_IS_NOT_VALID');
1306
            }
1307
 
3729 efrain 1308
            return $this->redirect()->toRoute('home');
1309
 
1 www 1310
 
3298 efrain 1311
 
1 www 1312
        } else {
1313
            $response = [
1314
                'success' => false,
1315
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1316
            ];
1317
        }
1318
 
1319
        return new JsonModel($response);
1320
 
1321
    }
1322
 
1323
 
1324
 
1325
    public function onroomAction()
1326
    {
3650 efrain 1327
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 1328
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1329
 
1330
 
1331
 
1 www 1332
        $request = $this->getRequest();
1333
 
1334
        if($request->isPost()) {
1335
 
1336
            $dataPost = $request->getPost()->toArray();
1337
 
1338
 
1339
            $form = new  MoodleForm();
1340
            $form->setData($dataPost);
1341
            if($form->isValid()) {
1342
 
1343
                $dataPost   = (array) $form->getData();
1344
                $username   = $dataPost['username'];
1345
                $password   = $dataPost['password'];
1346
                $timestamp  = $dataPost['timestamp'];
1347
                $rand       = $dataPost['rand'];
1348
                $data       = $dataPost['data'];
1349
 
1350
                $config_username    = $this->config['leaderslinked.moodle.username'];
1351
                $config_password    = $this->config['leaderslinked.moodle.password'];
1352
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1353
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
1354
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
1355
 
1356
 
1357
 
1358
 
1359
                if(empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1360
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']) ;
1361
                    exit;
1362
                }
1363
 
1364
                if($username != $config_username) {
1365
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']) ;
1366
                    exit;
1367
                }
1368
 
1369
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1370
                if(!$dt) {
1371
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']) ;
1372
                    exit;
1373
                }
1374
 
1375
                $t0 = $dt->getTimestamp();
1376
                $t1 = strtotime('-5 minutes');
1377
                $t2 = strtotime('+5 minutes');
1378
 
1379
                if($t0 < $t1 || $t0 > $t2) {
1380
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1381
                    //exit;
1382
                }
1383
 
1384
                if(!password_verify( $username.'-'. $config_password . '-' . $rand. '-' . $timestamp, $password)) {
1385
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']) ;
1386
                    exit;
1387
                }
1388
 
1389
                if(empty($data)) {
1390
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']) ;
1391
                    exit;
1392
                }
1393
 
1394
                $data = base64_decode($data);
1395
                if(empty($data)) {
1396
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']) ;
1397
                    exit;
1398
                }
1399
 
1400
 
1401
                try {
1402
                    $rsa = Rsa::getInstance();
1403
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1404
                } catch (\Throwable $e)
1405
                {
1406
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']) ;
1407
                    exit;
1408
                }
1409
 
1410
                $data = (array) json_decode($data);
1411
                if(empty($data)) {
1412
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']) ;
1413
                    exit;
1414
                }
1415
 
1416
                $email      = trim(isset($data['email']) ? filter_var($data['email'], FILTER_SANITIZE_EMAIL) : '');
1417
                $first_name = trim(isset($data['first_name']) ? filter_var($data['first_name'], FILTER_SANITIZE_STRING) : '');
1418
                $last_name  = trim(isset($data['last_name']) ? filter_var($data['last_name'], FILTER_SANITIZE_STRING) : '');
1419
 
1420
                if(!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
1421
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']) ;
1422
                    exit;
1423
                }
1424
 
1425
                $userMapper = UserMapper::getInstance($this->adapter);
1426
                $user = $userMapper->fetchOneByEmail($email);
1427
                if(!$user) {
1428
 
1429
 
1430
                    $user = new User();
3649 efrain 1431
                    $user->network_id = $currentNetwork->id;
1 www 1432
                    $user->blocked = User::BLOCKED_NO;
1433
                    $user->email = $email;
1434
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1435
                    $user->first_name = $first_name;
1436
                    $user->last_name = $last_name;
1437
                    $user->login_attempt = 0;
1438
                    $user->password = '-NO-PASSWORD-';
1439
                    $user->usertype_id = UserType::USER;
1440
                    $user->status = User::STATUS_ACTIVE;
1441
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
1442
 
1443
                    if($userMapper->insert($user)) {
1444
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]) ;
1445
                        exit;
1446
                    }
1447
 
1448
 
1449
 
1450
 
1451
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
1452
                    $content    = trim(isset($data['avatar_content']) ? filter_var($data['avatar_content'], FILTER_SANITIZE_STRING) : '');
1453
 
1454
                    if($filename && $content) {
1455
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
1456
                        try {
1457
                            file_put_contents($source, base64_decode($content));
1458
                            if (file_exists($source)) {
1459
                                $target_path = $this->config['leaderslinked.fullpath.user'] . $user->uuid;
1460
                                list( $target_width, $target_height ) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
1461
 
1462
                                $target_filename    = 'user-' . uniqid() . '.png';
1463
                                $crop_to_dimensions = true;
1464
 
1465
                                if(!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
1466
                                    return new JsonModel([
1467
                                        'success'   => false,
1468
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1469
                                    ]);
1470
                                }
1471
 
1472
                                $user->image = $target_filename;
1473
                                $userMapper->updateImage($user);
1474
                            }
1475
                        } catch(\Throwable $e) {
1476
 
1477
                        } finally {
1478
                            if(file_exists($source)) {
1479
                                unlink($source);
1480
                            }
1481
                        }
1482
                    }
1483
 
1484
                }
1485
 
1486
                $auth = new AuthEmailAdapter($this->adapter);
1487
                $auth->setData($email);
1488
 
1489
                $result = $auth->authenticate();
1490
                if($result->getCode() == AuthResult::SUCCESS) {
1491
                    return $this->redirect()->toRoute('dashboard');
1492
 
1493
 
1494
                } else {
1495
                    $message = $result->getMessages()[0];
1496
                    if(!in_array($message, ['ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1497
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1498
                        'ERROR_ENTERED_PASS_INCORRECT_1'])) {
1499
 
1500
 
1501
                    }
1502
 
1503
                    switch($message)
1504
                    {
1505
                        case 'ERROR_USER_NOT_FOUND' :
1506
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1507
                            break;
1508
 
1509
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED' :
1510
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1511
                            break;
1512
 
1513
                        case 'ERROR_USER_IS_BLOCKED' :
1514
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1515
                            break;
1516
 
1517
                        case 'ERROR_USER_IS_INACTIVE' :
1518
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1519
                            break;
1520
 
1521
 
1522
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1523
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1524
                            break;
1525
 
1526
 
1527
                        case 'ERROR_ENTERED_PASS_INCORRECT_2' :
1528
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1529
                            break;
1530
 
1531
 
1532
                        case 'ERROR_ENTERED_PASS_INCORRECT_1' :
1533
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1534
                            break;
1535
 
1536
 
1537
                        default :
1538
                            $message = 'ERROR_UNKNOWN';
1539
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1540
                            break;
1541
 
1542
 
1543
                    }
1544
 
1545
 
1546
 
1547
 
1548
                    return new JsonModel( [
1549
                        'success'   => false,
1550
                        'data'   => $message
1551
                    ]);
1552
                }
1553
 
1554
 
1555
 
1556
 
1557
            } else {
1558
                $messages = [];
1559
 
1560
 
1561
 
1562
                $form_messages = (array) $form->getMessages();
1563
                foreach($form_messages  as $fieldname => $field_messages)
1564
                {
1565
 
1566
                    $messages[$fieldname] = array_values($field_messages);
1567
                }
1568
 
1569
                return new JsonModel([
1570
                    'success'   => false,
1571
                    'data'   => $messages
1572
                ]);
1573
            }
1574
 
1575
        } else {
1576
            $data = [
1577
                'success' => false,
1578
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1579
            ];
1580
 
1581
            return new JsonModel($data);
1582
        }
1583
 
1584
        return new JsonModel($data);
1585
    }
1586
 
210 efrain 1587
    public function csrfAction()
1588
    {
1589
        $request = $this->getRequest();
1590
        if($request->isGet()) {
1591
 
1592
            $token = md5(uniqid('CSFR-' . mt_rand(), true));
1593
            $_SESSION['token'] = $token;
1594
 
1595
 
1596
            return new JsonModel([
1597
                'success' => true,
1598
                'data' => $token
1599
            ]);
1600
 
1601
 
1602
        } else {
1603
            return new JsonModel([
1604
                'success' => false,
1605
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1606
            ]);
1607
        }
1608
 
1609
 
1610
    }
3639 efrain 1611
 
1612
    public function impersonateAction()
1613
    {
1614
        $request = $this->getRequest();
1615
        if($request->isGet()) {
1616
            $user_uuid  = filter_var($this->params()->fromQuery('user_uuid'), FILTER_SANITIZE_STRING);
1617
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
1618
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
1619
            $password   = filter_var($this->params()->fromQuery('password'), FILTER_SANITIZE_STRING);
1620
 
1621
 
1622
            if(!$user_uuid || !$rand || !$timestamp || !$password ) {
1623
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
1624
            }
1625
 
1626
 
3650 efrain 1627
            $currentUserPlugin = $this->plugin('currentUserPlugin');
3639 efrain 1628
            $currentUserPlugin->clearIdentity();
1629
 
1630
 
1631
            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
1632
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);
1633
 
1634
            $authService = new AuthenticationService();
1635
            $result = $authService->authenticate($authAdapter);
1636
 
1637
 
1638
            if($result->getCode() == AuthResult::SUCCESS) {
1639
                return $this->redirect()->toRoute('dashboard');
1640
            } else {
1641
                throw new \Exception($result->getMessages()[0]);
1642
            }
1643
        }
1644
 
1645
        return new JsonModel([
1646
            'success' => false,
1647
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1648
        ]);
1649
    }
1 www 1650
 
1651
}