Extract Database\PrivilegesController from Server\PrivilegesController

Signed-off-by: Maurício Meneghini Fauth <mauricio@fauth.dev>
This commit is contained in:
Maurício Meneghini Fauth 2022-05-27 17:13:23 -03:00
parent dc5bf0074c
commit d58057daec
No known key found for this signature in database
GPG Key ID: 6A16FD38AFC89CC8
15 changed files with 91 additions and 109 deletions

View File

@ -7,14 +7,19 @@ declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\CheckUserPrivileges;
use PhpMyAdmin\Controllers\AbstractController;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Server\Privileges;
use PhpMyAdmin\Template;
use PhpMyAdmin\Util;
use function __;
use function mb_strtolower;
use function ob_get_clean;
use function ob_start;
/**
* Controller for database privileges
@ -38,18 +43,62 @@ class PrivilegesController extends AbstractController
$this->dbi = $dbi;
}
/**
* @param string[] $params Request parameters
* @psalm-param array{checkprivsdb: string} $params
*/
public function __invoke(array $params): string
public function __invoke(): void
{
$GLOBALS['text_dir'] = $GLOBALS['text_dir'] ?? null;
$checkUserPrivileges = new CheckUserPrivileges($this->dbi);
$checkUserPrivileges->getPrivileges();
$this->addScriptFiles(['server/privileges.js', 'vendor/zxcvbn-ts.js']);
/**
* Checks if the user is allowed to do what they try to...
*/
$isGrantUser = $this->dbi->isGrantUser();
$isCreateUser = $this->dbi->isCreateUser();
if (! $this->dbi->isSuperUser() && ! $isGrantUser && ! $isCreateUser) {
$this->render('server/sub_page_header', [
'type' => 'privileges',
'is_image' => false,
]);
$this->response->addHTML(
Message::error(__('No Privileges'))
->getDisplay()
);
return;
}
if (! $isGrantUser && ! $isCreateUser) {
$this->response->addHTML(Message::notice(
__('You do not have the privileges to administrate the users!')
)->getDisplay());
}
// Gets the database structure
$GLOBALS['sub_part'] = '_structure';
ob_start();
[
$GLOBALS['tables'],
$GLOBALS['num_tables'],
$GLOBALS['total_num_tables'],
$GLOBALS['sub_part'],,,
$GLOBALS['tooltip_truename'],
$GLOBALS['tooltip_aliasname'],
$GLOBALS['pos'],
] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part']);
$content = ob_get_clean();
$this->response->addHTML($content . "\n");
$scriptName = Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabDatabase'], 'database');
$db = $params['checkprivsdb'];
$db = $GLOBALS['db'];
if ($this->dbi->getLowerCaseNames() === '1') {
$db = mb_strtolower($params['checkprivsdb']);
$db = mb_strtolower($GLOBALS['db']);
}
$privileges = [];
@ -57,7 +106,7 @@ class PrivilegesController extends AbstractController
$privileges = $this->privileges->getAllPrivileges($db);
}
return $this->template->render('database/privileges/index', [
$this->render('database/privileges/index', [
'is_superuser' => $this->dbi->isSuperUser(),
'db' => $db,
'database_url' => $scriptName,
@ -66,5 +115,6 @@ class PrivilegesController extends AbstractController
'is_grantuser' => $this->dbi->isGrantUser(),
'privileges' => $privileges,
]);
$this->render('export_modal');
}
}

View File

@ -8,7 +8,6 @@ use PhpMyAdmin\CheckUserPrivileges;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\ConfigStorage\RelationCleanup;
use PhpMyAdmin\Controllers\AbstractController;
use PhpMyAdmin\Controllers\Database\PrivilegesController as DatabaseController;
use PhpMyAdmin\Core;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Html\Generator;
@ -25,8 +24,6 @@ use function header;
use function implode;
use function is_array;
use function is_string;
use function ob_get_clean;
use function ob_start;
use function str_replace;
use function urlencode;
@ -101,13 +98,7 @@ class PrivilegesController extends AbstractController
new Plugins($this->dbi)
);
$databaseController = new DatabaseController($this->response, $this->template, $serverPrivileges, $this->dbi);
if (
(isset($_GET['viewing_mode'])
&& $_GET['viewing_mode'] === 'server')
&& $relationParameters->configurableMenusFeature !== null
) {
if ($relationParameters->configurableMenusFeature !== null) {
$this->response->addHTML('<div class="container-fluid">');
$this->render('server/privileges/subnav', [
'active' => 'privileges',
@ -368,26 +359,7 @@ class PrivilegesController extends AbstractController
/**
* Displays the links
*/
if (isset($_GET['viewing_mode']) && $_GET['viewing_mode'] === 'db') {
$GLOBALS['db'] = $_REQUEST['db'] = $_GET['checkprivsdb'];
// Gets the database structure
$GLOBALS['sub_part'] = '_structure';
ob_start();
[
$GLOBALS['tables'],
$GLOBALS['num_tables'],
$GLOBALS['total_num_tables'],
$GLOBALS['sub_part'],,,
$GLOBALS['tooltip_truename'],
$GLOBALS['tooltip_aliasname'],
$GLOBALS['pos'],
] = Util::getDbInfo($GLOBALS['db'], $GLOBALS['sub_part']);
$content = ob_get_clean();
$this->response->addHTML($content . "\n");
} elseif (! empty($GLOBALS['message'])) {
if (! empty($GLOBALS['message'])) {
$this->response->addHTML(Generator::getMessage($GLOBALS['message']));
unset($GLOBALS['message']);
}
@ -417,16 +389,6 @@ class PrivilegesController extends AbstractController
$this->response->addHTML($serverPrivileges->getHtmlForAddUser(
Util::escapeMysqlWildcards(is_string($GLOBALS['dbname']) ? $GLOBALS['dbname'] : '')
));
} elseif (isset($_GET['checkprivsdb']) && is_string($_GET['checkprivsdb'])) {
if ($this->response->isAjax() === true && empty($_REQUEST['ajax_page_request'])) {
$GLOBALS['message'] = Message::success(__('User has been added.'));
$this->response->addJSON('message', $GLOBALS['message']);
return;
}
$this->response->addHTML($databaseController(['checkprivsdb' => $_GET['checkprivsdb']]));
$this->render('export_modal');
} else {
if (isset($GLOBALS['dbname']) && ! is_array($GLOBALS['dbname'])) {
$GLOBALS['url_dbname'] = urlencode(
@ -479,11 +441,7 @@ class PrivilegesController extends AbstractController
}
}
if (
! isset($_GET['viewing_mode'])
|| $_GET['viewing_mode'] !== 'server'
|| $relationParameters->configurableMenusFeature === null
) {
if ($relationParameters->configurableMenusFeature === null) {
return;
}

View File

@ -153,20 +153,6 @@ class Footer
$params['server'] = $GLOBALS['server'];
// needed for server privileges tabs
if (isset($_GET['viewing_mode']) && in_array($_GET['viewing_mode'], ['server', 'db'])) {
$params['viewing_mode'] = $_GET['viewing_mode'];
}
/**
* @todo coming from /server/privileges, here $db is not set,
* add the following condition below when that is fixed
* && $_GET['checkprivsdb'] == $db
*/
if (isset($_GET['checkprivsdb'])) {
$params['checkprivsdb'] = $_GET['checkprivsdb'];
}
if (isset($_REQUEST['single_table']) && in_array($_REQUEST['single_table'], [true, false])) {
$params['single_table'] = $_REQUEST['single_table'];
}

View File

@ -394,13 +394,11 @@ class Menu
$tabs['operation']['active'] = $route === '/database/operations';
if ($isSuperUser || $isCreateOrGrantUser) {
$tabs['privileges']['route'] = '/server/privileges';
$tabs['privileges']['args']['checkprivsdb'] = $this->db;
$tabs['privileges']['route'] = '/database/privileges';
// stay on database view
$tabs['privileges']['args']['viewing_mode'] = 'db';
$tabs['privileges']['text'] = __('Privileges');
$tabs['privileges']['icon'] = 's_rights';
$tabs['privileges']['active'] = $route === '/server/privileges';
$tabs['privileges']['active'] = $route === '/database/privileges';
}
$tabs['routines']['route'] = '/database/routines';
@ -500,7 +498,6 @@ class Menu
'/server/privileges',
'/server/user-groups',
]);
$tabs['rights']['args']['viewing_mode'] = 'server';
}
$tabs['export']['icon'] = 'b_export';

View File

@ -2101,7 +2101,6 @@ class Privileges
return $this->template->render('server/privileges/initials_row', [
'array_initials' => $arrayInitials,
'initial' => $_GET['initial'] ?? null,
'viewing_mode' => $_GET['viewing_mode'] ?? null,
]);
}
@ -2901,20 +2900,16 @@ class Privileges
return '';
}
$relParams = [];
$urlParams = ['adduser' => 1];
if (! empty($db)) {
$urlParams['dbname'] = $relParams['checkprivsdb'] = $db;
$urlParams['dbname'] = $db;
}
if (! empty($table)) {
$urlParams['tablename'] = $table;
}
return $this->template->render('server/privileges/add_user_fieldset', [
'url_params' => $urlParams,
'rel_params' => $relParams,
]);
return $this->template->render('server/privileges/add_user_fieldset', ['url_params' => $urlParams]);
}
/**

View File

@ -270,7 +270,6 @@ class Url
'hostname',
'dbname',
'tablename',
'checkprivsdb',
];
$paramsToEncrypt = [];
foreach ($params as $paramKey => $paramValue) {

View File

@ -71,6 +71,7 @@ return static function (RouteCollector $routes): void {
$routes->addRoute(['GET', 'POST'], '', Database\OperationsController::class);
$routes->post('/collation', Database\Operations\CollationController::class);
});
$routes->get('/privileges', Database\PrivilegesController::class);
$routes->addRoute(['GET', 'POST'], '/qbe', Database\QueryByExampleController::class);
$routes->addRoute(['GET', 'POST'], '/routines', Database\RoutinesController::class);
$routes->addRoute(['GET', 'POST'], '/search', Database\SearchController::class);

View File

@ -6706,10 +6706,7 @@
</MixedArgumentTypeCoercion>
<MixedAssignment occurrences="6">
<code>$info</code>
<code>$params['checkprivsdb']</code>
<code>$params['checkprivstable']</code>
<code>$params['single_table']</code>
<code>$params['viewing_mode']</code>
<code>$subObject</code>
</MixedAssignment>
<MixedReturnTypeCoercion occurrences="2">

View File

@ -132,7 +132,7 @@
<a id="add_user_anchor" href="{{ url('/server/privileges', {
'adduser': true,
'dbname': db
}) }}" rel="{{ get_common({'checkprivsdb': db}) }}">
}) }}">
{{ get_icon('b_usradd', 'Add user account'|trans) }}
</a>
</fieldset>

View File

@ -235,10 +235,7 @@
<td class="tool">
<a class="server_databases" data="
{{- database.name }}" href="{{ url('/server/privileges', {
'db': database.name,
'checkprivsdb': database.name
}) }}" title="
{{- database.name }}" href="{{ url('/database/privileges', {'db': database.name}) }}" title="
{{- 'Check privileges for database "%s".'|trans|format(database.name) }}">
{{ get_icon('s_rights', 'Check privileges'|trans) }}
</a>

View File

@ -2,10 +2,7 @@
<div class="col-12">
<fieldset class="pma-fieldset" id="fieldset_add_user">
<legend>{% trans %}New{% context %}Create new user{% endtrans %}</legend>
<a id="add_user_anchor" href="{{ url('/server/privileges', url_params) }}"
{% if rel_params is not empty %}
rel="{{ get_common(rel_params) }}"
{% endif %}>
<a id="add_user_anchor" href="{{ url('/server/privileges', url_params) }}">
{{ get_icon('b_usradd') }}{% trans 'Add user account' %}</a>
</fieldset>
</div>

View File

@ -4,7 +4,7 @@
{% if tmp_initial is not same as(null) %}
{% if initial_was_found %}
<li class="page-item{{ initial is same as(tmp_initial) ? ' active' }}"{{ initial is same as(tmp_initial) ? ' aria-current="page"' }}>
<a class="page-link" href="{{ url('/server/privileges', {'viewing_mode': viewing_mode, 'initial': tmp_initial}) }}">{{ tmp_initial }}</a>
<a class="page-link" href="{{ url('/server/privileges', {'initial': tmp_initial}) }}">{{ tmp_initial }}</a>
</li>
{% else %}
<li class="page-item disabled">
@ -14,7 +14,7 @@
{% endif %}
{% endfor %}
<li class="page-item">
<a class="page-link text-nowrap" href="{{ url('/server/privileges', {'viewing_mode': viewing_mode, 'showall': true}) }}">{% trans 'Show all' %}</a>
<a class="page-link text-nowrap" href="{{ url('/server/privileges', {'showall': true}) }}">{% trans 'Show all' %}</a>
</li>
</ul>
</nav>

View File

@ -1,7 +1,7 @@
<div class="row">
<ul class="nav nav-pills m-2">
<li class="nav-item">
<a class="nav-link{{ active == 'privileges' ? ' active' }}" href="{{ url('/server/privileges', {'viewing_mode': 'server'}) }}">
<a class="nav-link{{ active == 'privileges' ? ' active' }}" href="{{ url('/server/privileges') }}">
{% trans 'User accounts overview' %}
</a>
</li>

View File

@ -5,10 +5,10 @@ declare(strict_types=1);
namespace PhpMyAdmin\Tests\Controllers\Database;
use PhpMyAdmin\Controllers\Database\PrivilegesController;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Server\Privileges;
use PhpMyAdmin\Template;
use PhpMyAdmin\Tests\AbstractTestCase;
use PhpMyAdmin\Tests\Stubs\ResponseRenderer;
use PhpMyAdmin\Url;
use function __;
@ -31,23 +31,34 @@ class PrivilegesControllerTest extends AbstractTestCase
public function testIndex(): void
{
$GLOBALS['db'] = 'db';
$GLOBALS['db'] = 'test_db';
$GLOBALS['server'] = 0;
$GLOBALS['cfg']['Server']['DisableIS'] = false;
$GLOBALS['PMA_PHP_SELF'] = 'index.php';
$this->dummyDbi->addResult(
'SHOW TABLES FROM `test_db`;',
[['test_table']],
['Tables_in_test_db']
);
// phpcs:disable Generic.Files.LineLength.TooLong
$this->dummyDbi->addResult(
'SELECT *, `TABLE_SCHEMA` AS `Db`, `TABLE_NAME` AS `Name`, `TABLE_TYPE` AS `TABLE_TYPE`, `ENGINE` AS `Engine`, `ENGINE` AS `Type`, `VERSION` AS `Version`, `ROW_FORMAT` AS `Row_format`, `TABLE_ROWS` AS `Rows`, `AVG_ROW_LENGTH` AS `Avg_row_length`, `DATA_LENGTH` AS `Data_length`, `MAX_DATA_LENGTH` AS `Max_data_length`, `INDEX_LENGTH` AS `Index_length`, `DATA_FREE` AS `Data_free`, `AUTO_INCREMENT` AS `Auto_increment`, `CREATE_TIME` AS `Create_time`, `UPDATE_TIME` AS `Update_time`, `CHECK_TIME` AS `Check_time`, `TABLE_COLLATION` AS `Collation`, `CHECKSUM` AS `Checksum`, `CREATE_OPTIONS` AS `Create_options`, `TABLE_COMMENT` AS `Comment` FROM `information_schema`.`TABLES` t WHERE `TABLE_SCHEMA` IN (\'test_db\') ORDER BY Name ASC LIMIT 250 OFFSET 0',
[['def', 'test_db', 'test_table', 'BASE TABLE', 'InnoDB', '10', 'Dynamic', '3', '5461', '16384', '0', '0', '0', '4', '2011-12-13 14:15:16', null, null, 'utf8mb4_general_ci', null, '', '', '0', 'N', 'test_db', 'test_table', 'BASE TABLE', 'InnoDB', 'InnoDB', '10', 'Dynamic', '3', '5461', '16384', '0', '0', '0', '4', '2011-12-13 14:15:16', null, null, 'utf8mb4_general_ci', null, '', '']],
['TABLE_CATALOG', 'TABLE_SCHEMA', 'TABLE_NAME', 'TABLE_TYPE', 'ENGINE', 'VERSION', 'ROW_FORMAT', 'TABLE_ROWS', 'AVG_ROW_LENGTH', 'DATA_LENGTH', 'MAX_DATA_LENGTH', 'INDEX_LENGTH', 'DATA_FREE', 'AUTO_INCREMENT', 'CREATE_TIME', 'UPDATE_TIME', 'CHECK_TIME', 'TABLE_COLLATION', 'CHECKSUM', 'CREATE_OPTIONS', 'TABLE_COMMENT', 'MAX_INDEX_LENGTH', 'TEMPORARY', 'Db', 'Name', 'TABLE_TYPE', 'Engine', 'Type', 'Version', 'Row_format', 'Rows', 'Avg_row_length', 'Data_length', 'Max_data_length', 'Index_length', 'Data_free', 'Auto_increment', 'Create_time', 'Update_time', 'Check_time', 'Collation', 'Checksum', 'Create_options', 'Comment']
);
// phpcs:enable
$privileges = [];
$serverPrivileges = $this->createMock(Privileges::class);
$serverPrivileges->method('getAllPrivileges')
->willReturn($privileges);
$actual = (new PrivilegesController(
ResponseRenderer::getInstance(),
new Template(),
$serverPrivileges,
$GLOBALS['dbi']
))(['checkprivsdb' => $GLOBALS['db']]);
$response = new ResponseRenderer();
(new PrivilegesController($response, new Template(), $serverPrivileges, $GLOBALS['dbi']))();
$actual = $response->getHTMLResult();
$this->assertStringContainsString(
Url::getCommon(['db' => $GLOBALS['db']], ''),
@ -86,9 +97,5 @@ class PrivilegesControllerTest extends AbstractTestCase
_pgettext('Create new user', 'New'),
$actual
);
$this->assertStringContainsString(
Url::getCommon(['checkprivsdb' => $GLOBALS['db']]),
$actual
);
}
}

View File

@ -54,8 +54,6 @@ class PrivilegesControllerTest extends AbstractTestCase
);
// phpcs:enable
$_GET = ['viewing_mode' => 'server'];
$response = new ResponseRenderer();
(new PrivilegesController($response, new Template(), new Relation($this->dbi), $this->dbi))();