Tuesday, October 21, 2014

Restrict access to a page without using accessRules (admin only) in yii

In this tutorial i will show you how to restrict diffrent types of access to a page without using accessRules().
In my example. I am going to edit my PostController.php, comment out some array in our accessRules, follow the codes below.
/**
 * Specifies the access control rules.
 * This method is used by the 'accessControl' filter.
 * @return array access control rules
 */
public function accessRules()
{
 return array(
  // array('allow',  // allow all users to perform 'index' and 'view' actions
   // 'actions'=>array('index','view'),
   // 'users'=>array('*'),
  // ),
  // array('allow', // allow authenticated user to perform 'create' and 'update' actions
   // 'actions'=>array('create','update'),
   // 'users'=>array('@'),
  // ),
  // array('allow', // allow admin user to perform 'admin' and 'delete' actions
   // 'actions'=>array('admin','delete'),
   // 'users'=>array('admin'),
  // ),
  array('allow',  // deny all users
   'users'=>array('*'),
  ),
 );
}

in PostController or any controller, we just need to insert this line of code to the controller function that we are going to restrict. note that you can change Yii::app()->user->role_id depending on the id that you are going to validate. In my example, i already set an session variable role_id after i login.
public function actionIndex()
{
 if(isset(Yii::app()->user->role_id)){
  if (Yii::app()->user->role_id != 1) {
   throw new CHttpException(403, 'You have no permission to view this content');
  }
 }else{  
  throw new CHttpException(403, 'You have no permission to view this content'); 
 }   
 
 // some codes ..... 
}
DRY , we dont want to repeat ourself from typing this line of code again and again so we will put it in a custom class. Check this tutorial for more clarification about creating custom class Create custom class and function in yii
class CustomClass 
{ 
 //level 1 = admin 
 public function adminOnly() { 
  if(isset(Yii::app()->user->role_id)){
   if (Yii::app()->user->role_id != 1) {
    throw new CHttpException(403, 'You have no permission to view this content');
   }
  }else{  
   throw new CHttpException(403, 'You have no permission to view this content'); 
  }  
 } 
}
in PostController, we just need to insert this line of code.
public function actionIndex()
{
 CustomClass::adminOnly();   
 // some codes ..... 
}
Now our index page is restricted to admin only. It will only allow user to view the index page with a role id of 1.Note that you need to put this code CustomClass::adminOnly(); to any page that you want to restrict.

The advantage of using class is it lessen our time on writing tons codes again and again. Updating the code is also easy since we are only going to update our main function and it will be applied to the rest.

No comments:

Post a Comment