Proyectos de Subversion LeadersLinked - Services

Rev

Rev 119 | Rev 138 | 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,
877
                            'data'      => [
878
                                'message' => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED',
879
                                'redirect' => $this->url()->fromRoute('home'),
880
                            ],
881
 
882
                        ]);
883
                    } else {
884
                        $this->logger->err('Restablecer contraseña - Error desconocido', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
885
 
886
                        return new JsonModel([
887
                            'success'   => false,
888
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
889
 
890
                        ]);
891
                    }
892
                }
893
            } else {
894
                $form_messages =  $form->getMessages('captcha');
895
                if (!empty($form_messages)) {
896
                    return new JsonModel([
897
                        'success'   => false,
898
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
899
                    ]);
900
                }
901
 
902
                $messages = [];
903
 
904
                $form_messages = (array) $form->getMessages();
905
                foreach ($form_messages  as $fieldname => $field_messages) {
906
                    $messages[$fieldname] = array_values($field_messages);
907
                }
908
 
909
                return new JsonModel([
910
                    'success'   => false,
911
                    'data'   => $messages
912
                ]);
913
            }
914
        } else if ($request->isGet()) {
915
 
916
            if (empty($_SESSION['aes'])) {
917
                $_SESSION['aes'] = Functions::generatePassword(16);
918
            }
919
 
920
            if ($this->config['leaderslinked.runmode.sandbox']) {
921
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
922
            } else {
923
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
924
            }
925
 
926
 
927
            return new JsonModel([
928
                'code' => $code,
929
                'site_key' => $site_key,
930
                'aes'       => $_SESSION['aes'],
931
                'defaultNetwork' => $currentNetwork->default,
932
            ]);
933
 
934
        }
935
 
936
 
937
 
938
        return new JsonModel([
939
            'success' => false,
940
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
941
        ]);
942
    }
943
 
944
    public function forgotPasswordAction()
945
    {
946
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
947
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
948
 
949
 
950
 
951
        $request = $this->getRequest();
952
        if ($request->isPost()) {
953
            $dataPost = $request->getPost()->toArray();
954
            if (empty($_SESSION['aes'])) {
955
                return new JsonModel([
956
                    'success'   => false,
957
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
958
                ]);
959
            }
960
 
961
            if (!empty($dataPost['email'])) {
962
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
963
            }
964
 
965
            $form = new ForgotPasswordForm($this->config);
966
            $form->setData($dataPost);
967
 
968
            if ($form->isValid()) {
969
                $dataPost = (array) $form->getData();
970
                $email      = $dataPost['email'];
971
 
972
                $userMapper = UserMapper::getInstance($this->adapter);
973
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
974
                if (!$user) {
975
                    $this->logger->err('Olvidó contraseña ' . $email . '- Email no existe ', ['ip' => Functions::getUserIP()]);
976
 
977
                    return new JsonModel([
978
                        'success' => false,
979
                        'data' =>  'ERROR_EMAIL_IS_NOT_REGISTERED'
980
                    ]);
981
                } else {
982
                    if ($user->status == User::STATUS_INACTIVE) {
983
                        return new JsonModel([
984
                            'success' => false,
985
                            'data' =>  'ERROR_USER_IS_INACTIVE'
986
                        ]);
987
                    } else if ($user->email_verified == User::EMAIL_VERIFIED_NO) {
988
                        $this->logger->err('Olvidó contraseña - Email no verificado ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
989
 
990
                        return new JsonModel([
991
                            'success' => false,
992
                            'data' => 'ERROR_EMAIL_HAS_NOT_BEEN_VERIFIED'
993
                        ]);
994
                    } else {
995
                        $password_reset_key = md5($user->email . time());
996
                        $userMapper->updatePasswordResetKey((int) $user->id, $password_reset_key);
997
 
998
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
999
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RESET_PASSWORD, $currentNetwork->id);
1000
                        if ($emailTemplate) {
1001
                            $arrayCont = [
1002
                                'firstname'             => $user->first_name,
1003
                                'lastname'              => $user->last_name,
1004
                                'other_user_firstname'  => '',
1005
                                'other_user_lastname'   => '',
1006
                                'company_name'          => '',
1007
                                'group_name'            => '',
1008
                                'content'               => '',
1009
                                'code'                  => '',
1010
                                'link'                  => $this->url()->fromRoute('reset-password', ['code' => $password_reset_key], ['force_canonical' => true])
1011
                            ];
1012
 
1013
                            $email = new QueueEmail($this->adapter);
1014
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1015
                        }
1016
                        $flashMessenger = $this->plugin('FlashMessenger');
1017
                        $flashMessenger->addSuccessMessage('LABEL_RECOVERY_LINK_WAS_SENT_TO_YOUR_EMAIL');
1018
 
1019
                        $this->logger->info('Olvidó contraseña - Se envio link de recuperación ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1020
 
1021
                        return new JsonModel([
1022
                            'success' => true,
1023
                        ]);
1024
                    }
1025
                }
1026
            } else {
1027
 
1028
 
1029
                $form_messages =  $form->getMessages('captcha');
1030
 
1031
 
1032
 
1033
                if (!empty($form_messages)) {
1034
                    return new JsonModel([
1035
                        'success'   => false,
1036
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1037
                    ]);
1038
                }
1039
 
1040
                $messages = [];
1041
                $form_messages = (array) $form->getMessages();
1042
                foreach ($form_messages  as $fieldname => $field_messages) {
1043
                    $messages[$fieldname] = array_values($field_messages);
1044
                }
1045
 
1046
                return new JsonModel([
1047
                    'success'   => false,
1048
                    'data'      => $messages
1049
                ]);
1050
            }
1051
        } else  if ($request->isGet()) {
1052
 
1053
            if (empty($_SESSION['aes'])) {
1054
                $_SESSION['aes'] = Functions::generatePassword(16);
1055
            }
1056
 
1057
            if ($this->config['leaderslinked.runmode.sandbox']) {
1058
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1059
            } else {
1060
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1061
            }
1062
 
1063
            return new JsonModel([
1064
                'site_key'  => $site_key,
1065
                'aes'       => $_SESSION['aes'],
1066
                'defaultNetwork' => $currentNetwork->default,
1067
            ]);
1068
        }
1069
 
1070
        return new JsonModel([
1071
            'success' => false,
1072
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1073
        ]);
1074
    }
1075
 
1076
    public function signupAction()
1077
    {
1078
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1079
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1080
 
1081
 
1082
        $request = $this->getRequest();
1083
        if ($request->isPost()) {
1084
            $dataPost = $request->getPost()->toArray();
1085
 
1086
            if (empty($_SESSION['aes'])) {
1087
                return new JsonModel([
1088
                    'success'   => false,
1089
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
1090
                ]);
1091
            }
1092
 
1093
            if (!empty($dataPost['email'])) {
1094
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
1095
            }
1096
 
1097
            if (!empty($dataPost['password'])) {
1098
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
1099
            }
1100
 
1101
            if (!empty($dataPost['confirmation'])) {
1102
                $dataPost['confirmation'] = CryptoJsAes::decrypt($dataPost['confirmation'], $_SESSION['aes']);
1103
            }
1104
 
1105
            if (empty($dataPost['is_adult'])) {
1106
                $dataPost['is_adult'] = User::IS_ADULT_NO;
1107
            } else {
1108
                $dataPost['is_adult'] = $dataPost['is_adult'] == User::IS_ADULT_YES ? User::IS_ADULT_YES : User::IS_ADULT_NO;
1109
            }
1110
 
1111
 
1112
 
1113
            $form = new SignupForm($this->config);
1114
            $form->setData($dataPost);
1115
 
1116
            if ($form->isValid()) {
1117
                $dataPost = (array) $form->getData();
1118
 
1119
                $email = $dataPost['email'];
1120
 
1121
                $userMapper = UserMapper::getInstance($this->adapter);
1122
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
1123
                if ($user) {
1124
                    $this->logger->err('Registro ' . $email . '- Email ya  existe ', ['ip' => Functions::getUserIP()]);
1125
 
1126
 
1127
 
1128
                    return new JsonModel([
1129
                        'success' => false,
1130
                        'data' => 'ERROR_EMAIL_IS_REGISTERED'
1131
                    ]);
1132
                } else {
1133
 
1134
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
1135
 
1136
 
1137
                    if ($user_share_invitation) {
1138
                        $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
1139
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE) {
1140
                            $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1141
 
1142
                            $user = new User();
1143
                            $user->network_id           = $currentNetwork->id;
1144
                            $user->email                = $dataPost['email'];
1145
                            $user->first_name           = $dataPost['first_name'];
1146
                            $user->last_name            = $dataPost['last_name'];
1147
                            $user->usertype_id          = UserType::USER;
1148
                            $user->password             = $password_hash;
1149
                            $user->password_updated_on  = date('Y-m-d H:i:s');
1150
                            $user->status               = User::STATUS_ACTIVE;
1151
                            $user->blocked              = User::BLOCKED_NO;
1152
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
1153
                            $user->login_attempt        = 0;
1154
                            $user->is_adult             = $dataPost['is_adult'];
1155
                            $user->request_access       = User::REQUEST_ACCESS_APPROVED;
1156
 
1157
 
1158
 
1159
 
1160
 
1161
                            if ($userMapper->insert($user)) {
1162
 
1163
                                $userPassword = new UserPassword();
1164
                                $userPassword->user_id = $user->id;
1165
                                $userPassword->password = $password_hash;
1166
 
1167
                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1168
                                $userPasswordMapper->insert($userPassword);
1169
 
1170
 
1171
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1172
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1173
 
1174
                                if ($connection) {
1175
 
1176
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1177
                                        $connectionMapper->approve($connection);
1178
                                    }
1179
                                } else {
1180
                                    $connection = new Connection();
1181
                                    $connection->request_from = $user->id;
1182
                                    $connection->request_to = $userRedirect->id;
1183
                                    $connection->status = Connection::STATUS_ACCEPTED;
1184
 
1185
                                    $connectionMapper->insert($connection);
1186
                                }
1187
 
1188
 
1189
                                $this->cache->removeItem('user_share_invitation');
1190
 
1191
 
1192
 
1193
                                $data = [
1194
                                    'success'   => true,
1195
                                    'data'      => $this->url()->fromRoute('home'),
1196
                                ];
1197
 
1198
 
1199
                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1200
 
1201
                                return new JsonModel($data);
1202
                            }
1203
                        }
1204
                    }
1205
 
1206
 
1207
 
1208
 
1209
                    $timestamp = time();
1210
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);
1211
 
1212
                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);
1213
 
1214
                    $user = new User();
1215
                    $user->network_id           = $currentNetwork->id;
1216
                    $user->email                = $dataPost['email'];
1217
                    $user->first_name           = $dataPost['first_name'];
1218
                    $user->last_name            = $dataPost['last_name'];
1219
                    $user->usertype_id          = UserType::USER;
1220
                    $user->password             = $password_hash;
1221
                    $user->password_updated_on  = date('Y-m-d H:i:s');
1222
                    $user->activation_key       = $activation_key;
1223
                    $user->status               = User::STATUS_INACTIVE;
1224
                    $user->blocked              = User::BLOCKED_NO;
1225
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
1226
                    $user->login_attempt        = 0;
1227
 
1228
                    if ($currentNetwork->default == Network::DEFAULT_YES) {
1229
                        $user->request_access = User::REQUEST_ACCESS_APPROVED;
1230
                    } else {
1231
                        $user->request_access = User::REQUEST_ACCESS_PENDING;
1232
                    }
1233
 
1234
 
1235
 
1236
                    if ($userMapper->insert($user)) {
1237
 
1238
                        $userPassword = new UserPassword();
1239
                        $userPassword->user_id = $user->id;
1240
                        $userPassword->password = $password_hash;
1241
 
1242
                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1243
                        $userPasswordMapper->insert($userPassword);
1244
 
1245
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1246
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
1247
                        if ($emailTemplate) {
1248
                            $arrayCont = [
1249
                                'firstname'             => $user->first_name,
1250
                                'lastname'              => $user->last_name,
1251
                                'other_user_firstname'  => '',
1252
                                'other_user_lastname'   => '',
1253
                                'company_name'          => '',
1254
                                'group_name'            => '',
1255
                                'content'               => '',
1256
                                'code'                  => '',
1257
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
1258
                            ];
1259
 
1260
                            $email = new QueueEmail($this->adapter);
1261
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1262
                        }
1263
                        $flashMessenger = $this->plugin('FlashMessenger');
1264
                        $flashMessenger->addSuccessMessage('LABEL_REGISTRATION_DONE');
1265
 
1266
                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1267
 
1268
                        return new JsonModel([
1269
                            'success' => true,
1270
                        ]);
1271
                    } else {
1272
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);
1273
 
1274
                        return new JsonModel([
1275
                            'success' => false,
1276
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
1277
                        ]);
1278
                    }
1279
                }
1280
            } else {
1281
 
1282
                $form_messages =  $form->getMessages('captcha');
1283
                if (!empty($form_messages)) {
1284
                    return new JsonModel([
1285
                        'success'   => false,
1286
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
1287
                    ]);
1288
                }
1289
 
1290
                $messages = [];
1291
 
1292
                $form_messages = (array) $form->getMessages();
1293
                foreach ($form_messages  as $fieldname => $field_messages) {
1294
                    $messages[$fieldname] = array_values($field_messages);
1295
                }
1296
 
1297
                return new JsonModel([
1298
                    'success'   => false,
1299
                    'data'   => $messages
1300
                ]);
1301
            }
1302
        } else if ($request->isGet()) {
1303
 
1304
            if (empty($_SESSION['aes'])) {
1305
                $_SESSION['aes'] = Functions::generatePassword(16);
1306
            }
1307
 
1308
            if ($this->config['leaderslinked.runmode.sandbox']) {
1309
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
1310
            } else {
1311
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
1312
            }
1313
 
1314
            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';
1315
 
1316
            return new JsonModel([
1317
                'site_key'  => $site_key,
1318
                'aes'       => $_SESSION['aes'],
1319
                'defaultNetwork' => $currentNetwork->default,
1320
            ]);
1321
        }
1322
 
1323
        return new JsonModel([
1324
            'success' => false,
1325
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1326
        ]);
1327
    }
1328
 
1329
    public function activateAccountAction()
1330
    {
1331
 
1332
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1333
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1334
 
1335
 
1336
 
1337
        $request = $this->getRequest();
1338
        if ($request->isGet()) {
1339
            $code   =  Functions::sanitizeFilterString($this->params()->fromRoute('code'));
1340
            $userMapper = UserMapper::getInstance($this->adapter);
1341
            $user = $userMapper->fetchOneByActivationKeyAndNetworkId($code, $currentNetwork->id);
1342
 
1343
            $flashMessenger = $this->plugin('FlashMessenger');
1344
 
1345
            if ($user) {
1346
                if (User::EMAIL_VERIFIED_YES == $user->email_verified) {
1347
 
1348
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1349
 
1350
                    $flashMessenger->addErrorMessage('ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED');
1351
                } else {
1352
 
1353
                    if ($userMapper->activateAccount((int) $user->id)) {
1354
 
1355
                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1356
 
1357
 
1358
 
1359
                        $user_share_invitation = $this->cache->getItem('user_share_invitation');
1360
 
1361
                        if ($user_share_invitation) {
1362
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
1363
                            if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
1364
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1365
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
1366
 
1367
                                if ($connection) {
1368
 
1369
                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
1370
                                        $connectionMapper->approve($connection);
1371
                                    }
1372
                                } else {
1373
                                    $connection = new Connection();
1374
                                    $connection->request_from = $user->id;
1375
                                    $connection->request_to = $userRedirect->id;
1376
                                    $connection->status = Connection::STATUS_ACCEPTED;
1377
 
1378
                                    $connectionMapper->insert($connection);
1379
                                }
1380
                            }
1381
                        }
1382
 
1383
 
1384
 
1385
                        $this->cache->removeItem('user_share_invitation');
1386
 
1387
 
1388
                        if ($currentNetwork->default == Network::DEFAULT_YES) {
1389
                            $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED');
1390
                        } else {
1391
 
1392
                            $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1393
                            $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_REQUEST_ACCESS_PENDING, $currentNetwork->id);
1394
 
1395
                            if ($emailTemplate) {
1396
                                $arrayCont = [
1397
                                    'firstname'             => $user->first_name,
1398
                                    'lastname'              => $user->last_name,
1399
                                    'other_user_firstname'  => '',
1400
                                    'other_user_lastname'   => '',
1401
                                    'company_name'          => '',
1402
                                    'group_name'            => '',
1403
                                    'content'               => '',
1404
                                    'code'                  => '',
1405
                                    'link'                  => '',
1406
                                ];
1407
 
1408
                                $email = new QueueEmail($this->adapter);
1409
                                $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1410
                            }
1411
 
1412
 
1413
                            $flashMessenger->addSuccessMessage('LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED_WE_ARE_VERIFYING_YOUR_INFORMATION');
1414
                        }
1415
                    } else {
1416
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
1417
 
1418
                        $flashMessenger->addErrorMessage('ERROR_THERE_WAS_AN_ERROR');
1419
                    }
1420
                }
1421
            } else {
1422
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);
1423
 
1424
                $flashMessenger->addErrorMessage('ERROR_ACTIVATION_CODE_IS_NOT_VALID');
1425
            }
1426
 
1427
            return $this->redirect()->toRoute('home');
1428
        } else {
1429
            $response = [
1430
                'success' => false,
1431
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1432
            ];
1433
        }
1434
 
1435
        return new JsonModel($response);
1436
    }
1437
 
1438
 
1439
 
1440
    public function onroomAction()
1441
    {
1442
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
1443
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
1444
 
1445
 
1446
 
1447
        $request = $this->getRequest();
1448
 
1449
        if ($request->isPost()) {
1450
 
1451
            $dataPost = $request->getPost()->toArray();
1452
 
1453
 
1454
            $form = new  MoodleForm();
1455
            $form->setData($dataPost);
1456
            if ($form->isValid()) {
1457
 
1458
                $dataPost   = (array) $form->getData();
1459
                $username   = $dataPost['username'];
1460
                $password   = $dataPost['password'];
1461
                $timestamp  = $dataPost['timestamp'];
1462
                $rand       = $dataPost['rand'];
1463
                $data       = $dataPost['data'];
1464
 
1465
                $config_username    = $this->config['leaderslinked.moodle.username'];
1466
                $config_password    = $this->config['leaderslinked.moodle.password'];
1467
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
1468
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
1469
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
1470
 
1471
 
1472
 
1473
 
1474
                if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
1475
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
1476
                    exit;
1477
                }
1478
 
1479
                if ($username != $config_username) {
1480
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
1481
                    exit;
1482
                }
1483
 
1484
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
1485
                if (!$dt) {
1486
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
1487
                    exit;
1488
                }
1489
 
1490
                $t0 = $dt->getTimestamp();
1491
                $t1 = strtotime('-5 minutes');
1492
                $t2 = strtotime('+5 minutes');
1493
 
1494
                if ($t0 < $t1 || $t0 > $t2) {
1495
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
1496
                    //exit;
1497
                }
1498
 
1499
                if (!password_verify($username . '-' . $config_password . '-' . $rand . '-' . $timestamp, $password)) {
1500
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
1501
                    exit;
1502
                }
1503
 
1504
                if (empty($data)) {
1505
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
1506
                    exit;
1507
                }
1508
 
1509
                $data = base64_decode($data);
1510
                if (empty($data)) {
1511
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
1512
                    exit;
1513
                }
1514
 
1515
 
1516
                try {
1517
                    $rsa = Rsa::getInstance();
1518
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
1519
                } catch (\Throwable $e) {
1520
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
1521
                    exit;
1522
                }
1523
 
1524
                $data = (array) json_decode($data);
1525
                if (empty($data)) {
1526
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
1527
                    exit;
1528
                }
1529
 
1530
                $email      = isset($data['email']) ? Functions::sanitizeFilterString($data['email']) : '';
1531
                $first_name = isset($data['first_name']) ? Functions::sanitizeFilterString($data['first_name']) : '';
1532
                $last_name  = isset($data['last_name']) ? Functions::sanitizeFilterString($data['last_name']) : '';
1533
 
1534
                if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
1535
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']);
1536
                    exit;
1537
                }
1538
 
1539
                $userMapper = UserMapper::getInstance($this->adapter);
1540
                $user = $userMapper->fetchOneByEmail($email);
1541
                if (!$user) {
1542
 
1543
 
1544
                    $user = new User();
1545
                    $user->network_id = $currentNetwork->id;
1546
                    $user->blocked = User::BLOCKED_NO;
1547
                    $user->email = $email;
1548
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
1549
                    $user->first_name = $first_name;
1550
                    $user->last_name = $last_name;
1551
                    $user->login_attempt = 0;
1552
                    $user->password = '-NO-PASSWORD-';
1553
                    $user->usertype_id = UserType::USER;
1554
                    $user->status = User::STATUS_ACTIVE;
1555
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
1556
 
1557
                    if ($userMapper->insert($user)) {
1558
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]);
1559
                        exit;
1560
                    }
1561
 
1562
 
1563
 
1564
 
1565
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
1566
                    $content    = isset($data['avatar_content']) ? Functions::sanitizeFilterString($data['avatar_content']) : '';
1567
 
1568
                    if ($filename && $content) {
1569
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
1570
                        try {
1571
                            file_put_contents($source, base64_decode($content));
1572
                            if (file_exists($source)) {
1573
                                $target_path = $this->config['leaderslinked.fullpath.user'] . $user->uuid;
1574
                                list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
1575
 
1576
                                $target_filename    = 'user-' . uniqid() . '.png';
1577
                                $crop_to_dimensions = true;
1578
 
1579
                                if (!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
1580
                                    return new JsonModel([
1581
                                        'success'   => false,
1582
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
1583
                                    ]);
1584
                                }
1585
 
1586
                                $user->image = $target_filename;
1587
                                $userMapper->updateImage($user);
1588
                            }
1589
                        } catch (\Throwable $e) {
1590
                        } finally {
1591
                            if (file_exists($source)) {
1592
                                unlink($source);
1593
                            }
1594
                        }
1595
                    }
1596
                }
1597
 
1598
                $auth = new AuthEmailAdapter($this->adapter);
1599
                $auth->setData($email);
1600
 
1601
                $result = $auth->authenticate();
1602
                if ($result->getCode() == AuthResult::SUCCESS) {
1603
                    return $this->redirect()->toRoute('dashboard');
1604
                } else {
1605
                    $message = $result->getMessages()[0];
1606
                    if (!in_array($message, [
1607
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
1608
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
1609
                        'ERROR_ENTERED_PASS_INCORRECT_1'
1610
                    ])) {
1611
                    }
1612
 
1613
                    switch ($message) {
1614
                        case 'ERROR_USER_NOT_FOUND':
1615
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
1616
                            break;
1617
 
1618
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
1619
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
1620
                            break;
1621
 
1622
                        case 'ERROR_USER_IS_BLOCKED':
1623
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1624
                            break;
1625
 
1626
                        case 'ERROR_USER_IS_INACTIVE':
1627
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
1628
                            break;
1629
 
1630
 
1631
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
1632
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
1633
                            break;
1634
 
1635
 
1636
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
1637
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
1638
                            break;
1639
 
1640
 
1641
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
1642
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
1643
                            break;
1644
 
1645
 
1646
                        default:
1647
                            $message = 'ERROR_UNKNOWN';
1648
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
1649
                            break;
1650
                    }
1651
 
1652
 
1653
 
1654
 
1655
                    return new JsonModel([
1656
                        'success'   => false,
1657
                        'data'   => $message
1658
                    ]);
1659
                }
1660
            } else {
1661
                $messages = [];
1662
 
1663
 
1664
 
1665
                $form_messages = (array) $form->getMessages();
1666
                foreach ($form_messages  as $fieldname => $field_messages) {
1667
 
1668
                    $messages[$fieldname] = array_values($field_messages);
1669
                }
1670
 
1671
                return new JsonModel([
1672
                    'success'   => false,
1673
                    'data'   => $messages
1674
                ]);
1675
            }
1676
        } else {
1677
            $data = [
1678
                'success' => false,
1679
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1680
            ];
1681
 
1682
            return new JsonModel($data);
1683
        }
1684
 
1685
        return new JsonModel($data);
1686
    }
1687
 
1688
    public function csrfAction()
1689
    {
1690
        $request = $this->getRequest();
1691
        if ($request->isGet()) {
95 efrain 1692
 
1693
            $jwtToken = null;
1694
            $headers = getallheaders();
1695
 
1696
 
1697
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
1698
 
1699
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
1700
 
1701
 
1702
                if (substr($token, 0, 6 ) == 'Bearer') {
1703
 
1704
                    $token = trim(substr($token, 7));
1705
 
1706
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
1707
                        $key = $this->config['leaderslinked.jwt.key'];
1708
 
1709
 
1710
                        try {
1711
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
1712
 
1713
 
1714
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
1715
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
1716
                            }
1717
 
1718
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
1719
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
1720
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
1721
                            if(!$jwtToken) {
1722
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
1723
                            }
1724
 
1725
                        } catch(\Exception $e) {
1726
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
1727
                        }
1728
                    } else {
1729
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
1730
                    }
1731
                } else {
1732
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
1733
                }
1734
            } else {
1735
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
1736
            }
1737
 
1738
            $jwtToken->csrf = md5(uniqid('CSFR-' . mt_rand(), true));
1739
            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
1740
            $jwtTokenMapper->update($jwtToken);
100 efrain 1741
 
1742
 
106 efrain 1743
           // error_log('token id = ' . $jwtToken->id . ' csrf = ' . $jwtToken->csrf);
1 efrain 1744
 
1745
 
1746
            return new JsonModel([
1747
                'success' => true,
99 efrain 1748
                'data' => $jwtToken->csrf
1 efrain 1749
            ]);
1750
        } else {
1751
            return new JsonModel([
1752
                'success' => false,
1753
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1754
            ]);
1755
        }
1756
    }
1757
 
1758
    public function impersonateAction()
1759
    {
1760
        $request = $this->getRequest();
1761
        if ($request->isGet()) {
1762
            $user_uuid  = Functions::sanitizeFilterString($this->params()->fromQuery('user_uuid'));
1763
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
1764
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
1765
            $password   = Functions::sanitizeFilterString($this->params()->fromQuery('password'));
1766
 
1767
 
1768
            if (!$user_uuid || !$rand || !$timestamp || !$password) {
1769
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
1770
            }
1771
 
1772
 
1773
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1774
            $currentUserPlugin->clearIdentity();
1775
 
1776
 
1777
            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
1778
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);
1779
 
1780
            $authService = new AuthenticationService();
1781
            $result = $authService->authenticate($authAdapter);
1782
 
1783
 
1784
            if ($result->getCode() == AuthResult::SUCCESS) {
1785
                return $this->redirect()->toRoute('dashboard');
1786
            } else {
1787
                throw new \Exception($result->getMessages()[0]);
1788
            }
1789
        }
1790
 
1791
        return new JsonModel([
1792
            'success' => false,
1793
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1794
        ]);
1795
    }
119 efrain 1796
 
1797
    public function autologinAction()
1798
    {
1799
        $email = 'santiago.olivera@leaderslinked.com';
1800
        $network_id = 1;
1801
 
1802
        $authAdapter = new AuthEmailAdapter($this->adapter);
1803
        $authAdapter->setData($email, $network_id);
1804
 
1805
        $authService = new AuthenticationService();
1806
        $result = $authService->authenticate($authAdapter);
1807
 
1808
 
1809
        if ($result->getCode() == AuthResult::SUCCESS) {
1810
            return $this->redirect()->toRoute('dashboard');
1811
        } else {
1812
            throw new \Exception($result->getMessages()[0]);
1813
        }
1814
 
1815
 
1816
    }
1 efrain 1817
}