Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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