From bedbb845eec20363b928b424143787dbe988eefe Mon Sep 17 00:00:00 2001 From: ArthurHoaro Date: Thu, 13 Aug 2020 11:08:13 +0200 Subject: Move all admin controller into a dedicated group Also handle authentication check in a new middleware for the admin group. --- tests/front/ShaarliAdminMiddlewareTest.php | 100 +++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 tests/front/ShaarliAdminMiddlewareTest.php (limited to 'tests/front/ShaarliAdminMiddlewareTest.php') diff --git a/tests/front/ShaarliAdminMiddlewareTest.php b/tests/front/ShaarliAdminMiddlewareTest.php new file mode 100644 index 00000000..7451330b --- /dev/null +++ b/tests/front/ShaarliAdminMiddlewareTest.php @@ -0,0 +1,100 @@ +container = $this->createMock(ShaarliContainer::class); + + touch(static::TMP_MOCK_FILE); + + $this->container->conf = $this->createMock(ConfigManager::class); + $this->container->conf->method('getConfigFileExt')->willReturn(static::TMP_MOCK_FILE); + + $this->container->loginManager = $this->createMock(LoginManager::class); + $this->container->updater = $this->createMock(Updater::class); + + $this->container->environment = ['REQUEST_URI' => 'http://shaarli/subfolder/path']; + + $this->middleware = new ShaarliAdminMiddleware($this->container); + } + + public function tearDown(): void + { + unlink(static::TMP_MOCK_FILE); + } + + /** + * Try to access an admin controller while logged out -> redirected to login page. + */ + public function testMiddlewareWhileLoggedOut(): void + { + $this->container->loginManager->expects(static::once())->method('isLoggedIn')->willReturn(false); + + $request = $this->createMock(Request::class); + $request->method('getUri')->willReturnCallback(function (): Uri { + $uri = $this->createMock(Uri::class); + $uri->method('getBasePath')->willReturn('/subfolder'); + + return $uri; + }); + + $response = new Response(); + + /** @var Response $result */ + $result = $this->middleware->__invoke($request, $response, function () {}); + + static::assertSame(302, $result->getStatusCode()); + static::assertSame( + '/subfolder/login?returnurl=' . urlencode('http://shaarli/subfolder/path'), + $result->getHeader('location')[0] + ); + } + + /** + * Process controller while logged in. + */ + public function testMiddlewareWhileLoggedIn(): void + { + $this->container->loginManager->method('isLoggedIn')->willReturn(true); + + $request = $this->createMock(Request::class); + $request->method('getUri')->willReturnCallback(function (): Uri { + $uri = $this->createMock(Uri::class); + $uri->method('getBasePath')->willReturn('/subfolder'); + + return $uri; + }); + + $response = new Response(); + $controller = function (Request $request, Response $response): Response { + return $response->withStatus(418); // I'm a tea pot + }; + + /** @var Response $result */ + $result = $this->middleware->__invoke($request, $response, $controller); + + static::assertSame(418, $result->getStatusCode()); + } +} -- cgit v1.2.3