-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
accounts-list.js
480 lines (442 loc) · 19.6 KB
/
accounts-list.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/*
* This file is part of Cockpit.
*
* Copyright (C) 2020 Red Hat, Inc.
*
* Cockpit is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Cockpit 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/
import cockpit from 'cockpit';
import React, { useState, useEffect, useRef } from 'react';
import { superuser } from "superuser";
import { admins } from './users.js';
import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
import { Badge } from "@patternfly/react-core/dist/esm/components/Badge/index.js";
import { Card, CardExpandableContent, CardHeader, CardTitle } from '@patternfly/react-core/dist/esm/components/Card/index.js';
import { Divider } from '@patternfly/react-core/dist/esm/components/Divider/index.js';
import { DropdownItem } from '@patternfly/react-core/dist/esm/components/Dropdown/index.js';
import { Flex, FlexItem } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
import { HelperText, HelperTextItem } from "@patternfly/react-core/dist/esm/components/HelperText/index.js";
import { Label } from "@patternfly/react-core/dist/esm/components/Label/index.js";
import { Page, PageSection } from "@patternfly/react-core/dist/esm/components/Page/index.js";
import { SearchInput } from "@patternfly/react-core/dist/esm/components/SearchInput/index.js";
import { Stack } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
import { Text, TextContent, TextVariants } from "@patternfly/react-core/dist/esm/components/Text/index.js";
import { Toolbar, ToolbarContent, ToolbarItem } from "@patternfly/react-core/dist/esm/components/Toolbar/index.js";
import * as timeformat from "timeformat.js";
import { EmptyStatePanel } from 'cockpit-components-empty-state.jsx';
import { ListingTable } from 'cockpit-components-table.jsx';
import { SearchIcon } from '@patternfly/react-icons';
import { SortByDirection } from "@patternfly/react-table";
import { account_create_dialog } from "./account-create-dialog.js";
import { delete_account_dialog } from "./delete-account-dialog.js";
import { group_create_dialog } from "./group-create-dialog.js";
import { lockAccountDialog } from "./lock-account-dialog.js";
import { logoutAccountDialog } from "./logout-account-dialog.js";
import { GroupActions } from "./group-actions.jsx";
import { usePageLocation } from "hooks";
import { KebabDropdown } from "cockpit-components-dropdown";
const _ = cockpit.gettext;
const UserActions = ({ account }) => {
const actions = [
<DropdownItem key="edit-user"
onClick={ev => { ev.preventDefault(); cockpit.location.go(account.name) }}>
{_("Edit user")}
</DropdownItem>,
];
superuser.allowed && actions.push(
<Divider key="separator-0" />,
<DropdownItem key="log-user-out"
isDisabled={account.uid === 0 || !account.loggedIn}
onClick={() => logoutAccountDialog(account) }>
{_("Log user out")}
</DropdownItem>,
<Divider key="separator-1" />,
<DropdownItem key="lock-account"
isDisabled={account.isLocked}
onClick={() => lockAccountDialog(account) }>
{_("Lock account")}
</DropdownItem>,
<DropdownItem key="delete-account"
isDisabled={account.uid === 0}
className={account.uid === 0 ? "" : "delete-resource-red"}
onClick={() => delete_account_dialog(account) }>
{_("Delete account")}
</DropdownItem>,
);
return <KebabDropdown toggleButtonId="accounts-actions" dropdownItems={actions} />;
};
const getGroupRow = (group, accounts) => {
let groupColorClass;
if (group.isAdmin)
groupColorClass = "group-gold";
else if (group.members > 0)
groupColorClass = "group-cyan";
else
groupColorClass = "group-grey";
const columns = [
{
sortKey: group.name,
title: (
<Flex alignItems={{ default: 'alignItemsCenter' }}>
<div className={"dot " + groupColorClass} />
<FlexItem>{group.name}</FlexItem>
</Flex>
),
props: { width: 20, },
},
{
title: group.gid,
props: { width: 10, },
},
{
title: group.members,
props: { width: 20, },
},
{
title: (
<TextContent>
<Text component={TextVariants.p}>
{(group.userlistPrimary.concat(group.userlist))
.map(account => {
if (accounts.map(account => account.name).includes(account))
return <Text key={account} component={TextVariants.a} href={"#" + account}>{account}</Text>;
else
return account;
})
.reduce((acc, curr) => [...acc, ", ", curr], [])
.slice(1)}
</Text>
</TextContent>
),
props: { width: 50, },
},
];
if (superuser.allowed) {
columns.push(
{
title: <GroupActions group={group} />,
props: { className: "pf-v5-c-table__action" }
}
);
}
return { columns, props: { key: group.name } };
};
const getAccountRow = (account, current, groups) => {
const userGroups = groups.filter(group => group.gid === account.gid || group.userlist.find(accountName => accountName === account.name));
const userGroupLabels = userGroups.map(group => {
const color = group.isAdmin ? "gold" : "cyan";
return (
<Label key={group.name} variant="filled" color={color}>
{!group.isAdmin ? group.name : ("admin" + " (" + group.name + ")") }
</Label>
);
});
let loginText = "";
let loginSortKey = null;
if (account.loggedIn) {
loginText = _("Logged in");
loginSortKey = "logged in";
} else if (!account.lastLogin) {
loginText = _("Never logged in");
loginSortKey = "never";
} else {
loginSortKey = new Date(account.lastLogin);
loginText = timeformat.dateTime(loginSortKey);
}
const columns = [
{
title: (
<span>
<a href={"#/" + account.name}>{account.name}</a>
{current && <Badge id="current-account-badge">{_("Your account")}</Badge>}
</span>
),
sortKey: account.name,
props: { width: 25, },
},
{
title: account.gecos.split(',')[0],
props: { width: 20, },
},
{
title: account.uid,
props: { width: 10, },
},
{
title: loginText,
sortKey: loginSortKey,
props: { width: 25, },
},
{
title: (
<Flex spaceItems={{ default: 'spaceItemsSm' }}>
{userGroupLabels}
</Flex>
),
props: { width: 20 },
},
{
title: <UserActions account={account} />,
props: { className: "pf-v5-c-table__action" }
},
];
return { columns, props: { key: account.name } };
};
const mapGroupsToAccount = (accounts, groups) => {
return accounts.map(account => {
const accountGroups = [];
groups.forEach(group => {
if (group.userlist.find(accountName => accountName === account.name))
accountGroups.push(group.name);
});
account.groups = accountGroups;
return account;
});
};
const GroupsList = ({ groups, accounts, isExpanded, setIsExpanded, min_gid, max_gid }) => {
const { options } = usePageLocation();
const [currentTextFilter, setCurrentTextFilter] = useState(options.group || '');
const columns = [
{ title: _("Group name"), sortable: true },
{ title: _("ID"), sortable: true },
{ title: _("# of users"), sortable: true },
{ title: _("Accounts") },
];
const filtered_groups = groups.filter(group => {
if (currentTextFilter !== "" &&
(group.name.toLowerCase().indexOf(currentTextFilter.toLowerCase()) === -1) &&
(group.gid.toString().indexOf(currentTextFilter.toLowerCase()) === -1))
return false;
return true;
});
const ref = useRef();
useEffect(() => {
if (ref.current != currentTextFilter) {
ref.current = currentTextFilter;
const newOptions = { ...options };
if (currentTextFilter) {
newOptions.group = currentTextFilter;
} else {
delete newOptions.group;
}
cockpit.location.go([], newOptions);
} else {
setCurrentTextFilter(options.group || "");
}
}, [currentTextFilter, options]);
const sortRows = (rows, direction, idx) => {
// GID and members columns are numeric
const isNumeric = idx == 1 || idx == 2;
const sortedRows = rows.sort((a, b) => {
const aitem = a.columns[idx].sortKey || a.columns[idx].title;
const bitem = b.columns[idx].sortKey || b.columns[idx].title;
const aname = a.columns[0].sortKey;
const bname = b.columns[0].sortKey;
// administrator groups are always first
if (admins.includes(aname))
return direction === SortByDirection.asc ? -1 : 1;
if (admins.includes(bname))
return direction === SortByDirection.asc ? 1 : -1;
if (isNumeric)
return bitem - aitem;
else
return aitem.localeCompare(bitem);
});
return direction === SortByDirection.asc ? sortedRows : sortedRows.reverse();
};
const tableToolbar = (
<Toolbar>
<ToolbarContent className="groups-toolbar-header">
{isExpanded && <ToolbarItem>
<SearchInput id="groups-filter"
placeholder={_("Search for name or ID")}
value={currentTextFilter}
onChange={(_, val) => setCurrentTextFilter(val)}
onClear={() => setCurrentTextFilter('')} />
</ToolbarItem>}
{ superuser.allowed &&
<>
{isExpanded && <ToolbarItem variant="separator" />}
<ToolbarItem align={{ md: 'alignRight' }}>
<Button variant="secondary" id="groups-create" onClick={() => group_create_dialog(groups, setIsExpanded, min_gid, max_gid)}>
{_("Create new group")}
</Button>
</ToolbarItem>
</>
}
</ToolbarContent>
</Toolbar>
);
return (
<Card className="ct-card" isExpanded={isExpanded}>
<CardHeader actions={{ actions: tableToolbar, hasNoOffset: true }}
className="ct-card-expandable-header"
onExpand={() => setIsExpanded(!isExpanded)}
toggleButtonProps={{
id: 'groups-view-toggle',
'aria-label': _("Groups"),
'aria-expanded': isExpanded
}}>
<CardTitle className="pf-v5-l-flex pf-m-align-items-center pf-m-space-items-md">
<Text component={TextVariants.h2}>{_("Groups")}</Text>
{(!isExpanded && !groups.length) && <HelperText> <HelperTextItem variant="indeterminate">{_("Loading...")}</HelperTextItem></HelperText>}
{(!isExpanded && filtered_groups.length > 0) && <>
{filtered_groups.slice(0, 3)
.map(group => {
const color = group.isAdmin ? "gold" : "cyan";
return (
<Label key={group.name} variant="filled" color={color}>
{group.name + ": " + (group.userlistPrimary.length + group.userlist.length)}
</Label>
);
})}
{filtered_groups.length > 3 && <Button key="more" className="group-more-btn" isInline variant='link' onClick={() => setIsExpanded(!isExpanded)}>
{cockpit.format(_("$0 more..."), filtered_groups.length - 3)}
</Button>}
</>}
</CardTitle>
</CardHeader>
<CardExpandableContent>
<ListingTable columns={columns}
id="groups-list"
rows={ filtered_groups.map(a => getGroupRow(a, accounts)) }
loading={ groups.length && accounts.length ? '' : _("Loading...") }
sortMethod={sortRows}
emptyComponent={<EmptyStatePanel title={_("No matching results")} icon={SearchIcon} />}
variant="compact" sortBy={{ index: 2, direction: SortByDirection.asc }} />
</CardExpandableContent>
</Card>
);
};
const AccountsList = ({ accounts, current_user, groups, min_uid, max_uid, shells }) => {
const { options } = usePageLocation();
const [currentTextFilter, setCurrentTextFilter] = useState(options.user || '');
const filtered_accounts = accounts.filter(account => {
if (currentTextFilter !== "" &&
(account.name.toLowerCase().indexOf(currentTextFilter.toLowerCase()) === -1) &&
(account.gecos.toLowerCase().indexOf(currentTextFilter.toLowerCase()) === -1) &&
(account.uid.toString().indexOf(currentTextFilter.toLowerCase()) === -1) &&
(!account.groups.find(group => group.toLowerCase().indexOf(currentTextFilter.toLowerCase()) !== -1)))
return false;
return true;
});
const ref = useRef();
useEffect(() => {
if (ref.current != currentTextFilter) {
ref.current = currentTextFilter;
const newOptions = { ...options };
if (currentTextFilter) {
newOptions.user = currentTextFilter;
} else {
delete newOptions.user;
}
cockpit.location.go([], newOptions);
} else {
setCurrentTextFilter(options.user || "");
}
}, [currentTextFilter, options]);
const columns = [
{ title: _("Username"), sortable: true },
{ title: _("Full name"), sortable: true },
{ title: _("ID"), sortable: true },
{ title: _("Last active"), sortable: true },
{ title: _("Group") },
];
const sortRows = (rows, direction, idx) => {
const sortedRows = rows.sort((a, b) => {
const aitem = a.columns[idx];
const bitem = b.columns[idx];
const aname = a.columns[0];
const bname = b.columns[0];
// current user is always first
if (aname.sortKey === current_user)
return direction === SortByDirection.asc ? -1 : 1;
if (bname.sortKey === current_user)
return direction === SortByDirection.asc ? 1 : -1;
// sorting last login
if (idx === 3) {
if (aitem.sortKey === "logged in")
return -1;
if (bitem.sortKey === "logged in")
return 1;
if (aitem.sortKey === "never")
return 1;
if (bitem.sortKey === "never")
return -1;
return bitem.sortKey - aitem.sortKey;
}
if (idx == 2)
return bitem.title - aitem.title;
return ((typeof aitem == 'string' ? aitem : (aitem.sortKey || aitem.title)).localeCompare(typeof bitem == 'string' ? bitem : (bitem.sortKey || bitem.title)));
});
return direction === SortByDirection.asc ? sortedRows : sortedRows.reverse();
};
const tableToolbar = (
<Toolbar>
<ToolbarContent className="accounts-toolbar-header">
<ToolbarItem>
<SearchInput id="accounts-filter"
placeholder={_("Search for name, group or ID")}
value={currentTextFilter}
onChange={(_, val) => setCurrentTextFilter(val)}
onClear={() => setCurrentTextFilter('')} />
</ToolbarItem>
{ superuser.allowed &&
<>
<ToolbarItem variant="separator" />
<ToolbarItem align={{ md: 'alignRight' }}>
<Button id="accounts-create" onClick={() => account_create_dialog(accounts, min_uid, max_uid, shells)}>
{_("Create new account")}
</Button>
</ToolbarItem>
</>
}
</ToolbarContent>
</Toolbar>
);
return (
<Card className="ct-card">
<CardHeader actions={{ actions: tableToolbar }}>
<CardTitle component="h2">{_("Accounts")}</CardTitle>
</CardHeader>
<ListingTable columns={columns}
id="accounts-list"
isEmptyStateInTable={currentTextFilter !== "" && filtered_accounts.length !== accounts.length}
rows={ filtered_accounts.map(a => getAccountRow(a, current_user === a.name, groups)) }
loading={ accounts.length ? '' : _("Loading...") }
sortMethod={sortRows}
emptyComponent={<EmptyStatePanel title={_("No matching results")} icon={SearchIcon} />}
variant="compact" sortBy={{ index: 0, direction: SortByDirection.asc }} />
</Card>
);
};
export const AccountsMain = ({ accountsInfo, current_user, groups, isGroupsExpanded, setIsGroupsExpanded, min_gid, max_gid, min_uid, max_uid, shells }) => {
const accounts = mapGroupsToAccount(accountsInfo, groups).filter(account => {
if ((account.uid < 1000 && account.uid !== 0) ||
account.shell.match(/^(\/usr)?\/sbin\/nologin/) ||
account.shell === '/bin/false')
return false;
return true;
});
return (
<Page id="accounts">
<PageSection>
<Stack hasGutter>
<GroupsList accounts={accounts} groups={groups} isExpanded={isGroupsExpanded} setIsExpanded={setIsGroupsExpanded} min_gid={min_gid} max_gid={max_gid} />
<AccountsList accounts={accounts} current_user={current_user} groups={groups} shells={shells} min_uid={min_uid} max_uid={max_uid} />
</Stack>
</PageSection>
</Page>
);
};