Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 4419 | Rev 4458 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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