diff --git a/src/Controller/Component/AuthenticationComponent.php b/src/Controller/Component/AuthenticationComponent.php index 398e24d5..a9318340 100644 --- a/src/Controller/Component/AuthenticationComponent.php +++ b/src/Controller/Component/AuthenticationComponent.php @@ -445,6 +445,10 @@ public function stopImpersonating() */ public function isImpersonating(): bool { + if (!$this->getIdentity()) { + return false; + } + $service = $this->getImpersonationAuthenticationService(); $controller = $this->getController(); diff --git a/tests/TestCase/Controller/Component/AuthenticationComponentTest.php b/tests/TestCase/Controller/Component/AuthenticationComponentTest.php index abe5d9aa..b7cd2397 100644 --- a/tests/TestCase/Controller/Component/AuthenticationComponentTest.php +++ b/tests/TestCase/Controller/Component/AuthenticationComponentTest.php @@ -731,13 +731,17 @@ public function testIsImpersonating() $this->request->getSession()->write('AuthImpersonate', $impersonator); $this->service->authenticate($this->request); $request = $this->request - ->withAttribute('authentication', $this->service); + ->withAttribute('authentication', $this->service) + ->withAttribute('identity', new Identity($impersonated)); $controller = new Controller($request, $this->response); $registry = new ComponentRegistry($controller); $component = new AuthenticationComponent($registry); $result = $component->isImpersonating(); $this->assertTrue($result); + + $component->logout(); + $this->assertFalse($component->isImpersonating()); } /** @@ -749,10 +753,13 @@ public function testGetImpersonationAuthenticationServiceFailure() { $service = $this->getMockBuilder(AuthenticationServiceInterface::class)->getMock(); - $component = $this->createPartialMock(AuthenticationComponent::class, ['getAuthenticationService']); - $component->expects($this->once()) - ->method('getAuthenticationService') - ->willReturn($service); + $user = new ArrayObject(['username' => 'mariano']); + $request = $this->request + ->withAttribute('authentication', $service) + ->withAttribute('identity', new Identity($user)); + $controller = new Controller($request, $this->response); + $registry = new ComponentRegistry($controller); + $component = new AuthenticationComponent($registry); $this->expectException(InvalidArgumentException::class); $classname = get_class($service);