lnms user:add command (#9830)

* Add lnms user:add command
Uses events to mark past notifications as read (even for non-manually added users)

* Filter out previous options from auto-completion

* use validation to check cli input

* Warn if using other auth

* abstract LnmsCommand

* Use setPassword helper for hashing instead of mutator

* Extract validation function
This commit is contained in:
Tony Murray
2019-02-15 09:00:07 -06:00
committed by GitHub
parent a41f1d9608
commit a4b79d3339
9 changed files with 345 additions and 22 deletions

View File

@@ -0,0 +1,101 @@
<?php
/**
* AddUserCommand.php
*
* CLI command to add a user to LibreNMS
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2019 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace App\Console\Commands;
use App\Console\LnmsCommand;
use App\Models\User;
use Illuminate\Validation\Rule;
use LibreNMS\Config;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
class AddUserCommand extends LnmsCommand
{
protected $name = 'user:add';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->setDescription(__('commands.user:add.description'));
$this->addArgument('username', InputArgument::REQUIRED);
$this->addOption('password', 'p', InputOption::VALUE_REQUIRED);
$this->addOption('role', 'r', InputOption::VALUE_REQUIRED, __('commands.user:add.options.role', ['roles' => '[normal, global-read, admin]']), 'normal');
$this->addOption('email', 'e', InputOption::VALUE_REQUIRED);
$this->addOption('full-name', 'l', InputOption::VALUE_REQUIRED);
$this->addOption('descr', 's', InputOption::VALUE_REQUIRED);
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if (Config::get('auth_mechanism') != 'mysql') {
$this->warn(__('commands.user:add.wrong-auth'));
}
$roles = [
'normal' => 1,
'global-read' => 5,
'admin' => 10
];
$this->validate([
'username' => ['required', Rule::unique('users', 'username')->where('auth_type', 'mysql')],
'email' => 'email',
'role' => Rule::in(array_keys($roles))
]);
// set get password
$password = $this->option('password');
if (!$password) {
$password = $this->secret(__('commands.user:add.password-request'));
}
$user = new User([
'username' => $this->argument('username'),
'level' => $roles[$this->option('role')],
'descr' => (string)$this->option('descr'),
'email' => (string)$this->option('email'),
'realname' => (string)$this->option('full-name'),
'auth_type' => 'mysql',
]);
$user->setPassword($password);
$user->save();
$this->info(__('commands.user:add.success', ['username' => $user->username]));
return 0;
}
}

View File

@@ -54,7 +54,7 @@ class BashCompletionCommand extends Command
if (!starts_with($previous, '-')) {
$completions = $this->completeArguments($command, $current, end($words));
}
$completions = $completions->merge($this->completeOption($command_def, $current));
$completions = $completions->merge($this->completeOption($command_def, $current, $this->getPreviousOptions($words)));
}
}
}
@@ -110,9 +110,10 @@ class BashCompletionCommand extends Command
*
* @param InputDefinition $command
* @param string $partial
* @param array $prev_options Previous words in the command
* @return \Illuminate\Support\Collection
*/
private function completeOption($command, $partial)
private function completeOption($command, $partial, $prev_options)
{
// default options
$options = collect([
@@ -132,8 +133,13 @@ class BashCompletionCommand extends Command
if ($command) {
$options = collect($command->getOptions())
->flatMap(function ($option) {
return $this->parseOption($option);
->flatMap(function ($option) use ($prev_options) {
$option_flags = $this->parseOption($option);
// don't return previously specified options
if (array_intersect($option_flags, $prev_options)) {
return [];
}
return $option_flags;
})->merge($options);
}
@@ -142,6 +148,17 @@ class BashCompletionCommand extends Command
});
}
private function getPreviousOptions($words)
{
return array_reduce($words, function ($result, $word) {
if (starts_with($word, '-')) {
$split = explode('=', $word, 2); // users may use equals for values
$result[] = reset($split);
}
return $result;
}, []);
}
/**
* Complete options with values (if a list is enumerate in the description)
*

113
app/Console/LnmsCommand.php Normal file
View File

@@ -0,0 +1,113 @@
<?php
/**
* LnmsCommand.php
*
* Convenience class for common command code
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2019 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace App\Console;
use Illuminate\Console\Command;
use Illuminate\Validation\ValidationException;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Validator;
abstract class LnmsCommand extends Command
{
protected $developer = false;
public function isHidden()
{
return $this->hidden || ($this->developer && $this->getLaravel()->environment() !== 'production');
}
/**
* Adds an argument. If $description is null, translate commands.command-name.arguments.name
* If you want the description to be empty, just set an empty string
*
* @param string $name The argument name
* @param int|null $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
* @param string $description A description text
* @param string|string[]|null $default The default value (for InputArgument::OPTIONAL mode only)
*
* @throws InvalidArgumentException When argument mode is not valid
*
* @return $this
*/
public function addArgument($name, $mode = null, $description = null, $default = null)
{
// use a generated translation location by default
if (is_null($description)) {
$description = __('commands.' . $this->getName() . '.arguments.' . $name);
}
parent::addArgument($name, $mode, $description, $default);
return $this;
}
/**
* Adds an option. If $description is null, translate commands.command-name.arguments.name
* If you want the description to be empty, just set an empty string
*
* @param string $name The option name
* @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
* @param int|null $mode The option mode: One of the InputOption::VALUE_* constants
* @param string $description A description text
* @param string|string[]|int|bool|null $default The default value (must be null for InputOption::VALUE_NONE)
*
* @throws InvalidArgumentException If option mode is invalid or incompatible
*
* @return $this
*/
public function addOption($name, $shortcut = null, $mode = null, $description = null, $default = null)
{
// use a generated translation location by default
if (is_null($description)) {
$description = __('commands.' . $this->getName() . '.options.' . $name);
}
parent::addOption($name, $shortcut, $mode, $description, $default);
return $this;
}
/**
* Validate the input of this command. Uses Laravel input validation
* merging the arguments and options together to check.
*
* @param array $rules
* @param array $messages
*/
protected function validate($rules, $messages = [])
{
$validator = Validator::make($this->arguments() + $this->options(), $rules, $messages);
try {
$validator->validate();
} catch (ValidationException $e) {
collect($validator->getMessageBag()->all())->each(function ($message) {
$this->error($message);
});
exit(1);
}
}
}