I am a newbie, started using Yii two days ago. I am able to set up and use the blog tutorial. However, when I tried to add any new feature to the tutorial, I am not able to figure out which file to modify. For example, there is an email field in tbl_user. And, I have added firstname and lastname fields to tbl_user. After login, I want to display the firstname on a page with something like
I shall appreciate if some expert can guide me how should I implement this.
Also on the same lines, if I want to implement a simple scheme to determine whether a logged-in user is a regular user or has admin rights, based on the contents of a field in tbl_user (e.g. tbl_user.level > 1 means ‘admin’ and tbl_user.level <= 1 means a regular user), how do I implement this?
Thanks for your quick response. Well, your suggestion will work. However, I believe that it will require fetching data from the user table from the database. Is it possible to modify/extend the CWebUser or some other class to store the required details, such as User’s firstname, last name, phone number, etc. in the user object on successful login? I also want to determine whether the user is ‘admin’ based on some data in the user table. Then I would like to use user->isAdmin() to determine if the logged-in user has admin rights.
I tried to implement what I wanted (e.g. Yii::app()->user->getFirstname() ), but could not achieve, may be due to my limited knowledge about the Yii framework and too many files involved in implementing user and authentication. (UserIdentity.php, User.php, cUserIdentiry.php, CWebUser.php and many more, and I did not want to modify any Framework files.)
Anyway, I achieved what I wanted through Session in the authenticate method of protected/components/UserIdentity.php as shown here.
// Added to save details about the logged-in user
Yii::app()->session['user_firstname'] = $user->firstname;
Yii::app()->session['user_lastname'] = $user->lastname;
Yii::app()->session['user_fullname'] = trim($user->firstname). ' ' . trim($user->lastname);
Yii::app()->session['user_email'] = $user->email;
I would still prefer if I can implement my original scheme, i.e. Yii::app()->user->getFirstname(), however, my workaround works through <?php echo "Email= " . Yii::app()->session[‘user_email’] . “<BR>” ?>. I don’t know whether saving non-sensitive data in session will lead to any security issues. Any comments?
Take a look at CWebUser::setState(). It also stores the data in session AND if you use auto-login cookie, it will store those informations in there. Note that in the auto-login case, you shouldn’t save sensitive informations like passwords since they appear in clear text in cookie.
After you set a state, you can get it back with getState(). You can also do this of course:
class MyWebUser extends CWebUser
public function getFirstname()
Also note there is an afterLogin() method of CWebUser. In there you can do the setState() for each attribute instead of doing it in UserIdentity.