Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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