Proyectos de Subversion LeadersLinked - Services

Rev

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