Fix pagination and remove ModuleController, rename handlesAuth

This commit introduces the following changes:
- Count is now performed after joins are added to the selection query,
  therefore returning the correct number
- MonitoringControllerTest now needn't to mock ModuleActionController (which is now removed)
- handlesAuthentication is now requiresAuthentication
- Redirection to login is now directly handled in the ActionController constructor,
  so we don't need to overwrite the preDispatch method

refs #4589
refs #4591
refs #4572
This commit is contained in:
Jannis Moßhammer 2013-08-30 15:50:49 +02:00 committed by Eric Lippmann
parent aac1d69ed2
commit 9f923b4940
9 changed files with 282 additions and 445 deletions

View File

@ -43,7 +43,7 @@ class AuthenticationController extends ActionController
*
* @var bool
*/
protected $handlesAuthentication = true;
protected $requiresAuthentication = false;
/**
* This controller modifies the session

View File

@ -38,12 +38,11 @@ use \Icinga\Application\Icinga;
class IndexController extends ActionController
{
/**
* Always authenticate
* Use a default redirection rule to welcome page
*/
public function preDispatch()
{
parent::preDispatch(); // -> auth :(
if ($this->action_name !== 'welcome') {
if ($this->getRequest()->getActionName() !== 'welcome') {
$this->redirect('index/welcome');
}
}

View File

@ -35,42 +35,24 @@ use \Icinga\Application\Logger;
class StaticController extends ActionController
{
/**
* @TODO: Bug #4572
* Static routes don't require authentication
*
* @var bool
*/
protected $handlesAuthentication = true;
protected $requiresAuthentication = false;
/**
* Disable layout rendering as this controller doesn't provide any html layouts
*/
public function init()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
}
private function getModuleList()
{
$modules = Icinga::app()->getModuleManager()->getLoadedModules();
// preliminary static definition
$result = array();
foreach ($modules as $name => $module) {
$hasJs = file_exists($module->getBasedir() . '/public/js/' . $name . '.js');
$result[] = array(
'name' => $name,
'active' => true,
'type' => 'generic',
'behaviour' => $hasJs
);
}
return $result;
}
public function modulelistAction()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$this->getResponse()->setHeader('Content-Type', 'application/json');
echo 'define(function() { return ' . json_encode($this->getModuleList(), true) . '; })';
exit;
}
/**
* Return an image from the application's or the module's public folder
*/
public function imgAction()
{
$module = $this->_getParam('module_name');
@ -107,6 +89,9 @@ class StaticController extends ActionController
return;
}
/**
* Return a javascript file from the application's or the module's public folder
*/
public function javascriptAction()
{
$module = $this->_getParam('module_name');

View File

@ -28,11 +28,11 @@
namespace Icinga\Web\Controller;
use \Zend_Controller_Action as ZfController;
use \Zend_Controller_Request_Abstract as ZfRequest;
use \Zend_Controller_Response_Abstract as ZfResponse;
use \Zend_Controller_Action_HelperBroker as ZfActionHelper;
use \Zend_Layout as ZfLayout;
use \Zend_Controller_Action;
use \Zend_Controller_Request_Abstract;
use \Zend_Controller_Response_Abstract;
use \Zend_Controller_Action_HelperBroker;
use \Zend_Layout;
use \Icinga\Authentication\Manager as AuthManager;
use \Icinga\Application\Benchmark;
use \Icinga\Exception;
@ -46,7 +46,7 @@ use \Icinga\Web\Url;
*
* All Icinga Web core controllers should extend this class
*/
class ActionController extends ZfController
class ActionController extends Zend_Controller_Action
{
/**
* True to mark this layout to not render the full layout
@ -61,7 +61,7 @@ class ActionController extends ZfController
*
* @var bool
*/
protected $handlesAuthentication = false;
protected $requiresAuthentication = true;
/**
* Set true when this controller modifies the session
@ -74,74 +74,49 @@ class ActionController extends ZfController
*/
protected $modifiesSession = false;
/**
* True if authentication succeeded, otherwise false
*
* @var bool
*/
protected $allowAccess = false;
/**
* The current module name. TODO: Find out whether this shall be null for
* non-module actions
*
* @var string
*/
protected $module_name;
/**
* The current controller name
*
* @var string
*/
protected $controller_name;
/**
* The current action name
*
* @var string
*/
protected $action_name;
/**
* The constructor starts benchmarking, loads the configuration and sets
* other useful controller properties
*
* @param ZfRequest $request
* @param ZfResponse $response
* @param array $invokeArgs Any additional invocation arguments
* @param Zend_Controller_Request_Abstract $request
* @param Zend_Controller_Response_Abstract $response
* @param array $invokeArgs Any additional invocation arguments
*/
public function __construct(
ZfRequest $request,
ZfResponse $response,
Zend_Controller_Request_Abstract $request,
Zend_Controller_Response_Abstract $response,
array $invokeArgs = array()
) {
Benchmark::measure('Action::__construct()');
$this->module_name = $request->getModuleName();
$this->controller_name = $request->getControllerName();
$this->action_name = $request->getActionName();
$this->setRequest($request)
->setResponse($response)
->_setInvokeArgs($invokeArgs);
$this->_helper = new ZfActionHelper($this);
->setResponse($response)
->_setInvokeArgs($invokeArgs);
$this->_helper = new Zend_Controller_Action_HelperBroker($this);
if ($this->handlesAuthentication ||
AuthManager::getInstance(
null,
array(
'writeSession' => $this->modifiesSession
)
)->isAuthenticated()
) {
$this->allowAccess = true;
// when noInit is set (e.g. for testing), authentication and init is skipped
if (isset($invokeArgs['noInit'])) {
return;
}
if ($this->determineAuthenticationState() === true) {
$this->view->tabs = new Tabs();
$this->init();
} else {
$this->redirectToLogin();
}
}
protected function determineAuthenticationState(array $invokeArgs = array())
{
if (!$this->requiresAuthentication) {
return true;
}
return AuthManager::getInstance(
null,
array('writeSession' => $this->modifiesSession)
)->isAuthenticated();
}
/**
* Return the tabs
*
@ -165,36 +140,13 @@ class ActionController extends ZfController
return t($string);
}
/**
* Redirect to the login path
*/
private function redirectToLogin()
{
$this->_request->setModuleName('default')
->setControllerName('authentication')
->setActionName('login')
->setDispatched(false);
}
/**
* Prepare action execution by testing for correct permissions and setting shortcuts
*/
public function preDispatch()
{
Benchmark::measure('Action::preDispatch()');
if (! $this->allowAccess) {
return $this->redirectToLogin();
}
$this->view->action_name = $this->action_name;
$this->view->controller_name = $this->controller_name;
$this->view->module_name = $this->module_name;
Benchmark::measure(
sprintf(
'Action::preDispatched(): %s / %s / %s',
$this->module_name,
$this->controller_name,
$this->action_name
)
);
$url = Url::fromPath('/authentication/login');
$this->redirectNow($url->getRelativeUrl());
}
/**

View File

@ -1,42 +0,0 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
/**
* Module action controller
*/
namespace Icinga\Web\Controller;
/**
* Base class for all module action controllers
*
* @TODO: Only here for compatibility and testing reasons, make ActionController testable and remove this (Bug #4540)
*
*/
class ModuleActionController extends ActionController
{
}

View File

@ -32,7 +32,7 @@ use \Monitoring\Backend;
use \Icinga\Application\Config;
use \Icinga\Application\Logger;
use \Icinga\Web\Form;
use \Icinga\Web\Controller\ModuleActionController;
use \Icinga\Web\Controller\ActionController;
use \Icinga\Protocol\Commandpipe\CommandPipe;
use \Icinga\Exception\ConfigurationError;
use \Icinga\Exception\MissingParameterException;
@ -51,7 +51,7 @@ use \Monitoring\Form\Command\SubmitPassiveCheckResultForm;
*
* Interface to send commands and display forms
*/
class Monitoring_CommandController extends ModuleActionController
class Monitoring_CommandController extends ActionController
{
const DEFAULT_VIEW_SCRIPT = 'renderform';

View File

@ -31,7 +31,7 @@
use \Icinga\Application\Benchmark;
use \Icinga\Data\Db\Query;
use \Icinga\File\Csv;
use \Icinga\Web\Controller\ModuleActionController;
use \Icinga\Web\Controller\ActionController;
use \Icinga\Web\Hook;
use \Icinga\Web\Widget\Tabextension\BasketAction;
use \Icinga\Web\Widget\Tabextension\DashboardAction;
@ -39,7 +39,7 @@ use \Icinga\Web\Widget\Tabextension\OutputFormat;
use \Icinga\Web\Widget\Tabs;
use \Monitoring\Backend;
class Monitoring_ListController extends ModuleActionController
class Monitoring_ListController extends ActionController
{
/**
* The backend used for this controller
@ -68,6 +68,16 @@ class Monitoring_ListController extends ModuleActionController
$this->createTabs();
}
/**
* Overwrite the backend to use (used for testing)
*
* @param Backend $backend The Backend that should be used for querying
*/
public function setBackend($backend)
{
$this->backend = $backend;
}
/**
* Display host list
*/

View File

@ -28,7 +28,7 @@
// {{{ICINGA_LICENSE_HEADER}}}
use Monitoring\Backend;
use Icinga\Web\Controller\ModuleActionController;
use Icinga\Web\Controller\ActionController;
use Icinga\Web\Hook;
use Monitoring\Object\Host;
use Monitoring\Object\Service;
@ -43,7 +43,7 @@ use Icinga\Web\Widget\Tabextension\BasketAction;
*
* Actions for show context
*/
class Monitoring_ShowController extends ModuleActionController
class Monitoring_ShowController extends ActionController
{
/**
* @var Backend

View File

@ -26,307 +26,240 @@
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Web\Controller
namespace Test\Monitoring\Testlib;
require_once 'Zend/View.php';
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';
use \Zend_View;
use \Zend_Config;
use \Zend_Test_PHPUnit_ControllerTestCase;
use \Icinga\Protocol\Statusdat\Reader;
use \Icinga\Web\Controller\ActionController;
use \Icinga\Application\DbAdapterFactory;
use \Monitoring\Backend\Ido;
use \Monitoring\Backend\Statusdat;
use \Test\Monitoring\Testlib\DataSource\TestFixture;
use \Test\Monitoring\Testlib\DataSource\DataSourceTestSetup;
/**
* Base class for monitoring controllers that loads required dependencies
* and allows easier setup of tests
*
* Example:
* <code>
*
* class MyControllerTest extends MonitoringControllerTest
* {
* public function testSomething()
* {
* // Create a test fixture
* $fixture = new TestFixture()
* $fixture->addHost('host', 0)->addService(...)->..->;
*
* $this->setupFixture($fixture, "mysql"); // setup the fixture
* $controller = $this->requireController('MyController', 'mysql');
* // controller is now the Zend controller instance, perform an action
* $controller->myAction();
* $result = $controller->view->hosts->fetchAll();
* // assert stuff
* }
* }
*/
abstract class MonitoringControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
/**
* Mocked controller base class to avoid the complete
* Bootstrap dependency of the normally used ModuleActionController
* The module directory for requiring modules (is relative to the source file)
* @var string
*/
class ModuleActionController
private $moduleDir = "";
/**
* The application directory for requirying library files (is relative to the source file)
* @var string
*/
private $appDir = "";
/**
* Require necessary libraries on test creation
*
* This is called for every test and assures that all required libraries for the controllers
* are loaded. If you need additional dependencies you should overwrite this method, call the parent
* and then require your classes
*/
public function setUp()
{
/**
* The view this controller would create
* @var stdClass
*/
public $view;
$this->moduleDir = dirname(__FILE__) . '/../../../';
$this->appDir = $this->moduleDir.'../../library/Icinga/';
$module = $this->moduleDir;
$app = $this->appDir;
set_include_path(get_include_path().':'.$module);
set_include_path(get_include_path().':'.$app);
public $headers = array();
require_once('Zend/Config.php');
require_once('Zend/Db.php');
require_once(dirname(__FILE__) . '/datasource/DataSourceTestSetup.php');
/**
* Parameters provided on call
* @var array
*/
public $params = array();
$this->requireBase();
$this->requireViews();
}
/**
* _getParam method that normally retrieves GET/POST parameters
*
* @param string $param The parameter name to retrieve
* @return mixed|bool The parameter $param or false if it doesn't exist
*/
public function _getParam($param, $default = null)
{
if (!isset($this->params[$param])) {
return $default;
/**
* Require base application and data retrieval classes from the Icinga Library
*
*/
private function requireBase()
{
require_once('Application/Benchmark.php');
require_once('Data/AbstractQuery.php');
require_once('Data/DatasourceInterface.php');
require_once('Data/Db/Connection.php');
require_once('Data/Db/Query.php');
require_once('Exception/ProgrammingError.php');
require_once('library/Monitoring/Backend/AbstractBackend.php');
}
/**
* Require all defined IDO queries in this module
*
*/
private function requireIDOQueries()
{
require_once('Application/DbAdapterFactory.php');
require_once('library/Monitoring/Backend/Ido.php');
$this->requireFolder('library/Monitoring/Backend/Ido/Query');
}
/**
* Require all php files in the folder $folder
*
* @param $folder The path to the folder containing PHP files
*/
private function requireFolder($folder)
{
$module = $this->moduleDir;
$views = scandir($module.$folder);
foreach ($views as $view) {
if (!preg_match('/php$/', $view)) {
continue;
}
return $this->params[$param];
}
public function getParam($param, $default = null)
{
return $this->_getParam($param, $default);
}
public function preserve()
{
return $this;
}
public function getParams()
{
return $this->params;
}
/**
* Sets the backend for this controller which will be used in the action
*
* @param $backend
*/
public function setBackend($backend)
{
$this->backend = $backend;
}
public function __get($param) {
return $this;
}
public function getHeader($header) {
if (isset($this->headers[$header])) {
return $this->headers[$header];
}
return null;
require_once(realpath($module.$folder."/".$view));
}
}
}
namespace Test\Monitoring\Testlib
{
require_once 'Zend/View.php';
use \Zend_View;
use \Zend_Config;
use \Icinga\Protocol\Statusdat\Reader;
use \Icinga\Web\Controller\ActionController;
use \Icinga\Application\DbAdapterFactory;
use \Monitoring\Backend\Ido;
use \Monitoring\Backend\Statusdat;
use \Test\Monitoring\Testlib\DataSource\TestFixture;
use \Test\Monitoring\Testlib\DataSource\DataSourceTestSetup;
/**
* Base class for monitoring controllers that loads required dependencies
* and allows easier setup of tests
* Require all views and queries from the statusdat backen
*
* Example:
* <code>
*
* class MyControllerTest extends MonitoringControllerTest
* {
* public function testSomething()
* {
* // Create a test fixture
* $fixture = new TestFixture()
* $fixture->addHost('host', 0)->addService(...)->..->;
*
* $this->setupFixture($fixture, "mysql"); // setup the fixture
* $controller = $this->requireController('MyController', 'mysql');
* // controller is now the Zend controller instance, perform an action
* $controller->myAction();
* $result = $controller->view->hosts->fetchAll();
* // assert stuff
* }
* }
*/
abstract class MonitoringControllerTest extends \PHPUnit_Framework_TestCase
private function requireStatusDatQueries()
{
/**
* The module directory for requiring modules (is relative to the source file)
* @var string
*/
private $moduleDir = "";
require_once(realpath($this->moduleDir.'/library/Monitoring/Backend/Statusdat.php'));
require_once(realpath($this->moduleDir.'/library/Monitoring/Backend/Statusdat/Query/Query.php'));
$this->requireFolder('library/Monitoring/Backend/Statusdat');
$this->requireFolder('library/Monitoring/Backend/Statusdat/Criteria');
$this->requireFolder('library/Monitoring/Backend/Statusdat/Query');
$this->requireFolder('library/Monitoring/Backend/Statusdat/DataView');
$this->requireFolder('library/Monitoring/Backend/Statusdat/DataView');
}
/**
* The application directory for requirying library files (is relative to the source file)
* @var string
*/
private $appDir = "";
/**
* Require all (generic) view classes from the monitoring module
*/
private function requireViews()
{
$module = $this->moduleDir;
require_once($module.'library/Monitoring/View/MonitoringView.php');
$this->requireFolder('library/Monitoring/View/');
}
/**
* Require necessary libraries on test creation
*
* This is called for every test and assures that all required libraries for the controllers
* are loaded. If you need additional dependencies you should overwrite this method, call the parent
* and then require your classes
*/
public function setUp()
{
$this->moduleDir = dirname(__FILE__) . '/../../../';
$this->appDir = $this->moduleDir.'../../library/Icinga/';
$module = $this->moduleDir;
$app = $this->appDir;
set_include_path(get_include_path().':'.$module);
set_include_path(get_include_path().':'.$app);
/**
* Require and set up a controller $controller using the backend type specified at $backend
*
* @param string $controller The name of the controller tu use
* (must be under monitoring/application/controllers)
* @param string $backend The backend to use ('mysql', 'pgsql' or 'statusdat')
* @return ModuleActionController The newly created controller
*/
public function requireController($controller, $backend)
{
require_once($this->moduleDir.'/application/controllers/'.$controller.'.php');
$controllerName = '\Monitoring_'.ucfirst($controller);
/** @var ActionController $controller */
$controller = new $controllerName(
$this->getRequest(),
$this->getResponse(),
array('noInit' => true)
);
$controller->setBackend($this->getBackendFor($backend));
require_once('Zend/Config.php');
require_once('Zend/Db.php');
require_once(dirname(__FILE__) . '/datasource/DataSourceTestSetup.php');
// Many controllers need a view to work properly
$controller->view = new Zend_View();
$this->requireBase();
$this->requireViews();
}
return $controller;
}
/**
* Require base application and data retrieval classes from the Icinga Library
*
*/
private function requireBase()
{
require_once('Application/Benchmark.php');
require_once('Data/AbstractQuery.php');
require_once('Data/DatasourceInterface.php');
require_once('Data/Db/Connection.php');
require_once('Data/Db/Query.php');
require_once('Exception/ProgrammingError.php');
/**
* Create a new backend and insert the given fixture into it
*
* @param TestFixture $fixture The TestFixture to create
* @param string $type The type of the backend ('mysql', 'pgsql' or 'statusdat')
*/
public function setupFixture(TestFixture $fixture, $type)
{
$dbInstance = new DataSourceTestSetup($type);
$dbInstance->setup();
$dbInstance->insert($fixture);
}
require_once('library/Monitoring/Backend/AbstractBackend.php');
/**
* Set up and configure a new testbackend for the given type
*
* @param string $type The type of the backend 'mysql', 'pgsql' or 'statusdat'
* @return Ido|Statusdat The newly created backend
*/
public function getBackendFor($type)
{
if ($type == "mysql" || $type == "pgsql") {
$this->requireIDOQueries();
}
/**
* Require all defined IDO queries in this module
*
*/
private function requireIDOQueries()
{
require_once('Application/DbAdapterFactory.php');
require_once('library/Monitoring/Backend/Ido.php');
$this->requireFolder('library/Monitoring/Backend/Ido/Query');
}
/**
* Require all php files in the folder $folder
*
* @param $folder The path to the folder containing PHP files
*/
private function requireFolder($folder)
{
$module = $this->moduleDir;
$views = scandir($module.$folder);
foreach ($views as $view) {
if (!preg_match('/php$/', $view)) {
continue;
}
require_once(realpath($module.$folder."/".$view));
}
}
/**
* Require all views and queries from the statusdat backen
*
*/
private function requireStatusDatQueries()
{
require_once(realpath($this->moduleDir.'/library/Monitoring/Backend/Statusdat.php'));
require_once(realpath($this->moduleDir.'/library/Monitoring/Backend/Statusdat/Query/Query.php'));
$this->requireFolder('library/Monitoring/Backend/Statusdat');
$this->requireFolder('library/Monitoring/Backend/Statusdat/Criteria');
$this->requireFolder('library/Monitoring/Backend/Statusdat/Query');
$this->requireFolder('library/Monitoring/Backend/Statusdat/DataView');
$this->requireFolder('library/Monitoring/Backend/Statusdat/DataView');
}
/**
* Require all (generic) view classes from the monitoring module
*/
private function requireViews()
{
$module = $this->moduleDir;
require_once($module.'library/Monitoring/View/MonitoringView.php');
$this->requireFolder('library/Monitoring/View/');
}
/**
* Require and set up a controller $controller using the backend type specified at $backend
*
* @param string $controller The name of the controller tu use
* (must be under monitoring/application/controllers)
* @param string $backend The backend to use ('mysql', 'pgsql' or 'statusdat')
* @return ModuleActionController The newly created controller
*/
public function requireController($controller, $backend)
{
require_once($this->moduleDir.'/application/controllers/'.$controller.'.php');
$controllerName = '\Monitoring_'.ucfirst($controller);
/** @var ActionController $controller */
$controller = new $controllerName;
$controller->setBackend($this->getBackendFor($backend));
// Many controllers need a view to work properly
$controller->view = new Zend_View();
return $controller;
}
/**
* Create a new backend and insert the given fixture into it
*
* @param TestFixture $fixture The TestFixture to create
* @param string $type The type of the backend ('mysql', 'pgsql' or 'statusdat')
*/
public function setupFixture(TestFixture $fixture, $type)
{
$dbInstance = new DataSourceTestSetup($type);
$dbInstance->setup();
$dbInstance->insert($fixture);
}
/**
* Set up and configure a new testbackend for the given type
*
* @param string $type The type of the backend 'mysql', 'pgsql' or 'statusdat'
* @return Ido|Statusdat The newly created backend
*/
public function getBackendFor($type)
{
if ($type == "mysql" || $type == "pgsql") {
$this->requireIDOQueries();
$resourceConfig = array(
'icinga-db-unittest' => array(
'type' => 'db',
'db' => $type,
'host' => "localhost",
'username' => "icinga_unittest",
'password' => "icinga_unittest",
'dbname' => "icinga_unittest"
)
);
DbAdapterFactory::resetConfig();
DbAdapterFactory::setConfig($resourceConfig);
$backendConfig = array(
$resourceConfig = array(
'icinga-db-unittest' => array(
'type' => 'db',
'resource' => 'icinga-db-unittest'
);
'db' => $type,
'host' => "localhost",
'username' => "icinga_unittest",
'password' => "icinga_unittest",
'dbname' => "icinga_unittest"
)
);
return new Ido(
new Zend_Config($backendConfig)
);
} elseif ($type == "statusdat") {
$this->requireStatusDatQueries();
return new Statusdat(
new \Zend_Config(
array(
'status_file' => '/tmp/teststatus.dat',
'objects_file' => '/tmp/testobjects.cache',
'no_cache' => true
)
DbAdapterFactory::resetConfig();
DbAdapterFactory::setConfig($resourceConfig);
$backendConfig = array(
'type' => 'db',
'resource' => 'icinga-db-unittest'
);
return new Ido(
new Zend_Config($backendConfig)
);
} elseif ($type == "statusdat") {
$this->requireStatusDatQueries();
return new Statusdat(
new \Zend_Config(
array(
'status_file' => '/tmp/teststatus.dat',
'objects_file' => '/tmp/testobjects.cache',
'no_cache' => true
)
);
}
)
);
}
}
}
}