用户模拟

版本 2.10.0 中新增: 用户模拟已添加。

部署应用程序后,您可能偶尔需要“模拟”另一个用户,以调试客户报告的问题,或查看客户看到应用程序的状态。

启用模拟

要模拟另一个用户,您可以使用 impersonate() 方法在 AuthenticationComponent 上。要模拟用户,您首先需要从应用程序的数据库中加载该用户

// In a controller
public function impersonate()
{
    $this->request->allowMethod(['POST']);

    $currentUser = $this->request->getAttribute('identity');

    // You should always check that the current user is allowed
    // to impersonate other users first.
    if (!$currentUser->isStaff()) {
        throw new NotFoundException();
    }

    // Fetch the user we want to impersonate.
    $targetUser = $this->Users->findById(
        $this->request->getData('user_id')
    )->firstOrFail();

    // Enable impersonation.
    $this->Authentication->impersonate($targetUser);

    return $this->redirect($this->referer());
}

开始模拟用户后,所有后续请求都将使用 $targetUser 作为活动身份。

结束模拟

完成模拟用户后,可以使用 AuthenticationComponent 结束模拟并恢复到以前的身份

// In a controller
public function revertIdentity()
{
    $this->request->allowMethod(['POST']);

    // Make sure we are still impersonating a user.
    if (!$this->Authentication->isImpersonating()) {
        throw new NotFoundException();
    }
    $this->Authentication->stopImpersonating();
}

模拟的限制

模拟有一些限制。

  1. 您的应用程序必须使用 Session 身份验证器。

  2. 在模拟活动时,您不能模拟另一个用户。相反,您必须 stopImpersonation(),然后再次启动它。