Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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