Debian Codegraph @

utils/users_admin.php

raw symbols SCIP
1 <?php
2
3 /**
4 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
5 * Copyright (C) 2024 Aleksey Andreev (liuch)
6 *
7 * Available at:
8 * https://github.com/liuch/dmarc-srg
9 *
10 * This program is free software: you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the Free
12 * Software Foundation, either version 3 of the License.
13 *
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 * more details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * =========================
23 *
24 * This script is designed to manipulate the list of users in the database.
25 * Usage: php users_admin.php <command> [<args>]
26 * The available commands are:
27 * `list` - Outputs a list of users sorted by username. No parameters.
28 * `add` - Adds a new user to the database. Parameters:
29 * name=<username> Required.
30 * level=<user|manager> Access level. Optional. The default value is user.
31 * enabled=<true|false> Optional. The default value is false. The valid values are:
32 * true, false, 1, 0, yes, no. The value is case insensitive.
33 * `show` - Displays user information. Parameters:
34 * id=<user ID>|name=<username> Required.
35 * `modify` - Modifies a user. Parameters:
36 * id=<user ID>|name=<username> Required.
37 * level=<user|manager> Access level. Optional. The default value is user.
38 * enabled=<true|false> Optional.
39 * Note: This command changes only the specified user data. The rest of the data remains unchanged.
40 * `setpassword` - Changes user's password. Parameters:
41 * id=<user ID>|name=<username> Required.
42 * password=<user password> Required.
43 * `domains` - Assigns or unassigns domains to a user. Paremeters:
44 * id=<user ID>|name=<username> Required.
45 * add=<user name> Optional.
46 * remove=<user name> Optional.
47 * `delete` - Deletes a user from the database. Parameters:
48 * id=<user ID>|name=<username> Required.
49 *
50 * Some some examples:
51 *
52 * $php utils/users_admin.php list
53 * will display a list of users from the database
54 *
55 * $php utils/users_admin.php add name=cooluser enabled=yes level=user
56 * will create a new user named cooluser and assign it "user" access level.
57 *
58 * $php utils/users_admin.php show id=1
59 * will display information about the user with ID=1
60 *
61 * $php utils/users_admin.php show name=cooluser
62 * will display information about the user cooluser
63 *
64 * $php utils/users_admin.php modify id=1 enabled=no
65 * will deactivate the user with ID=1
66 *
67 * $php utils/users_admin.php domains id=1 add=a.net
68 * will assign the domain a.net to the user with ID=1
69 *
70 * $php utils/users_admin.php delete name=baduser
71 * will delete the user named baduser
72 *
73 * @category Utilities
74 * @package DmarcSrg
75 * @author Aleksey Andreev (liuch)
76 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
77 */
78
79 namespace Liuch\DmarcSrg;
80
81 use Liuch\DmarcSrg\Users\User;
82 use Liuch\DmarcSrg\Users\DbUser;
83 use Liuch\DmarcSrg\Users\UserList;
84 use Liuch\DmarcSrg\Domains\Domain;
85 use Liuch\DmarcSrg\Domains\DomainList;
86 use Liuch\DmarcSrg\Exception\SoftException;
87 use Liuch\DmarcSrg\Exception\RuntimeException;
88
89 require realpath(__DIR__ . '/..') . '/init.php';
90
91 if (Core::isWEB()) {
92 echo 'Forbidden';
93 exit(1);
94 }
95
96 if (!isset($argv)) {
97 echo 'Cannot get the script arguments. Probably register_argc_argv is disabled.', PHP_EOL;
98 exit(1);
99 }
100
101 $parseArguments = function (array $allowed) use (&$argv): array {
102 $res = [];
103 for ($i = 2; $i < count($argv); ++$i) {
104 $av = explode('=', $argv[$i], 2);
105 if (count($av) == 1 || !in_array($av[0], $allowed)) {
106 throw new SoftException("Incorrect parameter \"{$av[0]}\"");
107 }
108 $res[$av[0]] = $av[1];
109 }
110 return $res;
111 };
112 $getLevelParameter = function (array $args) {
113 $lvl = strtolower($args['level']);
114 if ($lvl === 'admin') {
115 $lvl = '';
116 }
117 try {
118 $nlvl = User::stringToLevel($lvl);
119 } catch (SoftException $e) {
120 throw new SoftException('Incorrect user level. The valid values are: "user", "manager"');
121 }
122 return $nlvl;
123 };
124 $getEnabledParameter = function (array $args) {
125 $ac = array_search(strtolower($args['enabled']), [ '', '0', 'false', 'no', '1', 'true', 'yes' ], true);
126 if ($ac === false) {
127 throw new SoftException('Incorrect value of the "enabled" paramenter');
128 }
129 return $ac > 3;
130 };
131 $getUser = function (array $args) {
132 if (isset($args['id'])) {
133 if (isset($args['name'])) {
134 throw new SoftException('To identify a user you need to specify either its id or name, not both');
135 }
136 $id = filter_var($args['id'], FILTER_VALIDATE_INT, [ 'options' => [ 'min_range' => 0 ] ]);
137 if (!$id) {
138 throw new SoftException('Incorrect user ID');
139 }
140 $user = new DbUser($id);
141 } elseif (!empty($args['name'])) {
142 $user = new DbUser($args['name']);
143 } else {
144 throw new SoftException('Either the "id" or "name" parameter must be specified');
145 }
146 return $user;
147 };
148
149 try {
150 Core::instance()->setCurrentUser('admin');
151 $action = $argv[1] ?? '';
152 switch ($action) {
153 case 'list':
154 $parseArguments([]);
155 $list = (new UserList())->getList()['users'];
156 $table = new TextTable([ 'ID', 'Name', 'Level', 'Enabled', 'Domains', 'Updated' ]);
157 foreach ($list as $user) {
158 $ua = $user->toArray();
159 $table->appendRow([
160 $user->id(),
161 $ua['name'],
162 User::levelToString($ua['level']),
163 $ua['enabled'] ? '+' : '',
164 $ua['domains'],
165 $ua['updated_time']->format('c')
166 ]);
167 }
168 $table->setMinColumnWidth(1, 10)->sortBy(1)->output();
169 break;
170 case 'add':
171 $args = $parseArguments([ 'name', 'level', 'enabled' ]);
172 if (empty($args['name'])) {
173 throw new SoftException('Parameter "name" must be specified');
174 }
175 $ud = [ 'name' => $args['name'] ];
176 $ud['level'] = isset($args['level']) ? $getLevelParameter($args) : User::LEVEL_USER;
177 $ud['enabled'] = isset($args['enabled']) ? $getEnabledParameter($args) : false;
178 $user = new DbUser($ud);
179 $user->ensure('nonexist');
180 $user->save();
181 echo 'Done.', PHP_EOL;
182 break;
183 case 'show':
184 $user = $getUser($parseArguments([ 'id', 'name' ]));
185 $ud = $user->toArray();
186 $domains = (new DomainList($user))->names();
187 echo 'ID: ', $user->id(), PHP_EOL;
188 echo 'Name: ', $ud['name'], PHP_EOL;
189 echo 'Level: ', User::levelToString($ud['level']), PHP_EOL;
190 echo 'Enabled: ', $ud['enabled'] ? 'Yes' : 'No', PHP_EOL;
191 echo 'Password: ', $ud['password'] ? 'Yes' : 'No', PHP_EOL;
192 echo 'Domains: ', ($domains ? implode(', ', $domains) : 'None'), PHP_EOL;
193 echo 'Created: ', $ud['created_time']->format('c'), PHP_EOL;
194 echo 'Updated: ', $ud['updated_time']->format('c'), PHP_EOL;
195 break;
196 case 'modify':
197 $args = $parseArguments([ 'id', 'name', 'level', 'enabled' ]);
198 $user = $getUser($args);
199 $user->ensure('exist');
200 $mf = false;
201 $ud = $user->toArray();
202 if (isset($args['enabled'])) {
203 $en = $getEnabledParameter($args);
204 if ($ud['enabled'] !== $en) {
205 $ud['enabled'] = $en;
206 $mf = true;
207 }
208 }
209 if (isset($args['level'])) {
210 $lvl = $getLevelParameter($args);
211 if ($lvl !== $ud['level']) {
212 $ud['level'] = $getLevelParameter($args);
213 $mf = true;
214 }
215 }
216 if ($mf) {
217 (new DbUser($ud))->save();
218 echo 'Done.', PHP_EOL;
219 } else {
220 echo 'There is nothing to change', PHP_EOL;
221 }
222 break;
223 case 'setpassword':
224 $args = $parseArguments([ 'id', 'name', 'password' ]);
225 $user = $getUser($args);
226 if (empty($args['password'])) {
227 throw new SoftException('The password must not be empty');
228 }
229 $user->ensure('exist');
230 $user->setPassword($args['password']);
231 echo 'Done.', PHP_EOL;
232 break;
233 case 'domains':
234 $args = $parseArguments([ 'id', 'name', 'add', 'remove' ]);
235 $user = $getUser($args);
236 $action = null;
237 $mf = 0;
238 foreach ([ 'add', 'remove' ] as $a) {
239 if (isset($args[$a])) {
240 $action = $a;
241 if ($mf++) {
242 break;
243 }
244 }
245 }
246 if ($mf === 1) {
247 $user->ensure('exist');
248 $domain = new Domain($args[$action]);
249 $domain->ensure('exist');
250 if (!empty($args['add'])) {
251 $domain->assignUser($user);
252 } elseif (!empty($args['remove'])) {
253 $domain->unassignUser($user);
254 }
255 echo 'Done.', PHP_EOL;
256 } elseif ($mf === 0) {
257 echo 'There is nothing to change', PHP_EOL;
258 } else {
259 throw new SoftException('You can specify only one of the actions for this command');
260 }
261 break;
262 case 'delete':
263 $user = $getUser($parseArguments([ 'id', 'name' ]));
264 $user->ensure('exist');
265 $user->delete();
266 echo 'Done.', PHP_EOL;
267 break;
268 default:
269 echo 'Unknown command ', $action, PHP_EOL, PHP_EOL;
270 // no break needed
271 case '':
272 echo "Usage: {$argv[0]} <command> [<parameters>]", PHP_EOL, PHP_EOL;
273 echo 'Commands:', PHP_EOL;
274 echo ' list Outputs a list of users sorted by username. No parameters.', PHP_EOL;
275 echo ' add Adds a new user to the database.', PHP_EOL;
276 echo ' Required parameter: name.', PHP_EOL;
277 echo ' Optional parameters: enabled, level.', PHP_EOL;
278 echo ' show Displays user information.', PHP_EOL;
279 echo ' Required parameters: id or name.', PHP_EOL;
280 echo ' modify Makes changes to a user record.', PHP_EOL;
281 echo ' Required parameters: id or name.', PHP_EOL;
282 echo ' Optional parameters: level, enabled.', PHP_EOL;
283 echo ' setpassword Changes user\'s password.', PHP_EOL;
284 echo ' Required parameters: id or name and password.', PHP_EOL;
285 echo ' domains Assigns or unassigns domains to a user.', PHP_EOL;
286 echo ' Required parameters: id or name.', PHP_EOL;
287 echo ' Required parameters: add or remove.', PHP_EOL;
288 echo ' delete Deletes a user record from the database.', PHP_EOL;
289 echo ' Required parameters: id or name.', PHP_EOL, PHP_EOL;
290 echo 'Parameters:', PHP_EOL;
291 echo ' id User internal ID. Cannot be changed.', PHP_EOL;
292 echo ' Used for user identification only.', PHP_EOL;
293 echo ' name User name. Cannot be changed.', PHP_EOL;
294 echo ' Used when adding a user and for it identification.', PHP_EOL;
295 echo ' level User access level. It can have one of the following values: user, manager.', PHP_EOL;
296 echo ' enabled Whether the user is active or not. One of the following values:', PHP_EOL;
297 echo ' 1, 0, yes, no, true, false.', PHP_EOL;
298 echo ' password Password string. Used with the setpassword command.', PHP_EOL;
299 echo ' add String with domain to be assigned. Used with the domains command.', PHP_EOL;
300 echo ' remove String with domain to be unassigned. Used with the domains command.', PHP_EOL;
301 exit(1);
302 }
303 } catch (SoftException $e) {
304 echo 'Error: ' . $e->getMessage() . PHP_EOL;
305 exit(1);
306 } catch (RuntimeException $e) {
307 echo ErrorHandler::exceptionText($e);
308 exit(1);
309 }
310
311 exit(0);