Proyectos de Subversion LeadersLinked - Services

Rev

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