Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 4398 | Rev 4422 | 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'],
764
            ]);
765
 
766
            return $viewModel;
767
        }
768
 
769
 
770
 
771
        return new JsonModel([
772
            'success' => false,
773
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
774
        ]);
775
    }
776
 
777
    public function forgotPasswordAction()
778
    {
3650 efrain 779
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 780
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
781
 
782
 
783
 
1 www 784
        $request = $this->getRequest();
785
        if($request->isPost()) {
786
            $dataPost = $request->getPost()->toArray();
787
            if(empty($_SESSION['aes'])) {
788
                return new JsonModel([
789
                    'success'   => false,
790
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
791
                ]);
792
            }
793
 
794
            if(!empty( $dataPost['email'])) {
795
                $dataPost['email'] = CryptoJsAes::decrypt( $dataPost['email'], $_SESSION['aes']);
796
            }
797
 
798
            $form = new ForgotPasswordForm($this->config);
799
            $form->setData($dataPost);
800
 
801
            if($form->isValid()) {
802
                $dataPost = (array) $form->getData();
803
                $email      = $dataPost['email'];
804
 
805
                $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 806
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1 www 807
                if(!$user) {
808
                    $this->logger->err('Olvidó contraseña ' . $email . '- Email no existe ', ['ip' => Functions::getUserIP()]);
809
 
810
                    return new JsonModel([
811
                        'success' => false,
812
                        'data' =>  'ERROR_EMAIL_IS_NOT_REGISTERED'
813
                    ]);
814
                } else {
815
                    if($user->status == User::STATUS_INACTIVE) {
816
                        return new JsonModel([
817
                            'success' => false,
818
                            'data' =>  'ERROR_USER_IS_INACTIVE'
819
                        ]);
820
                    } else if ($user->email_verified == User::EMAIL_VERIFIED_NO) {
821
                        $this->logger->err('Olvidó contraseña - Email no verificado ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
822
 
823
                        return new JsonModel([
824
                            'success' => false,
825
                            'data' => 'ERROR_EMAIL_HAS_NOT_BEEN_VERIFIED'
826
                        ]);
827
                    } else {
828
                        $password_reset_key = md5($user->email. time());
829
                        $userMapper->updatePasswordResetKey((int) $user->id, $password_reset_key);
830
 
831
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3649 efrain 832
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RESET_PASSWORD, $currentNetwork->id);
1 www 833
                        if($emailTemplate) {
834
                            $arrayCont = [
835
                                'firstname'             => $user->first_name,
836
                                'lastname'              => $user->last_name,
837
                                'other_user_firstname'  => '',
838
                                'other_user_lastname'   => '',
839
                                'company_name'          => '',
840
                                'group_name'            => '',
841
                                'content'               => '',
842
                                'code'                  => '',
843
                                'link'                  => $this->url()->fromRoute('reset-password', ['code' => $password_reset_key], ['force_canonical' => true])
844
                            ];
845
 
846
                            $email = new QueueEmail($this->adapter);
847
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
848
                        }
849
                        $flashMessenger = $this->plugin('FlashMessenger');
850
                        $flashMessenger->addSuccessMessage('LABEL_RECOVERY_LINK_WAS_SENT_TO_YOUR_EMAIL');
851
 
852
                        $this->logger->info('Olvidó contraseña - Se envio link de recuperación ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
853
 
854
                        return new JsonModel([
855
                            'success' => true,
856
                        ]);
857
                    }
858
                }
859
 
860
            } else {
861
 
862
 
863
                $form_messages =  $form->getMessages('captcha');
864
 
865
 
866
 
867
                if(!empty($form_messages)) {
868
                    return new JsonModel([
869
                        'success'   => false,
870
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
871
                    ]);
872
                }
873
 
874
                $messages = [];
875
                $form_messages = (array) $form->getMessages();
876
                foreach($form_messages  as $fieldname => $field_messages)
877
                {
878
                    $messages[$fieldname] = array_values($field_messages);
879
                }
880
 
881
                return new JsonModel([
882
                    'success'   => false,
883
                    'data'      => $messages
884
                ]);
885
            }
886
        }
887
 
888
        /*
889
        if($request->isGet())  {
890
            if(empty($_SESSION['aes'])) {
891
                $_SESSION['aes'] = Functions::generatePassword(16);
892
            }
893
 
894
            if($this->config['leaderslinked.runmode.sandbox']) {
895
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
896
            } else {
897
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
898
            }
899
 
900
 
901
            $form = new ForgotPasswordForm($this->config);
902
 
903
            $this->layout()->setTemplate('layout/auth.phtml');
904
            $viewModel = new ViewModel();
905
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
906
            $viewModel->setVariables([
907
                'form' => $form,
908
                'site_key' => $site_key,
909
                'aes' => $_SESSION['aes'],
910
            ]);
911
 
912
            return $viewModel ;
913
        }
914
        */
915
 
916
        if($request->isGet())  {
917
 
918
            if(empty($_SESSION['aes'])) {
919
                $_SESSION['aes'] = Functions::generatePassword(16);
920
            }
921
 
922
            if($this->config['leaderslinked.runmode.sandbox']) {
923
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
924
            } else {
925
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
926
            }
927
 
928
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
929
            $remember   = $email ? true : false;
930
 
931
            $form = new SigninForm($this->config);
932
            $form->setData([
933
                'email'     => $email,
934
                'remember'  => $remember,
935
            ]);
936
            $this->layout()->setTemplate('layout/auth.phtml');
937
            $viewModel = new ViewModel();
938
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
939
            $viewModel->setVariables([
940
                'form'      =>  $form,
941
                'site_key'  => $site_key,
942
                'aes'       => $_SESSION['aes'],
943
            ]);
944
 
945
            return $viewModel ;
946
 
947
        }
948
 
949
        return new JsonModel([
950
            'success' => false,
951
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
952
        ]);
953
    }
954
 
955
    public function signupAction()
956
    {
3650 efrain 957
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 958
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
959
 
960
 
1 www 961
        $request = $this->getRequest();
962
        if($request->isPost()) {
963
            $dataPost = $request->getPost()->toArray();
964
 
965
            if(empty($_SESSION['aes'])) {
966
                return new JsonModel([
967
                    'success'   => false,
968
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
969
                ]);
970
            }
971
 
972
            if(!empty( $dataPost['email'])) {
973
                $dataPost['email'] = CryptoJsAes::decrypt( $dataPost['email'], $_SESSION['aes']);
974
            }
975
 
976
            if(!empty( $dataPost['password'])) {
977
                $dataPost['password'] = CryptoJsAes::decrypt( $dataPost['password'], $_SESSION['aes']);
978
            }
979
 
980
            if(!empty( $dataPost['confirmation'])) {
981
                $dataPost['confirmation'] = CryptoJsAes::decrypt( $dataPost['confirmation'], $_SESSION['aes']);
982
            }
983
 
4398 efrain 984
            if(empty($dataPost['is_adult'])) {
985
                $dataPost['is_adult'] = User::IS_ADULT_NO;
986
            } else {
987
                $dataPost['is_adult'] = $dataPost['is_adult'] == User::IS_ADULT_YES ? User::IS_ADULT_YES : User::IS_ADULT_NO;
988
            }
1 www 989
 
4398 efrain 990
 
991
 
1 www 992
            $form = new SignupForm($this->config);
993
            $form->setData($dataPost);
994
 
995
            if($form->isValid()) {
996
                $dataPost = (array) $form->getData();
997
 
998
                $email = $dataPost['email'];
999
 
1000
                $userMapper = UserMapper::getInstance($this->adapter);
3649 efrain 1001
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1 www 1002
                if($user) {
1003
                    $this->logger->err('Registro ' . $email . '- Email ya  existe ', ['ip' => Functions::getUserIP()]);
1004
 
1005
 
1006
 
1007
                    return new JsonModel([
1008
                        'success' => false,
1009
                        'data' => 'ERROR_EMAIL_IS_REGISTERED'
1010
                    ]);
1011
                } else {
3298 efrain 1012
 
3364 efrain 1013
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
1014
 
3298 efrain 1015
 
3364 efrain 1016
                    if($user_share_invitation) {
1017
                        $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
3298 efrain 1018
                        if($userRedirect && $userRedirect->status == User::STATUS_ACTIVE) {
1019
                            $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1020
 
1021
                            $user = new User();
3649 efrain 1022
                            $user->network_id           = $currentNetwork->id;
3298 efrain 1023
                            $user->email                = $dataPost['email'];
1024
                            $user->first_name           = $dataPost['first_name'];
1025
                            $user->last_name            = $dataPost['last_name'];
1026
                            $user->usertype_id          = UserType::USER;
1027
                            $user->password             = $password_hash;
1028
                            $user->password_updated_on  = date('Y-m-d H:i:s');
1029
                            $user->status               = User::STATUS_ACTIVE;
1030
                            $user->blocked              = User::BLOCKED_NO;
1031
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
1032
                            $user->login_attempt        = 0;
4398 efrain 1033
                            $user->is_adult             = $dataPost['is_adult'];
3298 efrain 1034
 
1035
 
1036
                            if($userMapper->insert($user)) {
1037
 
1038
                                $userPassword = new UserPassword();
1039
                                $userPassword->user_id = $user->id;
1040
                                $userPassword->password = $password_hash;
1041
 
1042
                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1043
                                $userPasswordMapper->insert($userPassword);
1044
 
1045
 
1046
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1047
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1048
 
1049
                                if($connection) {
1050
 
1051
                                    if($connection->status != Connection::STATUS_ACCEPTED) {
1052
                                        $connectionMapper->approve($connection);
1053
                                    }
1054
 
1055
                                } else {
1056
                                    $connection = new Connection();
1057
                                    $connection->request_from = $user->id;
1058
                                    $connection->request_to = $userRedirect->id;
1059
                                    $connection->status = Connection::STATUS_ACCEPTED;
1060
 
1061
                                    $connectionMapper->insert($connection);
1062
                                }
1063
 
1064
 
3364 efrain 1065
                                $this->cache->removeItem('user_share_invitation');
1066
 
3298 efrain 1067
 
1068
 
3364 efrain 1069
                                $data = [
1070
                                    'success'   => true,
1071
                                    'data'      => $this->url()->fromRoute('home'),
1072
                                ];
1073
 
3298 efrain 1074
 
1075
                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1076
 
1077
                                return new JsonModel($data);
1078
                            }
1079
                        }
1080
                    }
1081
 
1082
 
1083
 
1084
 
1 www 1085
                    $timestamp = time();
1086
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);
1087
 
1088
                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1089
 
1090
                    $user = new User();
3649 efrain 1091
                    $user->network_id           = $currentNetwork->id;
1 www 1092
                    $user->email                = $dataPost['email'];
1093
                    $user->first_name           = $dataPost['first_name'];
1094
                    $user->last_name            = $dataPost['last_name'];
1095
                    $user->usertype_id          = UserType::USER;
1096
                    $user->password             = $password_hash;
1097
                    $user->password_updated_on  = date('Y-m-d H:i:s');
1098
                    $user->activation_key       = $activation_key;
1099
                    $user->status               = User::STATUS_INACTIVE;
1100
                    $user->blocked              = User::BLOCKED_NO;
1101
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
1102
                    $user->login_attempt        = 0;
3671 efrain 1103
 
1 www 1104
 
1105
                    if($userMapper->insert($user)) {
1106
 
1107
                        $userPassword = new UserPassword();
1108
                        $userPassword->user_id = $user->id;
1109
                        $userPassword->password = $password_hash;
1110
 
1111
                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1112
                        $userPasswordMapper->insert($userPassword);
1113
 
1114
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
3649 efrain 1115
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
1 www 1116
                        if($emailTemplate) {
1117
                            $arrayCont = [
1118
                                'firstname'             => $user->first_name,
1119
                                'lastname'              => $user->last_name,
1120
                                'other_user_firstname'  => '',
1121
                                'other_user_lastname'   => '',
1122
                                'company_name'          => '',
1123
                                'group_name'            => '',
1124
                                'content'               => '',
1125
                                'code'                  => '',
3298 efrain 1126
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
1 www 1127
                            ];
1128
 
1129
                            $email = new QueueEmail($this->adapter);
1130
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1131
                        }
1132
                        $flashMessenger = $this->plugin('FlashMessenger');
1133
                        $flashMessenger->addSuccessMessage('LABEL_REGISTRATION_DONE');
1134
 
1135
                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1136
 
1137
                        return new JsonModel([
1138
                            'success' => true,
1139
                        ]);
1140
 
1141
                    } else {
1142
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);
1143
 
1144
                        return new JsonModel([
1145
                            'success' => false,
1146
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1147
                        ]);
1148
                    }
1149
                }
1150
 
1151
 
1152
 
1153
            } else {
1154
 
1155
                $form_messages =  $form->getMessages('captcha');
1156
                if(!empty($form_messages)) {
1157
                    return new JsonModel([
1158
                        'success'   => false,
1159
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1160
                    ]);
1161
                }
1162
 
1163
                $messages = [];
1164
 
1165
                $form_messages = (array) $form->getMessages();
1166
                foreach($form_messages  as $fieldname => $field_messages)
1167
                {
1168
                    $messages[$fieldname] = array_values($field_messages);
1169
                }
1170
 
1171
                return new JsonModel([
1172
                    'success'   => false,
1173
                    'data'   => $messages
1174
                ]);
1175
            }
1176
        }
1177
        /*
1178
        if($request->isGet())  {
1179
            if(empty($_SESSION['aes'])) {
1180
                $_SESSION['aes'] = Functions::generatePassword(16);
1181
            }
1182
 
1183
            if($this->config['leaderslinked.runmode.sandbox']) {
1184
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1185
            } else {
1186
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1187
            }
1188
 
1189
 
1190
            $form = new SignupForm($this->config);
1191
 
1192
            $this->layout()->setTemplate('layout/auth.phtml');
1193
            $viewModel = new ViewModel();
1194
            $viewModel->setTemplate('leaders-linked/auth/signup.phtml');
1195
            $viewModel->setVariables([
1196
                'form' => $form,
1197
                'site_key' => $site_key,
1198
                'aes' =>  $_SESSION['aes'],
1199
            ]);
1200
 
1201
            return $viewModel ;
1202
        } */
1203
 
1204
 
1205
        if($request->isGet())  {
1206
 
1207
            if(empty($_SESSION['aes'])) {
1208
                $_SESSION['aes'] = Functions::generatePassword(16);
1209
            }
1210
 
1211
            if($this->config['leaderslinked.runmode.sandbox']) {
1212
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1213
            } else {
1214
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1215
            }
1216
 
1217
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
1218
            $remember   = $email ? true : false;
1219
 
1220
            $form = new SigninForm($this->config);
1221
            $form->setData([
1222
                'email'     => $email,
1223
                'remember'  => $remember,
1224
            ]);
1225
            $this->layout()->setTemplate('layout/auth.phtml');
1226
            $viewModel = new ViewModel();
1227
            $viewModel->setTemplate('leaders-linked/auth/signin.phtml');
1228
            $viewModel->setVariables([
1229
                'form'      =>  $form,
1230
                'site_key'  => $site_key,
1231
                'aes'       => $_SESSION['aes'],
4419 efrain 1232
                'defaultNetwork' => $currentNetwork->default,
1 www 1233
            ]);
1234
 
1235
            return $viewModel ;
1236
 
1237
        }
1238
 
1239
        return new JsonModel([
1240
            'success' => false,
1241
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1242
        ]);
1243
 
1244
 
1245
    }
1246
 
1247
    public function activateAccountAction()
1248
    {
1249
 
3650 efrain 1250
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 1251
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1252
 
1253
 
1254
 
1 www 1255
        $request = $this->getRequest();
1256
        if($request->isGet()) {
1257
            $code   = filter_var($this->params()->fromRoute('code'), FILTER_SANITIZE_STRING);
1258
            $userMapper = UserMapper::getInstance($this->adapter);
3759 efrain 1259
            $user = $userMapper->fetchOneByActivationKeyAndNetworkId($code, $currentNetwork->id);
1 www 1260
 
1261
            $flashMessenger = $this->plugin('FlashMessenger');
1262
 
1263
            if($user) {
1264
                if(User::EMAIL_VERIFIED_YES == $user->email_verified) {
3671 efrain 1265
 
1 www 1266
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1267
 
1268
                    $flashMessenger->addErrorMessage('ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED');
1269
                } else {
3671 efrain 1270
 
1 www 1271
                    if($userMapper->activateAccount((int) $user->id)) {
3728 efrain 1272
 
1 www 1273
                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1274
 
1275
                        $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED');
3298 efrain 1276
 
3364 efrain 1277
                        $user_share_invitation = $this->cache->getItem('user_share_invitation');
3298 efrain 1278
 
3364 efrain 1279
                        if($user_share_invitation) {
1280
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
3298 efrain 1281
                            if($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
1282
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1283
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1284
 
1285
                                if($connection) {
1286
 
1287
                                    if($connection->status != Connection::STATUS_ACCEPTED) {
1288
                                        $connectionMapper->approve($connection);
1289
                                    }
1290
 
1291
                                } else {
1292
                                    $connection = new Connection();
1293
                                    $connection->request_from = $user->id;
1294
                                    $connection->request_to = $userRedirect->id;
1295
                                    $connection->status = Connection::STATUS_ACCEPTED;
1296
 
1297
                                    $connectionMapper->insert($connection);
1298
                                }
1299
                            }
1300
                        }
1301
 
3364 efrain 1302
 
3298 efrain 1303
 
3364 efrain 1304
                        $this->cache->removeItem('user_share_invitation');
3729 efrain 1305
 
3298 efrain 1306
 
1 www 1307
                    } else {
1308
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1309
 
1310
                        $flashMessenger->addErrorMessage('ERROR_THERE_WAS_AN_ERROR');
1311
                    }
1312
                }
1313
            } else {
1314
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);
1315
 
1316
                $flashMessenger->addErrorMessage('ERROR_ACTIVATION_CODE_IS_NOT_VALID');
1317
            }
1318
 
3729 efrain 1319
            return $this->redirect()->toRoute('home');
1320
 
1 www 1321
 
3298 efrain 1322
 
1 www 1323
        } else {
1324
            $response = [
1325
                'success' => false,
1326
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1327
            ];
1328
        }
1329
 
1330
        return new JsonModel($response);
1331
 
1332
    }
1333
 
1334
 
1335
 
1336
    public function onroomAction()
1337
    {
3650 efrain 1338
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
3649 efrain 1339
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1340
 
1341
 
1342
 
1 www 1343
        $request = $this->getRequest();
1344
 
1345
        if($request->isPost()) {
1346
 
1347
            $dataPost = $request->getPost()->toArray();
1348
 
1349
 
1350
            $form = new  MoodleForm();
1351
            $form->setData($dataPost);
1352
            if($form->isValid()) {
1353
 
1354
                $dataPost   = (array) $form->getData();
1355
                $username   = $dataPost['username'];
1356
                $password   = $dataPost['password'];
1357
                $timestamp  = $dataPost['timestamp'];
1358
                $rand       = $dataPost['rand'];
1359
                $data       = $dataPost['data'];
1360
 
1361
                $config_username    = $this->config['leaderslinked.moodle.username'];
1362
                $config_password    = $this->config['leaderslinked.moodle.password'];
1363
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1364
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
1365
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
1366
 
1367
 
1368
 
1369
 
1370
                if(empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1371
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']) ;
1372
                    exit;
1373
                }
1374
 
1375
                if($username != $config_username) {
1376
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']) ;
1377
                    exit;
1378
                }
1379
 
1380
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1381
                if(!$dt) {
1382
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']) ;
1383
                    exit;
1384
                }
1385
 
1386
                $t0 = $dt->getTimestamp();
1387
                $t1 = strtotime('-5 minutes');
1388
                $t2 = strtotime('+5 minutes');
1389
 
1390
                if($t0 < $t1 || $t0 > $t2) {
1391
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1392
                    //exit;
1393
                }
1394
 
1395
                if(!password_verify( $username.'-'. $config_password . '-' . $rand. '-' . $timestamp, $password)) {
1396
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']) ;
1397
                    exit;
1398
                }
1399
 
1400
                if(empty($data)) {
1401
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']) ;
1402
                    exit;
1403
                }
1404
 
1405
                $data = base64_decode($data);
1406
                if(empty($data)) {
1407
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']) ;
1408
                    exit;
1409
                }
1410
 
1411
 
1412
                try {
1413
                    $rsa = Rsa::getInstance();
1414
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1415
                } catch (\Throwable $e)
1416
                {
1417
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']) ;
1418
                    exit;
1419
                }
1420
 
1421
                $data = (array) json_decode($data);
1422
                if(empty($data)) {
1423
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']) ;
1424
                    exit;
1425
                }
1426
 
1427
                $email      = trim(isset($data['email']) ? filter_var($data['email'], FILTER_SANITIZE_EMAIL) : '');
1428
                $first_name = trim(isset($data['first_name']) ? filter_var($data['first_name'], FILTER_SANITIZE_STRING) : '');
1429
                $last_name  = trim(isset($data['last_name']) ? filter_var($data['last_name'], FILTER_SANITIZE_STRING) : '');
1430
 
1431
                if(!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
1432
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']) ;
1433
                    exit;
1434
                }
1435
 
1436
                $userMapper = UserMapper::getInstance($this->adapter);
1437
                $user = $userMapper->fetchOneByEmail($email);
1438
                if(!$user) {
1439
 
1440
 
1441
                    $user = new User();
3649 efrain 1442
                    $user->network_id = $currentNetwork->id;
1 www 1443
                    $user->blocked = User::BLOCKED_NO;
1444
                    $user->email = $email;
1445
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1446
                    $user->first_name = $first_name;
1447
                    $user->last_name = $last_name;
1448
                    $user->login_attempt = 0;
1449
                    $user->password = '-NO-PASSWORD-';
1450
                    $user->usertype_id = UserType::USER;
1451
                    $user->status = User::STATUS_ACTIVE;
1452
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
1453
 
1454
                    if($userMapper->insert($user)) {
1455
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]) ;
1456
                        exit;
1457
                    }
1458
 
1459
 
1460
 
1461
 
1462
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
1463
                    $content    = trim(isset($data['avatar_content']) ? filter_var($data['avatar_content'], FILTER_SANITIZE_STRING) : '');
1464
 
1465
                    if($filename && $content) {
1466
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
1467
                        try {
1468
                            file_put_contents($source, base64_decode($content));
1469
                            if (file_exists($source)) {
1470
                                $target_path = $this->config['leaderslinked.fullpath.user'] . $user->uuid;
1471
                                list( $target_width, $target_height ) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
1472
 
1473
                                $target_filename    = 'user-' . uniqid() . '.png';
1474
                                $crop_to_dimensions = true;
1475
 
1476
                                if(!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
1477
                                    return new JsonModel([
1478
                                        'success'   => false,
1479
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1480
                                    ]);
1481
                                }
1482
 
1483
                                $user->image = $target_filename;
1484
                                $userMapper->updateImage($user);
1485
                            }
1486
                        } catch(\Throwable $e) {
1487
 
1488
                        } finally {
1489
                            if(file_exists($source)) {
1490
                                unlink($source);
1491
                            }
1492
                        }
1493
                    }
1494
 
1495
                }
1496
 
1497
                $auth = new AuthEmailAdapter($this->adapter);
1498
                $auth->setData($email);
1499
 
1500
                $result = $auth->authenticate();
1501
                if($result->getCode() == AuthResult::SUCCESS) {
1502
                    return $this->redirect()->toRoute('dashboard');
1503
 
1504
 
1505
                } else {
1506
                    $message = $result->getMessages()[0];
1507
                    if(!in_array($message, ['ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1508
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1509
                        'ERROR_ENTERED_PASS_INCORRECT_1'])) {
1510
 
1511
 
1512
                    }
1513
 
1514
                    switch($message)
1515
                    {
1516
                        case 'ERROR_USER_NOT_FOUND' :
1517
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1518
                            break;
1519
 
1520
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED' :
1521
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1522
                            break;
1523
 
1524
                        case 'ERROR_USER_IS_BLOCKED' :
1525
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1526
                            break;
1527
 
1528
                        case 'ERROR_USER_IS_INACTIVE' :
1529
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1530
                            break;
1531
 
1532
 
1533
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1534
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1535
                            break;
1536
 
1537
 
1538
                        case 'ERROR_ENTERED_PASS_INCORRECT_2' :
1539
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1540
                            break;
1541
 
1542
 
1543
                        case 'ERROR_ENTERED_PASS_INCORRECT_1' :
1544
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1545
                            break;
1546
 
1547
 
1548
                        default :
1549
                            $message = 'ERROR_UNKNOWN';
1550
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1551
                            break;
1552
 
1553
 
1554
                    }
1555
 
1556
 
1557
 
1558
 
1559
                    return new JsonModel( [
1560
                        'success'   => false,
1561
                        'data'   => $message
1562
                    ]);
1563
                }
1564
 
1565
 
1566
 
1567
 
1568
            } else {
1569
                $messages = [];
1570
 
1571
 
1572
 
1573
                $form_messages = (array) $form->getMessages();
1574
                foreach($form_messages  as $fieldname => $field_messages)
1575
                {
1576
 
1577
                    $messages[$fieldname] = array_values($field_messages);
1578
                }
1579
 
1580
                return new JsonModel([
1581
                    'success'   => false,
1582
                    'data'   => $messages
1583
                ]);
1584
            }
1585
 
1586
        } else {
1587
            $data = [
1588
                'success' => false,
1589
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1590
            ];
1591
 
1592
            return new JsonModel($data);
1593
        }
1594
 
1595
        return new JsonModel($data);
1596
    }
1597
 
210 efrain 1598
    public function csrfAction()
1599
    {
1600
        $request = $this->getRequest();
1601
        if($request->isGet()) {
1602
 
1603
            $token = md5(uniqid('CSFR-' . mt_rand(), true));
1604
            $_SESSION['token'] = $token;
1605
 
1606
 
1607
            return new JsonModel([
1608
                'success' => true,
1609
                'data' => $token
1610
            ]);
1611
 
1612
 
1613
        } else {
1614
            return new JsonModel([
1615
                'success' => false,
1616
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1617
            ]);
1618
        }
1619
 
1620
 
1621
    }
3639 efrain 1622
 
1623
    public function impersonateAction()
1624
    {
1625
        $request = $this->getRequest();
1626
        if($request->isGet()) {
1627
            $user_uuid  = filter_var($this->params()->fromQuery('user_uuid'), FILTER_SANITIZE_STRING);
1628
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
1629
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
1630
            $password   = filter_var($this->params()->fromQuery('password'), FILTER_SANITIZE_STRING);
1631
 
1632
 
1633
            if(!$user_uuid || !$rand || !$timestamp || !$password ) {
1634
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
1635
            }
1636
 
1637
 
3650 efrain 1638
            $currentUserPlugin = $this->plugin('currentUserPlugin');
3639 efrain 1639
            $currentUserPlugin->clearIdentity();
1640
 
1641
 
1642
            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
1643
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);
1644
 
1645
            $authService = new AuthenticationService();
1646
            $result = $authService->authenticate($authAdapter);
1647
 
1648
 
1649
            if($result->getCode() == AuthResult::SUCCESS) {
1650
                return $this->redirect()->toRoute('dashboard');
1651
            } else {
1652
                throw new \Exception($result->getMessages()[0]);
1653
            }
1654
        }
1655
 
1656
        return new JsonModel([
1657
            'success' => false,
1658
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1659
        ]);
1660
    }
1 www 1661
 
1662
}