Proyectos de Subversion LeadersLinked - Services

Rev

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