Debian Codegraph @

pkg/users/account-create-dialog.js

raw
1 /*
2 * Copyright (C) 2020 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from 'cockpit';
7 import React from 'react';
8
9 import { Bullseye } from "@patternfly/react-core/dist/esm/layouts/Bullseye/index.js";
10 import { Checkbox } from "@patternfly/react-core/dist/esm/components/Checkbox/index.js";
11 import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
12 import { FormSelect, FormSelectOption } from "@patternfly/react-core/dist/esm/components/FormSelect/index.js";
13 import { TextInput } from "@patternfly/react-core/dist/esm/components/TextInput/index.js";
14 import { Popover } from "@patternfly/react-core/dist/esm/components/Popover/index.js";
15 import { Flex, FlexItem } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
16 import { Radio } from "@patternfly/react-core/dist/esm/components/Radio/index.js";
17 import { Spinner } from "@patternfly/react-core/dist/esm/components/Spinner/index.js";
18 import { has_errors, is_valid_char_name } from "./dialog-utils.js";
19 import { passwd_change } from "./password-dialogs.js";
20 import { FormHelper } from "cockpit-components-form-helper";
21 import { password_quality, PasswordFormFields } from "cockpit-components-password.jsx";
22 import { show_modal_dialog, apply_modal_dialog } from "cockpit-components-dialog.jsx";
23 import { HelpIcon } from '@patternfly/react-icons';
24
25 const _ = cockpit.gettext;
26
27 function get_default_home_dir(base_home_dir, user_name) {
28 return base_home_dir && user_name
29 ? base_home_dir + '/' + user_name
30 : "";
31 }
32
33 function AccountCreateBody({ state, errors, change, shells }) {
34 const {
35 real_name, user_name,
36 locked, change_passw_force,
37 shell,
38 } = state;
39
40 // We want to let user know that password and confirmation password do not match without them having to constantly click on "Create" to validate the form.
41 // But we also don't want to show an error message while they are typing the confirmation password, only when they are finished typing it.
42 // To solve the issue of telling that user is finished writing the confirmation password, let's do the following:
43 // The dialog does not validate if passwords match until:
44 // 1. they are at least the same length (which signals user has finished typing)
45 // OR
46 // 2. user submits the form (which also signals they are finished typing)
47 // Once that happens, and passwords do not match, the confirm password is validated after each keystroke.
48 let dynamic_password_confirm_error;
49 if (state.password_confirm_dirty)
50 dynamic_password_confirm_error = validate_password_confirm(state.password_confirm, state.password);
51
52 return (
53 <Form isHorizontal onSubmit={apply_modal_dialog}>
54 <FormGroup label={_("Full name")}
55 fieldId="accounts-create-real-name">
56 <TextInput id="accounts-create-real-name"
57 validated={(errors?.real_name) ? "error" : "default"}
58 value={real_name} onChange={(_event, value) => change("real_name", value)} />
59 <FormHelper fieldId="accounts-create-real-name" helperTextInvalid={errors?.real_name} />
60 </FormGroup>
61
62 <FormGroup label={_("User name")}
63 fieldId="accounts-create-user-name">
64 <TextInput id="accounts-create-user-name"
65 validated={(errors?.user_name) ? "error" : "default"}
66 value={user_name} onChange={(_event, value) => change("user_name", value)} />
67 <FormHelper fieldId="accounts-create-user-name" helperTextInvalid={errors?.user_name} />
68 </FormGroup>
69
70 <FormGroup label={_("Home directory")}
71 fieldId="accounts-create-user-home-dir">
72 <TextInput id="accounts-create-user-home-dir"
73 onChange={(_event, value) => change("home_dir", value)}
74 placeholder={_("Path to directory")}
75 value={state.home_dir} />
76 <FormHelper fieldId="accounts-create-user-home-dir" helperTextInvalid={errors?.home_dir} />
77 </FormGroup>
78
79 <FormGroup label={_("Shell")}
80 fieldId="accounts-create-user-shell">
81 <FormSelect
82 data-selected={shell}
83 id="accounts-create-user-shell"
84 onChange={(_, selection) => { change("shell", selection) }}
85 value={shell}>
86 { shells.map(shell_path => <FormSelectOption key={shell_path} value={shell_path} label={shell_path} />) }
87 </FormSelect>
88 </FormGroup>
89
90 <FormGroup label={_("User ID")}
91 fieldId="accounts-create-user-uid">
92 <TextInput id="accounts-create-user-uid"
93 onChange={(_event, value) => change("uid", value)}
94 value={state.uid} />
95 <FormHelper fieldId="accounts-create-user-uid" helperTextInvalid={errors?.uid} />
96 </FormGroup>
97
98 <FormGroup label={_("Authentication")} fieldId="accounts-create-locked" hasNoPaddingTop>
99 <Radio id="account-use-password"
100 label={_("Use password")}
101 isChecked={!locked} onChange={(_, checked) => change("locked", !checked)}
102 description={
103 <Checkbox id="accounts-create-force-password-change"
104 className="pf-v6-u-mb-xs"
105 label={_("Require password change on first login")}
106 isChecked={change_passw_force} onChange={(_event, checked) => change("change_passw_force", checked)} />
107 } />
108
109 <Flex spaceItems={{ default: 'spaceItemsSm' }} alignItems={{ default: 'alignItemsCenter' }}>
110 <FlexItem spacer={{ default: 'spacerNone' }}>
111 <Radio id="accounts-create-locked"
112 isChecked={locked} onChange={(_, checked) => change("locked", checked)}
113 label={_("Disallow password authentication")} />
114 </FlexItem>
115
116 <FlexItem spacer={{ default: 'spacerNone' }}>
117 <Popover bodyContent={_("Other authentication methods are still available even when interactive password authentication is not allowed.")}
118 showClose={false}>
119 <HelpIcon />
120 </Popover>
121 </FlexItem>
122 </Flex>
123 </FormGroup>
124
125 <PasswordFormFields password_label={_("Password")}
126 password_confirm_label={_("Confirm password")}
127 error_password={errors?.password}
128 error_password_confirm={dynamic_password_confirm_error || errors?.password_confirm}
129 idPrefix="accounts-create-password"
130 change={change} />
131 </Form>
132 );
133 }
134
135 function validate_username(username, accounts) {
136 if (!username)
137 return _("No user name specified");
138
139 for (let i = 0; i < username.length; i++) {
140 if (!is_valid_char_name(username[i]))
141 return _("The user name can only consist of letters from a-z, digits, dots, dashes and underscores.");
142 }
143
144 for (let k = 0; k < accounts.length; k++) {
145 if (accounts[k].name == username)
146 return _("This user name already exists");
147 }
148
149 return null;
150 }
151
152 function validate_real_name(real_name) {
153 if (!real_name)
154 return _("No real name specified");
155
156 const real_name_chars = Array.from(real_name);
157 if (real_name_chars.includes(':'))
158 return _("The full name must not contain colons.");
159 }
160
161 function validate_uid(uid, accounts, min_uid, max_uid, change) {
162 if (!uid)
163 return undefined;
164
165 const uid_number = Number(uid);
166 if (!Number.isInteger(uid_number) || uid_number < 0)
167 return _("User ID must be a positive integer");
168
169 if (min_uid && uid_number < min_uid)
170 return cockpit.format(_("User ID must not be lower than $0"), min_uid);
171
172 if (max_uid && uid_number > max_uid)
173 return cockpit.format(_("User ID must not be higher than $0"), max_uid);
174
175 if (accounts.some(account => account.uid === uid_number)) {
176 change("uid_exists", true);
177 return _("User ID is already used by another user");
178 }
179 }
180
181 function validate_home_dir(dir, directoryExpected) {
182 return cockpit.spawn(["test", "!", directoryExpected ? "-d" : "-f", dir], { superuser: "require" });
183 }
184
185 function validate_password(password) {
186 if (!password)
187 return _("Empty password");
188
189 return null;
190 }
191
192 function validate_password_confirm(password_confirm, password) {
193 if (password_confirm !== password)
194 return _("The passwords do not match");
195
196 return null;
197 }
198
199 function suggest_username(realname) {
200 function remove_diacritics(str) {
201 const translate_table = {
202 a: '[àáâãäå]',
203 ae: 'æ',
204 c: '[čç]',
205 d: 'ď',
206 e: '[èéêë]',
207 i: '[íìïî]',
208 l: '[ĺľ]',
209 n: '[ňñ]',
210 o: '[òóôõö]',
211 oe: 'œ',
212 r: '[ŕř]',
213 s: 'š',
214 t: 'ť',
215 u: '[ùúůûűü]',
216 y: '[ýÿ]',
217 z: 'ž',
218 };
219 for (const i in translate_table)
220 str = str.replace(new RegExp(translate_table[i], 'g'), i);
221
222 for (let k = 0; k < str.length;) {
223 if (!is_valid_char_name(str[k]))
224 str = str.substring(0, k) + str.substring(k + 1);
225 else
226 k++;
227 }
228
229 return str;
230 }
231
232 let result = "";
233 const name = realname.split(' ');
234
235 if (name.length === 1)
236 result = name[0].toLowerCase();
237 else if (name.length > 1)
238 result = name[0][0].toLowerCase() + name[name.length - 1].toLowerCase();
239
240 return remove_diacritics(result);
241 }
242
243 export function account_create_dialog(accounts, min_uid, max_uid, shells) {
244 let dlg = null;
245
246 const used_ids = accounts.map(a => a.uid);
247 const uid = Math.max(min_uid, Math.max(...used_ids.filter(id => id < max_uid)) + 1);
248
249 const state = {
250 dialogLoading: true,
251 real_name: "",
252 user_name: "",
253 password: "",
254 password_confirm: "",
255 password_confirm_dirty: false,
256 locked: false,
257 confirm_weak: false,
258 change_passw_force: false,
259 base_home_dir: null,
260 shell: "",
261 uid,
262 uid_exists: false,
263 min_uid,
264 max_uid,
265 home_dir: "",
266 home_dir_dirty: false,
267 };
268 let errors = { };
269
270 let old_password = null;
271 let user_name_dirty = false;
272
273 function get_defaults() {
274 return cockpit.spawn(["useradd", "-D"], { superuser: "require", err: "message" })
275 .then(defaults => {
276 let shell = "";
277 let base_home_dir = null;
278 defaults.split("\n").forEach(item => {
279 if (item.indexOf("SHELL=") === 0) {
280 shell = item.split("=")[1] || "/bin/bash";
281 } else if (item.indexOf("HOME=") === 0) {
282 base_home_dir = item.split("=")[1] || "";
283 }
284 });
285 change("shell", shell);
286 change("base_home_dir", base_home_dir);
287 })
288 .catch(e => console.warn("Could not get useradd defaults: ", e.message))
289 .finally(() => change("dialogLoading", false));
290 }
291
292 function change(field, value) {
293 state[field] = value;
294 errors = { };
295
296 if (field == "user_name") {
297 user_name_dirty = true;
298 if (!state.home_dir_dirty)
299 state.home_dir = get_default_home_dir(state.base_home_dir, value);
300 }
301
302 if (!user_name_dirty && field == "real_name") {
303 const suggested_username = suggest_username(state.real_name);
304 state.user_name = suggested_username;
305 if (!state.home_dir_dirty)
306 state.home_dir = get_default_home_dir(state.base_home_dir, suggested_username);
307 }
308
309 if (state.password != old_password) {
310 state.confirm_weak = false;
311 old_password = state.password;
312 }
313
314 if (field == "change_passw_force")
315 state.locked = false;
316
317 // Once password and confirm password are the same length, validate them after each keystroke
318 if (field == "password_confirm" && value.length >= state.password.length)
319 state.password_confirm_dirty = true;
320
321 if (field == "locked")
322 state.change_passw_force = false;
323
324 if (field == "uid")
325 state.uid_exists = false;
326
327 if (field == "home_dir") {
328 state.home_dir_dirty = true;
329 state.home_dir_exists = false;
330 state.home_dir_is_file = false;
331 }
332
333 update();
334 }
335
336 function validate(force_weak, force_home, force_uid, real_name, user_name, password, password_confirm, uid, accounts, min_uid, max_uid, change) {
337 const errs = { };
338
339 errs.real_name = validate_real_name(real_name);
340 errs.password = validate_password(password);
341 errs.password_confirm = validate_password_confirm(password_confirm, password);
342
343 if (password.length > 256)
344 errs.password = _("Password is longer than 256 characters");
345
346 errs.user_name = validate_username(user_name, accounts);
347
348 const promises = [];
349 // only evaluate password score if no other password error si present
350 if (!errs.password) {
351 promises.push(
352 password_quality(password, force_weak)
353 .catch(ex => {
354 errs.password = (ex.message || ex.toString()).replaceAll("\n", " "); // not-covered: OS error
355 })
356 );
357 }
358 if (!force_uid)
359 errs.uid = validate_uid(uid, accounts, min_uid, max_uid, change);
360
361 promises.push(
362 validate_home_dir(state.home_dir, false)
363 .catch(() => {
364 errs.home_dir = cockpit.format(_("$0 is an existing file"), state.home_dir);
365 state.home_dir_is_file = true;
366 })
367 );
368
369 if (!force_home) {
370 promises.push(
371 validate_home_dir(state.home_dir, true)
372 .catch(() => {
373 errs.home_dir = cockpit.format(_("The home directory $0 already exists. Its ownership will be changed to the new user."), state.home_dir);
374 state.home_dir_exists = true;
375 })
376 );
377 }
378
379 return Promise.all(promises)
380 .then(() => {
381 errors = errs;
382 return !has_errors(errs);
383 });
384 }
385
386 function create(real_name, user_name, password, locked, uid, force_change, home_dir, force_home, force_uid) {
387 const prog = ["useradd", "--create-home", "-s", state.shell];
388 if (real_name) {
389 prog.push('-c');
390 prog.push(real_name);
391 }
392
393 if (uid) {
394 prog.push('-u');
395 prog.push(uid);
396 }
397
398 if (force_uid)
399 prog.push('-o'); // Create user with non-unique user-specified UID, useful at certain use cases
400
401 if (home_dir) {
402 prog.push('-d');
403 prog.push(home_dir);
404 }
405
406 prog.push(user_name);
407 return cockpit.spawn(prog, { superuser: "require", err: "message" })
408 .then(() => passwd_change(user_name, password))
409 .then(() => {
410 if (locked)
411 return cockpit.spawn([
412 "usermod",
413 user_name,
414 "--lock"
415 ], { superuser: "require", err: "message" });
416 if (force_change)
417 return cockpit.spawn([
418 "passwd",
419 "-e",
420 user_name
421 ], { superuser: "require", err: "message" });
422 })
423 .then(() => {
424 if (force_home) {
425 return cockpit.spawn(["id", user_name, "--group"], { superuser: "require", err: "message" })
426 .then(gid => cockpit.spawn(["chown", "-hR", `${user_name}:${gid.trim()}`, home_dir], { superuser: "require", err: "message" }));
427 }
428 });
429 }
430
431 function passwd_check(force_weak, force_home, force_uid, real_name, user_name, password, password_confirm, locked, home_dir, force_passwd_change, uid, accounts, min_uid, max_uid, change) {
432 return validate(force_weak, force_home, force_uid, real_name, user_name, password, password_confirm, uid, accounts, min_uid, max_uid, change).then(valid => {
433 if (valid)
434 return create(real_name, user_name, password, locked, uid, force_passwd_change, home_dir, force_home, force_uid);
435 else {
436 if (!errors.real_name && !errors.user_name && !errors.home_dir && !errors.uid && !errors.password_confirm && state.password.length <= 256)
437 state.confirm_weak = true;
438
439 // Once the form is submitted and passwords do not match, validate confirm password after each keystroke
440 if (errors.password_confirm)
441 state.password_confirm_dirty = true;
442
443 update();
444 return Promise.reject();
445 }
446 });
447 }
448
449 function update() {
450 const props = {
451 id: "accounts-create-dialog",
452 title: _("Create new account"),
453 };
454 if (state.dialogLoading) {
455 props.body = (
456 <Bullseye>
457 <Spinner />
458 </Bullseye>
459 );
460 } else {
461 props.body = <AccountCreateBody state={state} errors={errors} change={change} shells={shells} />;
462 }
463
464 const footer = {
465 actions: [
466 {
467 caption: _("Create"),
468 style: "primary",
469 clicked: () => passwd_check(
470 false, // force weak password was NOT clicked
471 false, // force user with existing home directory was NOT clicked
472 false, // force user with non-unique UID was NOT clicked
473 state.real_name,
474 state.user_name,
475 state.password,
476 state.password_confirm,
477 state.locked,
478 state.home_dir,
479 state.change_passw_force,
480 state.uid,
481 accounts,
482 state.min_uid,
483 state.max_uid,
484 change
485 ),
486 disabled: state.confirm_weak || state.uid_exists || state.home_dir_exists || state.home_dir_is_file
487 }
488 ]
489 };
490 if (state.home_dir_exists) {
491 footer.actions.push(
492 {
493 caption: _("Create and change ownership of home directory"),
494 style: "warning",
495 clicked: () => passwd_check(
496 false, // force weak password was NOT clicked
497 true, // force user with existing home directory was WAS clicked
498 false, // force user with non-unique UID was NOT clicked
499 state.real_name,
500 state.user_name,
501 state.password,
502 state.password_confirm,
503 state.locked,
504 state.home_dir,
505 state.change_passw_force,
506 state.uid,
507 accounts,
508 state.min_uid,
509 state.max_uid,
510 change
511 ),
512 }
513 );
514 }
515 if (state.confirm_weak) {
516 footer.actions.push(
517 {
518 caption: _("Create account with weak password"),
519 style: "warning",
520 clicked: () => passwd_check(
521 true, // force weak password was WAS clicked
522 false, // force user with existing home directory was NOT clicked
523 false, // force user with non-unique UID was NOT clicked
524 state.real_name,
525 state.user_name,
526 state.password,
527 state.password_confirm,
528 state.locked,
529 state.home_dir,
530 state.change_passw_force,
531 state.uid,
532 accounts,
533 state.min_uid,
534 state.max_uid,
535 change
536 ),
537 }
538 );
539 }
540 if (state.uid_exists) {
541 footer.actions.push(
542 {
543 caption: _("Create account with non-unique UID"),
544 style: "warning",
545 clicked: () => passwd_check(
546 false, // force weak password was NOT clicked
547 false, // force user with existing home directory was NOT clicked
548 true, // force user with non-unique UID was WAS clicked
549 state.real_name,
550 state.user_name,
551 state.password,
552 state.password_confirm,
553 state.locked,
554 state.home_dir,
555 state.change_passw_force,
556 state.uid,
557 accounts,
558 state.min_uid,
559 state.max_uid,
560 change
561 ),
562 }
563 );
564 }
565
566 if (!dlg)
567 dlg = show_modal_dialog(props, footer);
568 else {
569 dlg.setProps(props);
570 dlg.setFooterProps(footer);
571 }
572 }
573
574 update();
575 get_defaults();
576 }