Proyectos de Subversion LeadersLinked - Services

Rev

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

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