Get The Role Of Currently Logged In User

Hi,

There is a function that tells whether a user is a Guest or not that is:


Yii::app()->user->isGuest

Is there any method by which I can get the role of currently logged in user?

I override CWebUser class and add few new methods

I created new class Web user in protected/modules/user/components




class WebUser extends CWebUser

{




    // Store model to not repeat query.

    private static $_model;

...

    function getUserRole(){

        $user = $this->loadUser(Yii::app()->user->id);

        if ($user == NULL) {

            return FALSE;

        }

        return $user->role_id;

    }

    // Load user model.

    protected function loadUser($id = NULL)

    {

        if (self::$_model === NULL) {

            if ($id !== NULL)

                self::$_model = User::getUserById($id);

        }

        return self::$_model;

    }

}



Also you must change your user settings in main config.php




        'user' => array(

            // enable cookie-based authentication

            'class' => 'application.modules.user.components.WebUser',

            'allowAutoLogin' => true,

            'loginUrl' => array('/auth/login', 'auto' => 1),

        ),



Than you can get user role with


Yii::app()->user->getUserRole()

If you’re using the built in auth manager, you can use this to get all of the user’s roles:




Yii::app()->authManager->getRoles($userId);



See here.

If you use the yii right extension, you just need create a function called getUserRoles() in the class RWebUser that extends from CWebUser, this class is under the path:

YouYiiRootPathprotected/modules/rights/components/RWebUser.php

this is the code of the function:




         /**

	 * Retunr an array with the roles

	 */

	function getUserRoles()

	{

	

		$roles = array();

		$criteria=new CDbCriteria;

		$criteria->condition='userid=:id';

		$criteria->params=array(':id'=>Yii::app()->user->id);

		$Rol = Authassignment::model()->findAll($criteria);

	

		$indexArray = 0;

		foreach ($Rol as $item)

		{

			$roles[$indexArray] = $item->itemname;

		}

	

		return $roles;

	}



this will return an array with the roles of the current user.