Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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