Create AccessRules in modules Yii Framework

2019-09-09 16:51发布

in modules\administrator\components\AdminController:

class AdminController extends CController
{
    public function filters()
    {
        return array('accessControl');
    }

    public function accessRules()
    {
        return array(
            array('deny', 'users' => array('*')),
        );
    }
}

in modules\administrator\controllers\Sitecontroller:

class SiteController extends AdminController
{
    public function actionIndex()
    {
        $this->render('index');
    }

        public function actionLogin()
        {
                $this->render('login');
        }
}

but when visit mydomain.site/administrator/site/index, it does not redirect to mydomain.site/administrator/site/login which redirects to mydomain.site/site/login (default login), I want it redirects to mydomain.site/administrator/site/login

can someone help me?

标签: yii
2条回答
等我变得足够好
2楼-- · 2019-09-09 17:15

Set CWebUser::$loginUrl before filters are invoked:

class AdminModule extends CWebModule
{
 public function init()
  {
   $this->setImport(array(
    'admin.models.*',
   //'application.models.*',
    'admin.components.*',
  ));
 }

 public function beforeControllerAction($controller, $action)
 {
  if(parent::beforeControllerAction($controller, $action))
 {
  // this method is called before any module controller action is performed
   // you may place customized code here
 if ( !Yii::app()->user->checkAccess('admin') ) {
 if(Yii::app()->user->isGuest){
  $url = Yii::app()->createUrl(Yii::app()->user->loginUrl);
 Yii::app()->user->returnUrl = Yii::app()->createUrl('/admin/');
 Yii::app()->request->redirect($url);
}
 else {
  throw new CHttpException(403,'Have no permission');
 }
 }
 return true;
 }
 else
 return false;
 }
}
查看更多
放荡不羁爱自由
3楼-- · 2019-09-09 17:27

Try this:

array('allow', // allow authenticated user to perform below actions
      'actions'=>array('index'),
      'users'=>array('@'),
), 
array('deny',  // deny all users
      'users'=>array('*'),
),

This way, when the url is requested for site/index and as we have set index to be allowed only for authenticated users, the request will be redirected to site/login (or default login).

I hope it helps.

查看更多
登录 后发表回答