Add information to Yii::app()->user by extending CWebUser (better version)

I found a better solution.

(Your login credentials may differ from my version so you will have to fit the script to your needs. I'm only telling what is the point)

Steps to follow:

  1. Add $user field to UserIdentity class
  2. Add getUser() method - getter for above property
  3. Add setUser($user) method - setter for above property which will assign user's properties info $user attribute.

My example UserIdentity class:

<?php
class UserIdentity extends CUserIdentity
{
	/**
	* User's attributes
	* @var array
	*/
	public $user;

	public function authenticate()
	{
		$this->errorCode=self::ERROR_PASSWORD_INVALID;
		$user=User::model()->findByAttributes(array('email'=>CHtml::encode($this->username)));

		if ($user)
		{
			if ($user->password === md5($user->salt.$this->password)) {
				$this->errorCode=self::ERROR_NONE;
				$this->setUser($user);
			}
		}

		unset($user);
		return !$this->errorCode;
	}

	public function getUser()
	{
		return $this->user;
	}

	public function setUser(CActiveRecord $user)
	{
		$this->user=$user->attributes;
	}
}
?>

Now user's attributes has been set, create WebUser class and place it under /protected/components

class WebUser extends CWebUser
{
	public function __get($name)
	{
		if ($this->hasState('__userInfo')) {
			$user=$this->getState('__userInfo',array());
			if (isset($user[$name])) {
				return $user[$name];
			}
		}

		return parent::__get($name);
	}

	public function login($identity, $duration) {
		$this->setState('__userInfo', $identity->getUser());
		parent::login($identity, $duration);
	}

	/* 
	* Required to checkAccess function
	* Yii::app()->user->checkAccess('operation')
	*/
	public function getId()
	{
		return $this->id;
	}
}
?>

remember to set that class as Yii::app()->user class:

<?php
'components'=>array(
	'user'=>array(
		'class'=>'WebUser',
	)
)
?>

Should work now :) You can now access user's database fields as properties.

5 0
10 followers
Viewed: 49 262 times
Version: 1.1
Category: Tutorials
Tags: rbac, user, Yii
Written by: emix
Last updated by: Anas AbuDayah
Created on: Aug 15, 2010
Last updated: 10 years ago
Update Article

Revisions

View all history

Related Articles