Yii使用filter进行访问控制
Yii使用filter进行访问控制
作者:zccst
在Controller.php
注:filters是yii的CController.php中定义的方法,而Controller.php是继承CController.php的。此处,相当于覆盖父类中的filters方法。而所有的XXController.php又继承自Controller.php,显然都可以定义authlessActions()方法覆盖父类中相应方法。
public function filterAccessAuth($filterChain) {if(Yii::app()->user->getIsGuest() && !in_array($this->getAction()->getId(), $this->authlessActions())) {Yii::app()->user->setFlash("info", "请先登录");Yii::app()->user->loginRequired(); //封装了Yii::app()->user->loginUrl}elseif(!in_array($this->getAction()->getId(), $this->authlessActions()) && $this->current_user && $this->current_user->isPasswordExpired()) {$this->user->setFlash('error', "你的密码已经过期,超过: " . Yii::app()->params['user_pwd_max_expire_day'] . "天没有修改,请修改密码");$this->redirect($this->createUrl("/account/profile"));}if(!in_array($this->getAction()->getId(), $this->authlessActions()) && $this->current_user && $this->current_user->hi_id == NULL) {$target_url = $this->createUrl('account/profile');$this->user->setFlash('info', "你还没有设置Hi,请尽快到" . "<a href="$target_url"> 账号设置 </a>" . "添加!");}$filterChain->run();}public function filters() {return array('accessAuth',);}public function authlessActions() {return array();}
class PostController extends CController{......public function accessRules(){return array(rray('deny','actions'=>array('create', 'edit'),'users'=>array('?'),),array('allow','actions'=>array('delete'),'roles'=>array('admin'),),array('deny','actions'=>array('delete'),'users'=>array('*'),),);}}
if(isset($_POST['LoginForm'])){$model->attributes=$_POST['LoginForm'];// validate user input and redirect to the previous page if validif($model->validate() && $model->login()) {//初始化前,先初始化父类Controller.php的成员变量和成员函数。$this->init();// 检查上次密码修改时间if($this->current_user->isPasswordExpired()) {$this->user->setFlash('error', "密码已经" . Yii::app()->params['user_pwd_max_expire_day'] . "天没有修改过了,请修改密码");$this->redirect($this->createUrl("/account/profile"));}// 检查有没有设置Hiif($this->current_user->hi_id == NULL) {$target_url = $this->createUrl('account/profile');$this->user->setFlash('info', "你还没有设置Hi,请尽快到"."<a href="$target_url"> 账号设置 </a>"."添加!");}$this->redirect(Yii::app()->user->returnUrl);}}
if(Yii::app()->user->getIsGuest() && !in_array($this->getAction()->getId(), $this->authlessActions())) {Yii::app()->user->setFlash("info", "请先登录");Yii::app()->user->loginRequired(); //封装了Yii::app()->user->loginUrl}