Completed
Push — master ( 2e8683...7e20fc )
by Igor
07:20
created

Module::getUserPermissions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 0
1
<?php
2
3
namespace app\modules\admin;
4
5
use Yii;
6
use yii\web\ForbiddenHttpException;
7
8
class Module extends \yii\base\Module
9
{
10
    public $controllerNamespace = 'app\modules\admin\controllers';
11
    public $defaultRoute = 'index/index';
12
    public $layout = 'admin';
13
    public $permissions = [];
14
15
    public function init()
16
    {
17
        parent::init();
18
19
        if (Yii::$app->user->isGuest === false) {
20
            $this->permissions = $this->getUserPermissions();
21
        }
22
23
        Yii::$app->user->loginUrl = ['admin/index/login'];
24
    }
25
26
    public function beforeAction($action)
27
    {
28
        if (parent::beforeAction($action)) {
29
            return $this->checkAccess($action);
30
        }
31
        return false;
32
    }
33
34
    public function checkAccess($action)
35
    {
36
        if ($action->controller->id === 'index') {
37
            return true;
38
        }
39
40
        if (!\Yii::$app->user->can('AdminModule') ||
41
            !\Yii::$app->user->can($this->getCurrentPermissionName($action))
42
        ) {
43
            throw new ForbiddenHttpException(Yii::t('app', 'Access Denied'));
44
        }
45
46
        return true;
47
    }
48
49
    private function getCurrentPermissionName($action)
50
    {
51
        return 'ACTION_Admin' . ucfirst($action->controller->id);
52
    }
53
54
    private function getUserPermissions()
55
    {
56
        $authManager = Yii::$app->authManager;
57
58
        if (Yii::$app->user->identity->isSuperUser() === false) {
59
            return $authManager->getPermissionsByRole(Yii::$app->user->identity->role);
60
        }
61
62
        return Yii::$app->cache->getOrSet('rbac-permissions',
63
        function () use ($authManager) {
64
            return $authManager->getPermissions();
65
        });
66
    }
67
}
68