Completed
Push — master ( 5b873e...d824de )
by Alexey
02:27
created

AccessBehavior::events()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace modules\rbac\components\behavior;
4
5
use Yii;
6
use yii\base\Behavior;
7
use yii\console\Controller;
8
use modules\rbac\Module;
9
10
/**
11
 * Class AccessBehavior
12
 * @package modules\rbac\components\behavior
13
 */
14
class AccessBehavior extends Behavior
15
{
16
    /**
17
     * @var string
18
     */
19
    public $permission = '';
20
21
    /**
22
     * @var string
23
     */
24
    public $role = '';
25
26
    /**
27
     * @inheritdoc
28
     * @return array
29
     */
30
    public function events()
31
    {
32
        return [
33
            Controller::EVENT_BEFORE_ACTION => 'accessAction'
34
        ];
35
    }
36
37
    /**
38
     * @inheritdoc
39
     */
40
    public function accessAction()
41
    {
42
        if (($this->checkPermission() === false) && ($this->checkRole() === false)) {
43
            $this->processLogout();
44
        }
45
    }
46
47
    /**
48
     * @return bool
49
     */
50
    protected function checkPermission()
51
    {
52
        if (!empty($this->permission)) {
53
            if (Yii::$app->user->can($this->permission)) {
54
                return true;
55
            }
56
        }
57
        return false;
58
    }
59
60
    /**
61
     * @return bool
62
     */
63
    protected function checkRole()
64
    {
65
        if (!empty($this->role)) {
66
            if (Yii::$app->user->can($this->role)) {
67
                return true;
68
            }
69
        }
70
        return false;
71
    }
72
73
    /**
74
     * Logout and set Flash message
75
     */
76
    private function processLogout()
77
    {
78
        if (!Yii::$app->user->isGuest) {
79
            Yii::$app->user->logout();
80
            Yii::$app->session->setFlash('error', Module::t('module', 'You are not allowed access!'));
81
        }
82
    }
83
}
84