Impersonating user for API testing


#1

Hello,

I need to be able to impersonate users (user ids more specifically), while developing/testing my API and controllers.
Ideally, I want to be able to manipulate the response I get from:
$this->ci->currentUser;

Maybe I can selectively force a specific user id from an external configuration file?

Or provide a special API field to set the user_id to impersonate in each API request? (that would be easier for my API testing as well)

Any ideas?

Thanks


#2

It depends how you are testing. Overwriting the currentUser is not easy, as if you force change $this->ci->currentUser in the controller, it won’t change the whole stacks, ie everything loaded before the controller is invoked.

If you are testing in the browser, it won’t be easy… There’s nothing built-in UF for this currently. See : https://github.com/userfrosting/UserFrosting/issues/877

If you’re testing using PHPUnit, in UF 4.2, new Trait is available for this (documentation pending) : https://github.com/userfrosting/UserFrosting/blob/develop/app/sprinkles/account/tests/withTestUser.php


#3

Thanks…

Ideally I could do this:

  1. Encapsulate the $this->ci->currentUser in my own function.

  2. Set up a configuration variable, to allow user impersonation (for development), or not (production).

  3. If user impersonation is allowed, overrride $this->ci in my function, and instead allow a field in the API calls to determine a user_id as the logged in user.

Does that sound good enough?

What would be a good place to set the configuration variable for step (2)?

Thanks