Proyectos de Subversion LeadersLinked - Services

Rev

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