Proyectos de Subversion LeadersLinked - Services

Rev

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