Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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