Impersonate another user when running your plugin
Often, when running a plugin, you would want to execute a server-side transaction that might require additional privileges that the current logged in user does not have. For example, when a plugin passes or fails, you want to record the outcome of your process in a custom entity. Normal users would typically have limited-to-no access to such entities to avoid tampering. In such a scenario, even though the plugin is running in the context of a user, you would want that user to temporarily run as a different user with the correct privileges.
There are two ways to impersonate within plugins: you can either do it in your plugin code or when registering your plugin. In this recipe, we will cover the in-code example.
Getting ready
You will need a plugin already created, such as the one in the previous recipe. When running the code, the users must have the Act On Behalf Of Another User
privilege (under Business Management
| Miscellaneous Privileges...