Proyectos de Subversion LeadersLinked - Services

Rev

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