Monday, August 20, 2012

Creating User Access Levels for Forum Application Software Yii Framework

One of the important things in an application is a user-level access. User level access is a categorization of user permissions based on the user level. For example, we only allow a user with admin level making new news, allowing members who are logged in to make a new thread, and others. The first thing you should create is a user-level process to determine who is doing the activity in our application. In the "protected/components/" create a file with the extension ". Php" with the name "EwebUser.php". Then enter the following code in the file:
<?php
class EWebUser extends CWebUser{
    protected $_model;
    protected function loadUser()
    { 
        if ( $this->_model === null ) { 
            $this->_model = User::model()->findByPk($this->id); 
        }
        return $this->_model; 
    } 
    function getLevel() 
    { 
        $user=$this->loadUser(); 
        if($user) 
            return $user->level_id; 
        return 100; 
    } 
}
The above code CWebUser lower class that exist in Yii. In the above code getLevel function () will return the currently logged on user level from the table "Users" to attribute "level_id". After making the above code, we can restrict certain functions based on levels like the following example:
public function accessRules()
{
 return array(
  array('allow',
   'actions'=>array('index','view'), 
   'users'=>array('*'), 
  ),
  array('allow',
   'actions'=>array('create','update'), 
   'users'=>array('@'),
  ),
  array('allow',
   'actions'=>array('admin','delete'), 
   'expression'=>'$user->getLevel()<=1',
  ), 
  array('deny', 
   'users'=>array('*'),
  ),
 );
 }
The above code allows the index action and views accessible to all the good people who are logged in or not. Create and update action can only be accessed by users who are logged. Admin and delete action can only be accessed by users who have a level value <= 1. Level value itself will be taken from the user table. In this application level_id attribute will be connected to the attribute level that existed at the table level and level 1 a user with admin type. Now, using these methods you can define your own rules of access levels each. For this application we would have to adjust to the needs of our application.

In addition to set an access level, we can also use to set the user access level access to a view. For example if login with admin level would show made A, whereas if login with normal user level would show made B. Here's an example of its use
if(Yii::app()->user->getLevel()<=2)
{
 echo "it";
}
else
{
 echo "this";
}

6 comments:

Yii Framework Tutorials