CakePHP 2: Login as User feature

To be able to emulate logging in as a user from the admin side of your application all you need to do is store the user’s id in a separate session, then have the rest of your application decide which user id to read when querying data.

In this example I’m including all queries in the method and only obtaining the user id and name, in a real life application I would place my queries in model methods and maybe pass more conditions such as the user must be a customer only, it’s up to you how you want to amend this.

The next thing to do is to add to our AppController and add a new controller property to be able to obtain the appropriate id (Admin.id or Auth.User.id). In your beforeFilter add the following line:

$this->_userId = ($this->Session->check('Admin.user_id')) ? $this->Session->read('Admin.user_id') : $this->Auth->user('id');

Now from within any controller in your application (providing you don’t override the beforeFilter), you can decide whether to use $this->Auth->user(‘id’) to obtain the actual logged in user’s id or $this->_userId to obtain our new one. I think I should point out that you should only really use $this->_userId outside of the admin prefix, I can’t imagine why you would want to assume the customer’s id within the admin side of your application.

Another thing you could do in your AppController is rather than writing $this->_userId, you could save it to Configure::write(‘UserId’, $codeForUserId). This will allow you to use the same id within views, models and controllers much easier.

If you’ve already started your application it’ll go without saying that you will no doubt need to search for times you have used $this->Auth->user(‘id’) and replace it for this to work.

Finally you will need a method to stop emulating the user at any point, this is very straight forward and goes without saying.

You may wish to place an element in your layout file which reads the Admin.user_id session and present some sort of notification with a link to the above method. I have one which looks something like this:

And that’s about it! It’s really straight forward but yet very effective,┬áit beats trying to help a customer over the phone without being able to see what they see, have fun implementing.

Leave a Reply

Your email address will not be published. Required fields are marked *