Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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