Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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