Impersonate Users within Yii Framework

For some applications it can be advantageous for administration reasons to allow site administrators to login as other users. This is sometimes called user impersonation or "becoming that user".

This tutorial assumes you've set up a very standard Yii web application and was written when 1.1.6 was the current standard. We're also assuming you have a User model that we'll call "User". This is the model that stores your username, password, and other user related account information.

Step 1: UserIdentity

Open your protected.components.UserIdentity class. This should have an existing "authenticate" method that is called by the login form to authenticate a user. We'll begin by refactoring this method a little to pull out the actual work of saving the user.

public function authenticate()
        else if($this->_user->password!==$this->password)
        return !$this->errorCode;

    protected function logInUser($user)
            $this->_user = $user;
            $this->setState('name', $this->_user->name);

Note that your authenticate function might be finding the user by a different attribute, you mostly want to change it to call logInUser when it has successfully authenticated the user.

Now create a static function called Impersonate that looks like this:

public static function impersonate($userId)
	$ui = null;
	$user = User::model()->findByPk($userId);
		$ui = new UserIdentity($user->email, "");
	return $ui;

This function creates a UserIdentity for the specified userId and returns it. It uses our refactored logInUser function to log the user in. The advantage of using this function is that it avoids some of the private/protected access problems of using a static function. (There are some comments about this below that were added before this article was updated to include this refactor.)

Step 2: Create an impersonate action on your site controller:

public function actionImpersonate($id)
	$ui = UserIdentity::impersonate($id);
		Yii::app()->user->login($ui, 0);

You can see that we're logging in as the impersonated user by the same method that the standard LoginForm uses. We'll then redirect to the home page of the site as the new user.

Step 3:

Protect your site/impersonate action. Obviously this action is very powerful. Be sure to add it to your restricted access control rules so that only properly authenticated administrators can access it.

Note that you'll have to log out and back in as a site administrator to become a different user.

20 0
Viewed: 21 535 times
Version: 1.1
Category: Tutorials
Written by: Woil
Last updated by: Woil
Created on: Mar 4, 2011
Last updated: 9 years ago
Update Article


View all history

Related Articles