Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 16824 | Rev 16954 | 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;
5
 
6
use Laminas\Db\Adapter\AdapterInterface;
7
use Laminas\ModuleManager\ModuleEvent;
8
use Laminas\ModuleManager\ModuleManager;
9
use Laminas\Mvc\MvcEvent;
10
use Laminas\Config\Reader\Ini;
11
use Laminas\Permissions\Acl\Acl;
15343 efrain 12
use LeadersLinked\Plugin\CurrentNetworkPlugin;
1 www 13
use LeadersLinked\Plugin\CurrentUserPlugin;
14
use LeadersLinked\Model\Company;
15
use LeadersLinked\Mapper\UserMapper;
16
use Laminas\Permissions\Acl\Resource\GenericResource;
17
use Laminas\Permissions\Acl\Role\GenericRole;
18
use LeadersLinked\Mapper\CompanyUserMapper;
19
use LeadersLinked\Mapper\CompanyUserRoleMapper;
20
use LeadersLinked\Mapper\RoleMapper;
21
use LeadersLinked\Mapper\CompanyServiceMapper;
15343 efrain 22
use LeadersLinked\Model\Network;
1 www 23
use LeadersLinked\Model\Service;
15088 efrain 24
use LeadersLinked\Model\User;
25
use LeadersLinked\Model\UserType;
26
use LeadersLinked\Model\CompanyService;
27
use LeadersLinked\Model\CompanyUser;
15343 efrain 28
use LeadersLinked\Mapper\CompanyMapper;
15355 efrain 29
use LeadersLinked\Mapper\ApplicationVariantMapper;
1 www 30
 
16823 efrain 31
 
32
 
33
 
1 www 34
class Module
35
{
36
    /**
37
     *
38
     * @var boolean
39
     */
40
    private $isJson;
41
 
42
    /**
43
     *
44
     * @var boolean
45
     */
46
    private $isHtml;
47
 
48
    /**
49
     *
50
     * @var Acl
51
     */
52
    private $acl;
53
 
54
    /**
55
     *
56
     * @var Company
57
     */
58
    private $company;
59
 
60
    /**
61
     *
62
     * @var AdapterInterface
63
     */
64
    private $adapter;
16768 efrain 65
 
1 www 66
 
67
    /**
68
     *
69
     * @var CurrentUserPlugin
70
     */
15343 efrain 71
    private $currentUserPlugin;
1 www 72
 
73
 
15343 efrain 74
 
1 www 75
    /**
15343 efrain 76
     *
77
     * @var CurrentNetworkPlugin
78
     */
79
    private $currentNetworkPlugin;
16824 efrain 80
 
15343 efrain 81
    /**
1 www 82
     *
83
     * @var array
84
     */
85
    private $routesAuthorized = [];
86
 
87
    /**
88
     *
89
     * @var boolean
90
     */
91
    private $authByHeaders = false;
92
 
93
    public function init(ModuleManager $moduleManager)
94
    {
95
        $events = $moduleManager->getEventManager();
96
        $events->attach(ModuleEvent::EVENT_MERGE_CONFIG, array($this, 'onMergeConfig'));
97
    }
98
 
99
    public function onMergeConfig(ModuleEvent $event)
100
    {
101
        $configListener = $event->getConfigListener();
102
        $config         = $configListener->getMergedConfig(false);
103
 
104
        $reader = new Ini();
105
        $data = $reader->fromFile('config/leaderslinked.ini');
106
 
107
        $prefix = 'leaderslinked';
108
        foreach($data as $section => $pairs)
109
        {
110
            foreach($pairs as $key => $value)
111
            {
112
                $config[$prefix . '.' . $section . '.' . $key] = $value;
113
            }
114
        }
115
        $configListener->setMergedConfig($config);
116
    }
117
 
118
 
119
    public function getConfig() : array
120
    {
121
        return include __DIR__ . '/../config/module.config.php';
122
    }
123
 
124
    public function onBootstrap(MvcEvent $event)
125
    {
126
        $serviceManager = $event->getApplication()->getServiceManager();
127
        $adapter = $serviceManager->get('leaders-linked-db');
128
       // $logger          = $serviceManager->get('Zend\Log\Logger');
129
 
130
 
131
        $session = $serviceManager->get('leaders-linked-session');
132
        $session->start();
133
 
134
 
135
        $translator = $serviceManager->get('MvcTranslator');
136
        $translator->addTranslationFile(
137
            'phpArray',
138
            __DIR__ . '/i18n/validate.php',
139
            'default'
140
            );
141
 
142
        $translator->addTranslationFile(
143
            'phpArray',
144
            __DIR__ . '/i18n/spanish.php',
145
            'default'
146
            );
147
 
148
        \Laminas\Validator\AbstractValidator::setDefaultTranslator($translator);
149
 
15343 efrain 150
 
151
        $this->currentNetworkPlugin = new CurrentNetworkPlugin($adapter);
152
        if(!$this->currentNetworkPlugin->hasNetwork()) {
153
            header("HTTP/1.1 401 Unauthorized - Private network - not found");
154
            exit;
155
        }
156
 
157
        if($this->currentNetworkPlugin->getNetwork()->status == Network::STATUS_INACTIVE) {
158
            header("HTTP/1.1 401 Unauthorized - Private network - inactive");
159
            exit;
160
        }
161
 
162
 
163
 
164
        if(empty($_SERVER['REDIRECT_URL'])) {
165
            if(empty($_SERVER['REQUEST_URI'])) {
166
                $routeName = '';
167
 
168
            } else {
169
                $routeName = $_SERVER['REQUEST_URI'];
170
            }
171
 
172
        } else {
173
            $routeName = $_SERVER['REDIRECT_URL'];
174
 
175
        }
176
 
177
 
178
        $routeName = strtolower(trim($routeName));
179
        if(strlen($routeName) > 0 && substr($routeName, 0, 1) == '/') {
180
            $routeName = substr($routeName, 1);
181
        }
182
 
183
 
184
 
185
        $this->isHtml = $this->isJson ? false : true;
186
        $this->currentUserPlugin = new CurrentUserPlugin($adapter);
187
 
188
 
189
 
190
        if($this->currentUserPlugin->hasIdentity()) {
191
            if(in_array($routeName, ['signout', 'signin-admin', 'signin-company', 'home'])) {
192
                $checkUserForNetwork = false;
193
            } else {
194
                $checkUserForNetwork = true;
195
            }
196
        } else {
197
            $checkUserForNetwork = false;
198
        }
199
 
200
 
201
 
1 www 202
 
15343 efrain 203
 
204
 
205
        if($checkUserForNetwork) {
206
            if($this->currentUserPlugin->getUser()->network_id != $this->currentNetworkPlugin->getNetworkId()) {
207
                header("HTTP/1.1 401 Unauthorized - The user is not part of this private network");
208
                exit;
209
            }
210
        }
211
 
1 www 212
        $this->initAcl($event);
213
        $eventManager = $event->getApplication()->getEventManager();
214
        $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, [$this,'onDispatchError'], 0);
215
        $eventManager->attach(MvcEvent::EVENT_RENDER_ERROR, [$this,'onRenderError'], 0);
216
 
217
        $sharedManager = $eventManager->getSharedManager();
218
        $sharedManager->attach(__NAMESPACE__, MvcEvent::EVENT_DISPATCH, [$this, 'authPreDispatch'], 100);
219
        $sharedManager->attach(__NAMESPACE__, MvcEvent::EVENT_DISPATCH, [$this, 'authPosDispatch'], -100);
220
    }
221
 
222
    public function initAcl(MvcEvent $event)
223
    {
224
        $serviceManager = $event->getApplication()->getServiceManager();
225
        $adapter = $serviceManager->get('leaders-linked-db');
226
 
227
        require_once   (dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'acl.config.php');
228
 
15088 efrain 229
        //header('Content-type: text/plain');
1 www 230
 
231
        $this->acl = new Acl();
232
        $resources = getAclResources();
233
        foreach($resources as $resourceName)
234
        {
15088 efrain 235
           //echo $resourceName . PHP_EOL;
1 www 236
 
237
            $this->acl->addResource(new GenericResource($resourceName));
238
        }
239
 
15088 efrain 240
 
241
 
1 www 242
 
15343 efrain 243
        $rolesForUsertype = getAclRolesForUsertype();
15088 efrain 244
 
1 www 245
 
15088 efrain 246
 
15343 efrain 247
        $user = $this->currentUserPlugin->getUser();
248
        $company = $this->currentUserPlugin->getCompany();
249
        $network = $this->currentNetworkPlugin->getNetwork();
1 www 250
        if($company) {
251
 
15088 efrain 252
            $resources = [];
1 www 253
 
15088 efrain 254
 
1 www 255
            $this->acl->addRole(new GenericRole($user->usertype_id));
256
 
15092 efrain 257
 
15088 efrain 258
            foreach($rolesForUsertype[UserType::USER] as $resourceName)
259
            {
260
                if(!in_array($resourceName, $resources)) {
261
                    array_push($resources, $resourceName);
262
                }
263
            }
264
 
265
 
266
            $servicesActive = [];
267
            $now = date('Y-m-d');
15448 efrain 268
 
15088 efrain 269
            $companyServiceMapper = CompanyServiceMapper::getInstance($adapter);
270
            $companyServices = $companyServiceMapper->fetchAllByCompanyId($company->id);
271
 
272
            foreach($companyServices as $companyService)
273
            {
15448 efrain 274
                if($companyService->status == CompanyService::ACTIVE) {
15088 efrain 275
 
15448 efrain 276
                    $paid_from = trim(substr($companyService->paid_from, 0, 10));
277
                    $paid_to = trim(substr($companyService->paid_to, 0, 10));
278
 
279
                    if($now >= $paid_from   && $now <= $paid_to) {
280
                        if(!in_array($companyService->id, $servicesActive)) {
281
                            array_push($servicesActive, $companyService->service_id);
282
                        }
15088 efrain 283
                    }
15448 efrain 284
                }
15088 efrain 285
            }
286
 
287
            $rolesForCompany = getAclRolesCompany();
1 www 288
            $companyUserMapper = CompanyUserMapper::getInstance($adapter);
289
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($company->id, $user->id);
15088 efrain 290
 
291
            $roleMapper = RoleMapper::getInstance($adapter);
292
            if($companyUser) {
1 www 293
 
15088 efrain 294
                if($companyUser->creator == CompanyUser::CREATOR_YES) {
295
 
15355 efrain 296
 
297
 
298
                    $applicationVariantMapper = ApplicationVariantMapper::getInstance($adapter);
299
                    $total = $applicationVariantMapper->fetchCountActiveByCompanyId($company->id);
300
 
301
                    if($total > 0) {
302
 
303
                        $resourceNames = getAclPermissionPushTemplatesForCustomApps();
304
 
305
                        foreach($resourceNames as $resourceName)
306
                        {
307
                            if(!in_array($resourceName, $resources)) {
308
                                array_push($resources, $resourceName);
309
                            }
310
                        }
311
 
312
                    }
313
 
314
 
15088 efrain 315
                    $roles = $roleMapper->fetchAllForCreator();
316
                    if($roles) {
317
 
318
                        foreach($roles as $role)
1 www 319
                        {
15088 efrain 320
                            if(!empty($rolesForCompany[$role->code])) {
321
                                foreach($rolesForCompany[$role->code] as $resourceName) {
322
 
323
                                    if(!in_array($resourceName, $resources)) {
324
                                        array_push($resources, $resourceName);
325
                                    }
326
                                }
327
                            }
1 www 328
                        }
329
                    }
330
 
15088 efrain 331
 
332
                    foreach ($servicesActive as $service_id) {
333
                        $roles = $roleMapper->fetchAllByServiceId($service_id);
15371 efrain 334
 
335
 
15088 efrain 336
                        foreach($roles as $role) {
337
 
338
 
339
                            if(!empty($rolesForCompany[$role->code])) {
340
                                foreach($rolesForCompany[$role->code] as $resourceName) {
341
 
342
                                    if(!in_array($resourceName, $resources)) {
343
                                        array_push($resources, $resourceName);
344
                                    }
345
                                }
346
                            }
347
 
348
 
349
 
1 www 350
                        }
15088 efrain 351
 
1 www 352
                    }
15088 efrain 353
                } else {
354
                    $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($adapter);
355
                    $companyUserRoles = $companyUserRoleMapper->fetchAllByCompanyIdAndUserId($company->id, $user->id);
356
 
15343 efrain 357
 
358
 
15088 efrain 359
                    foreach($companyUserRoles as $companyUserRole)
360
                    {
959 geraldo 361
 
15088 efrain 362
                         $role = $roleMapper->fetchOne($companyUserRole->role_id);
15343 efrain 363
 
15088 efrain 364
                         if($role) {
365
 
366
                             if($role->service_id) {
367
 
15343 efrain 368
                                 if(!in_array($role->service_id, $servicesActive)) {
369
                                    continue;
370
                                 }
15088 efrain 371
                             }
372
 
15343 efrain 373
                             if(isset($rolesForCompany[ $role->code ] )) {
374
                                 foreach($rolesForCompany[ $role->code ] as $resourceName)
375
                                 {
376
                                     if(!in_array($resourceName, $resources)) {
377
                                        array_push($resources, $resourceName);
378
                                     }
379
 
15088 efrain 380
                                 }
15343 efrain 381
                            }
382
                        }
959 geraldo 383
 
15088 efrain 384
 
959 geraldo 385
                    }
1 www 386
                }
15088 efrain 387
            }
15355 efrain 388
 
15088 efrain 389
 
974 geraldo 390
 
15088 efrain 391
            foreach($resources as $resourceName)
392
            {
393
                $this->acl->allow($user->usertype_id, $resourceName);
1 www 394
            }
395
 
15088 efrain 396
        }   else {
1 www 397
 
15088 efrain 398
 
399
            foreach($rolesForUsertype as $usertype => $resources)
1 www 400
            {
401
                $this->acl->addRole(new GenericRole($usertype));
402
                foreach ($resources as $resourceName)
403
                {
15088 efrain 404
                    // echo $resourceName . PHP_EOL;
1 www 405
                    $this->acl->allow($usertype, $resourceName);
406
                }
407
            }
15343 efrain 408
 
409
 
410
            if($this->currentUserPlugin->hasIdentity()) {
411
                $user = $this->currentUserPlugin->getUser();
412
 
413
                if($user->is_super_user == User::IS_SUPER_USER_YES) {
414
                    $resources = getAclPermissionSuperAdmin();
415
                    foreach ($resources as $resourceName)
416
                    {
417
                        $this->acl->allow(UserType::ADMIN, $resourceName);
418
                    }
419
                }
420
            }
421
 
422
            if($this->company == null) {
423
 
424
                if($network->default == Network::DEFAULT_YES) {
425
                    $resources = getAclPermissionAdminForDefaultNetwork();
426
                    foreach ($resources as $resourceName)
427
                    {
428
                        $this->acl->allow(UserType::ADMIN, $resourceName);
429
                    }
430
                } else {
431
 
432
                    $companyMapper = CompanyMapper::getInstance($adapter);
433
                    $company = $companyMapper->fetchDefaultForNetworkByNetworkId($network->id);
434
                    if($company) {
15346 efrain 435
                        $companyUserMapper = CompanyUserMapper::getInstance($adapter);
15343 efrain 436
                        $companyUser = $companyUserMapper->fetchCreatorByCompanyId($company->id);
437
                        if($companyUser && $companyUser->user_id == $this->currentUserPlugin->getUserId()) {
438
 
439
                            $resources = getAclPermissionAdminForNonDefaultNetwork();
440
                            foreach ($resources as $resourceName)
441
                            {
442
                                $this->acl->allow(UserType::ADMIN, $resourceName);
443
                            }
444
 
445
                        }
446
                    }
447
 
448
 
449
                }
450
            }
1 www 451
        }
452
        $event->getViewModel()->setVariable('acl', $this->acl);
453
    }
454
 
455
    public function onDispatchError(MvcEvent $event)
456
    {
457
        $this->processError($event);
458
    }
459
 
460
    public function onRenderError(MvcEvent $event)
461
    {
462
        $this->processError($event);
463
    }
464
 
465
    public function sendResponse(\Laminas\Http\Response $response, $data)
466
    {
467
 
468
 
469
        if($this->isJson) {
470
            $headers = $response->getHeaders();
471
            $headers->clearHeaders();
472
            $headers->addHeaderLine('Content-type', 'application/json; charset=UTF-8');
473
 
474
            $response->setStatusCode(200);
475
            $response->setContent(json_encode($data));
476
            $response->send();
477
 
478
 
479
        } else {
15348 efrain 480
           // print_r($data); exit;
481
 
1 www 482
            throw new \Exception($data['data']);
483
        }
484
        exit;
485
    }
486
 
487
    public function processError(MvcEvent $event)
488
    {
489
 
490
 
491
        $request =  $event->getRequest();
492
        if((method_exists($request, 'isXmlHttpRequest') && $request->isXmlHttpRequest()) || ($this->isJson && !$this->isHtml)) {
493
 
16785 efrain 494
 
495
 
1 www 496
            $error = $event->getError();
497
            if (!$error) {
498
                return;
499
            }
16785 efrain 500
 
1 www 501
 
502
            $response = $event->getResponse();
503
 
504
            if('error-exception' == $error) {
505
                $exception = $event->getParam('exception');
506
                error_log($exception->getCode() . ' ' . $exception->getMessage());
507
                //error_log($exception->getTraceAsString());
508
 
509
 
510
                $data = [
511
                    'success' => false,
512
                    'data' => 'An error occurred during execution; please try again later.'
513
                ];
514
 
515
            } else if('error-router-no-match' == $error) {
516
                $data = [
517
                    'success' => false,
518
                    'data' => 'Resource not found.'
519
 
520
                ];
521
            } else if(' error-controller-not-found' == $error) {
522
                $data = [
523
                    'success' => false,
524
                    'data' => 'Controller not found.'
525
 
526
                ];
527
            } else {
528
                $data = [
529
                    'success' => false,
530
                    'data' => 'Unknow error.' , 'error' => $error
531
 
532
                ];
533
            }
534
 
535
 
536
 
537
            $this->sendResponse($response, $data);
538
        }
539
 
540
        $this->initAcl($event);
541
    }
542
 
543
 
544
    public function authPreDispatch(MvcEvent $event)
545
    {
546
        $serviceManager = $event->getApplication()->getServiceManager();
547
        $adapter = $serviceManager->get('leaders-linked-db');
548
 
15343 efrain 549
        $userTypeId = $this->currentUserPlugin->getUserTypeId();
1 www 550
 
551
 
552
 
553
 
554
        $routeName = $event->getRouteMatch()->getMatchedRouteName();
555
 
556
 
557
 
558
        if($this->acl->isAllowed($userTypeId, $routeName)) {
15343 efrain 559
            $user = $this->currentUserPlugin->getUser();
1 www 560
 
14689 efrain 561
            if($user) {
562
 
563
 
564
                $updateLastActivity = true;
565
                if ('chat' == substr($routeName, 0, 4)) {
566
                    $updateLastActivity = false;
567
                }
568
                if ('inmail' == substr($routeName, 0, 6)) {
569
                    $updateLastActivity = false;
570
                }
571
                if ('check-session' == $routeName) {
572
                    $updateLastActivity = false;
573
                }
574
 
575
 
576
                if($updateLastActivity) {
577
                    $userMapper = UserMapper::getInstance($adapter);
578
                    $userMapper->updateLastActivity($user->id);
579
                }
14628 efrain 580
            }
1 www 581
 
582
        } else {
14690 efrain 583
 
16927 efrain 584
 
15343 efrain 585
            $this->currentUserPlugin->clearIdentity();
1 www 586
 
587
 
588
            if($this->isJson) {
589
                $response = $event->getResponse();
590
                $headers = $response->getHeaders();
591
                $headers->clearHeaders();
592
                $headers->addHeaderLine('Content-type', 'application/json; charset=UTF-8');
593
 
594
                $response->setStatusCode(200);
595
                $response->setContent(json_encode(['success' => false, 'data' => 'Unauthorized.', 'fatal' => true]));
596
                $response->send();
597
            } else {
598
                $url = $event->getRouter()->assemble([], ['name' => 'signout']);
599
 
600
                $response = $event->getResponse();
601
                $headers = $response->getHeaders();
602
                $headers->clearHeaders();
603
                $headers->addHeaderLine('Location', $url);
604
 
605
                $response->setStatusCode(302);
606
                $response->send();
607
            }
608
            exit;
609
        }
610
 
611
 
612
    }
613
 
614
 
615
    public function authPosDispatch(MvcEvent $event)
616
    {
617
 
618
    }
619
 
620
 
621
}