Proyectos de Subversion LeadersLinked - Services

Rev

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