AccessControl.php 2.72 KB
<?php

namespace backend\components\filters;

use Yii;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;

/**
 *
 * @author wuxiao
 * @date 2016-8-19
 */
class AccessControl extends \yii\filters\AccessControl
{
    
    /**
     * @var array a list of access rule objects or configuration arrays for creating the rule objects.
     * If a rule is specified via a configuration array, it will be merged with [[ruleConfig]] first
     * before it is used for creating the rule object.
     * @see ruleConfig
     */
    public $rules = [
        [
            'allow' => true,
            'roles' => ['@'],
        ],
    ];
    
    public function init()
    {
        $rules = [];
        
        /**
         * 验证用户访问权限
         */
        $route = Yii::$app->controller->id.'/'.Yii::$app->controller->action->id;
        if (!self::verifyAccess($route)){
            $rules = [['allow'=>false]];
        }
        
        $this->rules = ArrayHelper::merge($rules, $this->rules);
        
        $this->denyCallback = function ($rule, $action) {
            if (Yii::$app->user->getIsGuest()) {
                Yii::$app->user->loginRequired();
            } else {
                //throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
                Yii::$app->response->content = Yii::$app->view->render('@app/views/site/403',['_refer'=>Yii::$app->request->referrer]);
                Yii::$app->response->send();
                Yii::$app->end(1);
            }
        };
        parent::init();
    }
    
    /**
     * 验证用户访问权限
     * @param type $permission 权限标签
     * @return boolean
     */
    static function verifyAccess($permissionName)
    {
        /**
         * 首先判断具有强制通过验证权限
         */
        if (self::forceAccess() === true){
            return true;
        }
        
        return Yii::$app->authManager->checkAccess(Yii::$app->user->getId(), $permissionName);
    }
    
    /**
     * 判断是否具有强制通过验证权限
     * @staticvar type $forceAccess
     * @return boolean
     */
    static function forceAccess()
    {
        static $forceAccess;
        if ($forceAccess === null)
        {
            if (isset(Yii::$app->params['verifyAccess']) && !Yii::$app->params['verifyAccess'])
            {
                $forceAccess = true;
            }elseif (in_array(Yii::$app->user->getId(),Yii::$app->authManager->getUserIdsByRole('admin'))){
                $forceAccess = true;
            }else{
                $forceAccess = false;
            }
        }
        return $forceAccess;
    }
    
    public function beforeAction($action)
    {
        return parent::beforeAction($action);
    }
}