Proyectos de Subversion LeadersLinked - Services

Rev

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