Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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