Files
linux-cloud-router/web/src/GroupsPanel.tsx
T

202 lines
7.9 KiB
TypeScript

import Add from '@mui/icons-material/Add'
import Delete from '@mui/icons-material/Delete'
import Edit from '@mui/icons-material/Edit'
import Refresh from '@mui/icons-material/Refresh'
import {
Alert, Box, Button, Chip, IconButton, Stack, Table, TableBody, TableCell, TableHead, TableRow, Tooltip,
} from '@mui/material'
import { useCallback, useEffect, useState } from 'react'
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import GroupDialog from './GroupDialog.tsx'
import { Section } from './ServerPanel.tsx'
import SearchField from './SearchField.tsx'
import { matches } from './search.ts'
import Toolbar from './Toolbar.tsx'
import { ApiError, GROUPS_SHAPE, GROUP_SHAPE, REMOVED_SHAPE, SERVICE_ACCOUNTS_SHAPE, USERS_SHAPE, request, type Group, type User } from './api.ts'
/**
* The groups of the server's directory: list with their descriptions and members, add, edit the name, the
* description and the members, and remove. A group always keeps at least one member; the members offered are the users
* and the service accounts but the internal ones.
*/
export default function GroupsPanel() {
const [groups, setGroups] = useState<Group[] | null>(null)
const [users, setUsers] = useState<string[]>([])
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [busy, setBusy] = useState(true)
const [adding, setAdding] = useState(false)
const [editing, setEditing] = useState<Group | null>(null)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const [search, setSearch] = useState('')
/** Reads the groups with the users and service accounts; the state changes only once the server answers. */
const read = useCallback(async () => {
await Promise.all([
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
request<{ users: User[] }>('GET', '/users', USERS_SHAPE),
request<{ service_accounts: User[] }>('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE),
])
.then(([found, people, services]) => {
setGroups(found.groups)
setUsers([...people.users, ...services.service_accounts.filter((account) => !account.internal)].map((user) => user.name).sort())
setError(null)
setUnavailable(false)
}, (caught) => {
const failure = caught as ApiError
setGroups(null)
setUnavailable(failure.status === 404)
setError(failure.message)
})
.finally(() => setBusy(false))
}, [])
/** Reads the groups again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void read()
}, [read])
/** Runs a change of a group, then reads the list again; a failure is shown above the list. */
async function change(work: () => Promise<unknown>) {
setBusy(true)
let failure: string | null = null
try {
await work()
} catch (caught) {
failure = (caught as Error).message
}
await refresh()
if (failure !== null) {
setError(failure)
}
}
function remove(group: Group) {
setConfirm({
title: 'Remove group',
message: `Remove ${group.name}? Its members are kept.`,
confirmLabel: 'Remove',
destructive: true,
onCancel: () => setConfirm(null),
onConfirm: () => {
setConfirm(null)
void change(() => request('DELETE', `/groups/${group.name}`, REMOVED_SHAPE))
},
})
}
const shown = (groups ?? []).filter((group) => matches(search, [group.name, group.description, ...group.members]))
return (
<Box component="section">
<Toolbar description="User groups.">
<SearchField value={search} onChange={setSearch} />
<Button variant="contained" startIcon={<Add />} disabled={busy || groups === null || users.length === 0} onClick={() => setAdding(true)}>
Add
</Button>
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>
Refresh
</Button>
</Toolbar>
{error && <Alert severity={unavailable ? 'info' : 'error'} sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{groups && (
<Section title="Groups">
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Group</TableCell>
<TableCell>Description</TableCell>
<TableCell>Members</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{shown.length === 0 && (
<TableRow>
<TableCell colSpan={4} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{shown.map((group) => (
<TableRow key={group.name} hover>
<TableCell>{group.name}</TableCell>
<TableCell>{group.description || '-'}</TableCell>
<TableCell>
<Stack direction="row" sx={{ gap: 0.5, flexWrap: 'wrap' }}>
{group.members.map((member) => <Chip key={member} size="small" label={member} />)}
</Stack>
</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setEditing(group)}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => remove(group)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Section>
)}
{adding && (
<GroupDialog
users={users}
onCancel={() => setAdding(false)}
onSave={async (name, description, members) => {
await request('POST', '/groups', GROUP_SHAPE, { name, description, members })
setAdding(false)
await refresh()
}}
/>
)}
{editing && (
<GroupDialog
group={editing}
users={users}
onCancel={() => setEditing(null)}
onSave={async (name, description, members) => {
// Only what changed is sent: the changed properties, then each member added and each member taken out,
// the additions first so that the group never loses its last member; nothing when nothing changed.
const properties: { name?: string; description?: string } = {}
if (name !== editing.name) {
properties.name = name
}
if (description !== editing.description) {
properties.description = description
}
const added = members.filter((member) => !editing.members.includes(member))
const removed = editing.members.filter((member) => !members.includes(member))
if (Object.keys(properties).length > 0) {
await request('PUT', `/groups/${editing.name}`, GROUP_SHAPE, properties)
}
for (const user of added) {
await request('POST', `/groups/${name}/members`, GROUP_SHAPE, { user })
}
for (const user of removed) {
await request('DELETE', `/groups/${name}/members/${user}`, GROUP_SHAPE)
}
setEditing(null)
if (Object.keys(properties).length > 0 || added.length > 0 || removed.length > 0) {
await refresh()
}
}}
/>
)}
{confirm && <ConfirmDialog {...confirm} />}
</Box>
)
}