Proyectos de Subversion LeadersLinked - Services

Rev

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