Proyectos de Subversion LeadersLinked - Services

Rev

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