Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 3759 | Rev 4419 | 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
 
4398 efrain 982
            if(empty($dataPost['is_adult'])) {
983
                $dataPost['is_adult'] = User::IS_ADULT_NO;
984
            } else {
985
                $dataPost['is_adult'] = $dataPost['is_adult'] == User::IS_ADULT_YES ? User::IS_ADULT_YES : User::IS_ADULT_NO;
986
            }
1 www 987
 
4398 efrain 988
 
989
 
1 www 990
            $form = new SignupForm($this->config);
991
            $form->setData($dataPost);
992
 
993
            if($form->isValid()) {
994
                $dataPost = (array) $form->getData();
995
 
996
                $email = $dataPost['email'];
997
 
998
                $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 999
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1 www 1000
                if($user) {
1001
                    $this->logger->err('Registro ' . $email . '- Email ya  existe ', ['ip' => Functions::getUserIP()]);
1002
 
1003
 
1004
 
1005
                    return new JsonModel([
1006
                        'success' => false,
1007
                        'data' => 'ERROR_EMAIL_IS_REGISTERED'
1008
                    ]);
1009
                } else {
3298 efrain 1010
 
3364 efrain 1011
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
1012
 
3298 efrain 1013
 
3364 efrain 1014
                    if($user_share_invitation) {
1015
                        $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
3298 efrain 1016
                        if($userRedirect && $userRedirect->status == User::STATUS_ACTIVE) {
1017
                            $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1018
 
1019
                            $user = new User();
3649 efrain 1020
                            $user->network_id           = $currentNetwork->id;
3298 efrain 1021
                            $user->email                = $dataPost['email'];
1022
                            $user->first_name           = $dataPost['first_name'];
1023
                            $user->last_name            = $dataPost['last_name'];
1024
                            $user->usertype_id          = UserType::USER;
1025
                            $user->password             = $password_hash;
1026
                            $user->password_updated_on  = date('Y-m-d H:i:s');
1027
                            $user->status               = User::STATUS_ACTIVE;
1028
                            $user->blocked              = User::BLOCKED_NO;
1029
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
1030
                            $user->login_attempt        = 0;
4398 efrain 1031
                            $user->is_adult             = $dataPost['is_adult'];
3298 efrain 1032
 
1033
 
1034
                            if($userMapper->insert($user)) {
1035
 
1036
                                $userPassword = new UserPassword();
1037
                                $userPassword->user_id = $user->id;
1038
                                $userPassword->password = $password_hash;
1039
 
1040
                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1041
                                $userPasswordMapper->insert($userPassword);
1042
 
1043
 
1044
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1045
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1046
 
1047
                                if($connection) {
1048
 
1049
                                    if($connection->status != Connection::STATUS_ACCEPTED) {
1050
                                        $connectionMapper->approve($connection);
1051
                                    }
1052
 
1053
                                } else {
1054
                                    $connection = new Connection();
1055
                                    $connection->request_from = $user->id;
1056
                                    $connection->request_to = $userRedirect->id;
1057
                                    $connection->status = Connection::STATUS_ACCEPTED;
1058
 
1059
                                    $connectionMapper->insert($connection);
1060
                                }
1061
 
1062
 
3364 efrain 1063
                                $this->cache->removeItem('user_share_invitation');
1064
 
3298 efrain 1065
 
1066
 
3364 efrain 1067
                                $data = [
1068
                                    'success'   => true,
1069
                                    'data'      => $this->url()->fromRoute('home'),
1070
                                ];
1071
 
3298 efrain 1072
 
1073
                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1074
 
1075
                                return new JsonModel($data);
1076
                            }
1077
                        }
1078
                    }
1079
 
1080
 
1081
 
1082
 
1 www 1083
                    $timestamp = time();
1084
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);
1085
 
1086
                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1087
 
1088
                    $user = new User();
3649 efrain 1089
                    $user->network_id           = $currentNetwork->id;
1 www 1090
                    $user->email                = $dataPost['email'];
1091
                    $user->first_name           = $dataPost['first_name'];
1092
                    $user->last_name            = $dataPost['last_name'];
1093
                    $user->usertype_id          = UserType::USER;
1094
                    $user->password             = $password_hash;
1095
                    $user->password_updated_on  = date('Y-m-d H:i:s');
1096
                    $user->activation_key       = $activation_key;
1097
                    $user->status               = User::STATUS_INACTIVE;
1098
                    $user->blocked              = User::BLOCKED_NO;
1099
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
1100
                    $user->login_attempt        = 0;
3671 efrain 1101
 
1 www 1102
 
1103
                    if($userMapper->insert($user)) {
1104
 
1105
                        $userPassword = new UserPassword();
1106
                        $userPassword->user_id = $user->id;
1107
                        $userPassword->password = $password_hash;
1108
 
1109
                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1110
                        $userPasswordMapper->insert($userPassword);
1111
 
1112
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3649 efrain 1113
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
1 www 1114
                        if($emailTemplate) {
1115
                            $arrayCont = [
1116
                                'firstname'             => $user->first_name,
1117
                                'lastname'              => $user->last_name,
1118
                                'other_user_firstname'  => '',
1119
                                'other_user_lastname'   => '',
1120
                                'company_name'          => '',
1121
                                'group_name'            => '',
1122
                                'content'               => '',
1123
                                'code'                  => '',
3298 efrain 1124
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
1 www 1125
                            ];
1126
 
1127
                            $email = new QueueEmail($this->adapter);
1128
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1129
                        }
1130
                        $flashMessenger = $this->plugin('FlashMessenger');
1131
                        $flashMessenger->addSuccessMessage('LABEL_REGISTRATION_DONE');
1132
 
1133
                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1134
 
1135
                        return new JsonModel([
1136
                            'success' => true,
1137
                        ]);
1138
 
1139
                    } else {
1140
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);
1141
 
1142
                        return new JsonModel([
1143
                            'success' => false,
1144
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1145
                        ]);
1146
                    }
1147
                }
1148
 
1149
 
1150
 
1151
            } else {
1152
 
1153
                $form_messages =  $form->getMessages('captcha');
1154
                if(!empty($form_messages)) {
1155
                    return new JsonModel([
1156
                        'success'   => false,
1157
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1158
                    ]);
1159
                }
1160
 
1161
                $messages = [];
1162
 
1163
                $form_messages = (array) $form->getMessages();
1164
                foreach($form_messages  as $fieldname => $field_messages)
1165
                {
1166
                    $messages[$fieldname] = array_values($field_messages);
1167
                }
1168
 
1169
                return new JsonModel([
1170
                    'success'   => false,
1171
                    'data'   => $messages
1172
                ]);
1173
            }
1174
        }
1175
        /*
1176
        if($request->isGet())  {
1177
            if(empty($_SESSION['aes'])) {
1178
                $_SESSION['aes'] = Functions::generatePassword(16);
1179
            }
1180
 
1181
            if($this->config['leaderslinked.runmode.sandbox']) {
1182
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1183
            } else {
1184
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1185
            }
1186
 
1187
 
1188
            $form = new SignupForm($this->config);
1189
 
1190
            $this->layout()->setTemplate('layout/auth.phtml');
1191
            $viewModel = new ViewModel();
1192
            $viewModel->setTemplate('leaders-linked/auth/signup.phtml');
1193
            $viewModel->setVariables([
1194
                'form' => $form,
1195
                'site_key' => $site_key,
1196
                'aes' =>  $_SESSION['aes'],
1197
            ]);
1198
 
1199
            return $viewModel ;
1200
        } */
1201
 
1202
 
1203
        if($request->isGet())  {
1204
 
1205
            if(empty($_SESSION['aes'])) {
1206
                $_SESSION['aes'] = Functions::generatePassword(16);
1207
            }
1208
 
1209
            if($this->config['leaderslinked.runmode.sandbox']) {
1210
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1211
            } else {
1212
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1213
            }
1214
 
1215
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
1216
            $remember   = $email ? true : false;
1217
 
1218
            $form = new SigninForm($this->config);
1219
            $form->setData([
1220
                'email'     => $email,
1221
                'remember'  => $remember,
1222
            ]);
1223
            $this->layout()->setTemplate('layout/auth.phtml');
1224
            $viewModel = new ViewModel();
1225
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
1226
            $viewModel->setVariables([
1227
                'form'      =>  $form,
1228
                'site_key'  => $site_key,
1229
                'aes'       => $_SESSION['aes'],
1230
            ]);
1231
 
1232
            return $viewModel ;
1233
 
1234
        }
1235
 
1236
        return new JsonModel([
1237
            'success' => false,
1238
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1239
        ]);
1240
 
1241
 
1242
    }
1243
 
1244
    public function activateAccountAction()
1245
    {
1246
 
3650 efrain 1247
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 1248
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1249
 
1250
 
1251
 
1 www 1252
        $request = $this->getRequest();
1253
        if($request->isGet()) {
1254
            $code   = filter_var($this->params()->fromRoute('code'), FILTER_SANITIZE_STRING);
1255
            $userMapper = UserMapper::getInstance($this->adapter);
3759 efrain 1256
            $user = $userMapper->fetchOneByActivationKeyAndNetworkId($code, $currentNetwork->id);
1 www 1257
 
1258
            $flashMessenger = $this->plugin('FlashMessenger');
1259
 
1260
            if($user) {
1261
                if(User::EMAIL_VERIFIED_YES == $user->email_verified) {
3671 efrain 1262
 
1 www 1263
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1264
 
1265
                    $flashMessenger->addErrorMessage('ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED');
1266
                } else {
3671 efrain 1267
 
1 www 1268
                    if($userMapper->activateAccount((int) $user->id)) {
3728 efrain 1269
 
1 www 1270
                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1271
 
1272
                        $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED');
3298 efrain 1273
 
3364 efrain 1274
                        $user_share_invitation = $this->cache->getItem('user_share_invitation');
3298 efrain 1275
 
3364 efrain 1276
                        if($user_share_invitation) {
1277
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
3298 efrain 1278
                            if($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
1279
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1280
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1281
 
1282
                                if($connection) {
1283
 
1284
                                    if($connection->status != Connection::STATUS_ACCEPTED) {
1285
                                        $connectionMapper->approve($connection);
1286
                                    }
1287
 
1288
                                } else {
1289
                                    $connection = new Connection();
1290
                                    $connection->request_from = $user->id;
1291
                                    $connection->request_to = $userRedirect->id;
1292
                                    $connection->status = Connection::STATUS_ACCEPTED;
1293
 
1294
                                    $connectionMapper->insert($connection);
1295
                                }
1296
                            }
1297
                        }
1298
 
3364 efrain 1299
 
3298 efrain 1300
 
3364 efrain 1301
                        $this->cache->removeItem('user_share_invitation');
3729 efrain 1302
 
3298 efrain 1303
 
1 www 1304
                    } else {
1305
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1306
 
1307
                        $flashMessenger->addErrorMessage('ERROR_THERE_WAS_AN_ERROR');
1308
                    }
1309
                }
1310
            } else {
1311
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);
1312
 
1313
                $flashMessenger->addErrorMessage('ERROR_ACTIVATION_CODE_IS_NOT_VALID');
1314
            }
1315
 
3729 efrain 1316
            return $this->redirect()->toRoute('home');
1317
 
1 www 1318
 
3298 efrain 1319
 
1 www 1320
        } else {
1321
            $response = [
1322
                'success' => false,
1323
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1324
            ];
1325
        }
1326
 
1327
        return new JsonModel($response);
1328
 
1329
    }
1330
 
1331
 
1332
 
1333
    public function onroomAction()
1334
    {
3650 efrain 1335
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 1336
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1337
 
1338
 
1339
 
1 www 1340
        $request = $this->getRequest();
1341
 
1342
        if($request->isPost()) {
1343
 
1344
            $dataPost = $request->getPost()->toArray();
1345
 
1346
 
1347
            $form = new  MoodleForm();
1348
            $form->setData($dataPost);
1349
            if($form->isValid()) {
1350
 
1351
                $dataPost   = (array) $form->getData();
1352
                $username   = $dataPost['username'];
1353
                $password   = $dataPost['password'];
1354
                $timestamp  = $dataPost['timestamp'];
1355
                $rand       = $dataPost['rand'];
1356
                $data       = $dataPost['data'];
1357
 
1358
                $config_username    = $this->config['leaderslinked.moodle.username'];
1359
                $config_password    = $this->config['leaderslinked.moodle.password'];
1360
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1361
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
1362
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
1363
 
1364
 
1365
 
1366
 
1367
                if(empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1368
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']) ;
1369
                    exit;
1370
                }
1371
 
1372
                if($username != $config_username) {
1373
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']) ;
1374
                    exit;
1375
                }
1376
 
1377
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1378
                if(!$dt) {
1379
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']) ;
1380
                    exit;
1381
                }
1382
 
1383
                $t0 = $dt->getTimestamp();
1384
                $t1 = strtotime('-5 minutes');
1385
                $t2 = strtotime('+5 minutes');
1386
 
1387
                if($t0 < $t1 || $t0 > $t2) {
1388
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1389
                    //exit;
1390
                }
1391
 
1392
                if(!password_verify( $username.'-'. $config_password . '-' . $rand. '-' . $timestamp, $password)) {
1393
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']) ;
1394
                    exit;
1395
                }
1396
 
1397
                if(empty($data)) {
1398
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']) ;
1399
                    exit;
1400
                }
1401
 
1402
                $data = base64_decode($data);
1403
                if(empty($data)) {
1404
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']) ;
1405
                    exit;
1406
                }
1407
 
1408
 
1409
                try {
1410
                    $rsa = Rsa::getInstance();
1411
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1412
                } catch (\Throwable $e)
1413
                {
1414
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']) ;
1415
                    exit;
1416
                }
1417
 
1418
                $data = (array) json_decode($data);
1419
                if(empty($data)) {
1420
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']) ;
1421
                    exit;
1422
                }
1423
 
1424
                $email      = trim(isset($data['email']) ? filter_var($data['email'], FILTER_SANITIZE_EMAIL) : '');
1425
                $first_name = trim(isset($data['first_name']) ? filter_var($data['first_name'], FILTER_SANITIZE_STRING) : '');
1426
                $last_name  = trim(isset($data['last_name']) ? filter_var($data['last_name'], FILTER_SANITIZE_STRING) : '');
1427
 
1428
                if(!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
1429
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']) ;
1430
                    exit;
1431
                }
1432
 
1433
                $userMapper = UserMapper::getInstance($this->adapter);
1434
                $user = $userMapper->fetchOneByEmail($email);
1435
                if(!$user) {
1436
 
1437
 
1438
                    $user = new User();
3649 efrain 1439
                    $user->network_id = $currentNetwork->id;
1 www 1440
                    $user->blocked = User::BLOCKED_NO;
1441
                    $user->email = $email;
1442
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1443
                    $user->first_name = $first_name;
1444
                    $user->last_name = $last_name;
1445
                    $user->login_attempt = 0;
1446
                    $user->password = '-NO-PASSWORD-';
1447
                    $user->usertype_id = UserType::USER;
1448
                    $user->status = User::STATUS_ACTIVE;
1449
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
1450
 
1451
                    if($userMapper->insert($user)) {
1452
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]) ;
1453
                        exit;
1454
                    }
1455
 
1456
 
1457
 
1458
 
1459
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
1460
                    $content    = trim(isset($data['avatar_content']) ? filter_var($data['avatar_content'], FILTER_SANITIZE_STRING) : '');
1461
 
1462
                    if($filename && $content) {
1463
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
1464
                        try {
1465
                            file_put_contents($source, base64_decode($content));
1466
                            if (file_exists($source)) {
1467
                                $target_path = $this->config['leaderslinked.fullpath.user'] . $user->uuid;
1468
                                list( $target_width, $target_height ) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
1469
 
1470
                                $target_filename    = 'user-' . uniqid() . '.png';
1471
                                $crop_to_dimensions = true;
1472
 
1473
                                if(!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
1474
                                    return new JsonModel([
1475
                                        'success'   => false,
1476
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1477
                                    ]);
1478
                                }
1479
 
1480
                                $user->image = $target_filename;
1481
                                $userMapper->updateImage($user);
1482
                            }
1483
                        } catch(\Throwable $e) {
1484
 
1485
                        } finally {
1486
                            if(file_exists($source)) {
1487
                                unlink($source);
1488
                            }
1489
                        }
1490
                    }
1491
 
1492
                }
1493
 
1494
                $auth = new AuthEmailAdapter($this->adapter);
1495
                $auth->setData($email);
1496
 
1497
                $result = $auth->authenticate();
1498
                if($result->getCode() == AuthResult::SUCCESS) {
1499
                    return $this->redirect()->toRoute('dashboard');
1500
 
1501
 
1502
                } else {
1503
                    $message = $result->getMessages()[0];
1504
                    if(!in_array($message, ['ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1505
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1506
                        'ERROR_ENTERED_PASS_INCORRECT_1'])) {
1507
 
1508
 
1509
                    }
1510
 
1511
                    switch($message)
1512
                    {
1513
                        case 'ERROR_USER_NOT_FOUND' :
1514
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1515
                            break;
1516
 
1517
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED' :
1518
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1519
                            break;
1520
 
1521
                        case 'ERROR_USER_IS_BLOCKED' :
1522
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1523
                            break;
1524
 
1525
                        case 'ERROR_USER_IS_INACTIVE' :
1526
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1527
                            break;
1528
 
1529
 
1530
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1531
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1532
                            break;
1533
 
1534
 
1535
                        case 'ERROR_ENTERED_PASS_INCORRECT_2' :
1536
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1537
                            break;
1538
 
1539
 
1540
                        case 'ERROR_ENTERED_PASS_INCORRECT_1' :
1541
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1542
                            break;
1543
 
1544
 
1545
                        default :
1546
                            $message = 'ERROR_UNKNOWN';
1547
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1548
                            break;
1549
 
1550
 
1551
                    }
1552
 
1553
 
1554
 
1555
 
1556
                    return new JsonModel( [
1557
                        'success'   => false,
1558
                        'data'   => $message
1559
                    ]);
1560
                }
1561
 
1562
 
1563
 
1564
 
1565
            } else {
1566
                $messages = [];
1567
 
1568
 
1569
 
1570
                $form_messages = (array) $form->getMessages();
1571
                foreach($form_messages  as $fieldname => $field_messages)
1572
                {
1573
 
1574
                    $messages[$fieldname] = array_values($field_messages);
1575
                }
1576
 
1577
                return new JsonModel([
1578
                    'success'   => false,
1579
                    'data'   => $messages
1580
                ]);
1581
            }
1582
 
1583
        } else {
1584
            $data = [
1585
                'success' => false,
1586
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1587
            ];
1588
 
1589
            return new JsonModel($data);
1590
        }
1591
 
1592
        return new JsonModel($data);
1593
    }
1594
 
210 efrain 1595
    public function csrfAction()
1596
    {
1597
        $request = $this->getRequest();
1598
        if($request->isGet()) {
1599
 
1600
            $token = md5(uniqid('CSFR-' . mt_rand(), true));
1601
            $_SESSION['token'] = $token;
1602
 
1603
 
1604
            return new JsonModel([
1605
                'success' => true,
1606
                'data' => $token
1607
            ]);
1608
 
1609
 
1610
        } else {
1611
            return new JsonModel([
1612
                'success' => false,
1613
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1614
            ]);
1615
        }
1616
 
1617
 
1618
    }
3639 efrain 1619
 
1620
    public function impersonateAction()
1621
    {
1622
        $request = $this->getRequest();
1623
        if($request->isGet()) {
1624
            $user_uuid  = filter_var($this->params()->fromQuery('user_uuid'), FILTER_SANITIZE_STRING);
1625
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
1626
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
1627
            $password   = filter_var($this->params()->fromQuery('password'), FILTER_SANITIZE_STRING);
1628
 
1629
 
1630
            if(!$user_uuid || !$rand || !$timestamp || !$password ) {
1631
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
1632
            }
1633
 
1634
 
3650 efrain 1635
            $currentUserPlugin = $this->plugin('currentUserPlugin');
3639 efrain 1636
            $currentUserPlugin->clearIdentity();
1637
 
1638
 
1639
            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
1640
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);
1641
 
1642
            $authService = new AuthenticationService();
1643
            $result = $authService->authenticate($authAdapter);
1644
 
1645
 
1646
            if($result->getCode() == AuthResult::SUCCESS) {
1647
                return $this->redirect()->toRoute('dashboard');
1648
            } else {
1649
                throw new \Exception($result->getMessages()[0]);
1650
            }
1651
        }
1652
 
1653
        return new JsonModel([
1654
            'success' => false,
1655
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1656
        ]);
1657
    }
1 www 1658
 
1659
}