Proyectos de Subversion LeadersLinked - Services

Rev

Rev 120 | Rev 144 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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