Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

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