Files
edgeguard-native/management-ui/src/pages/IPAddresses/index.tsx
Debian d3a3b93c1b feat(rbac): Viewer-Rolle auf alle verbleibenden CRUD-Seiten durchsetzen — v1.1.92
DNS, NTP, ForwardProxy, RoutingRules, Networks (Interfaces + Routes),
IPAddresses, WireGuard (Servers + Clients + Peers), Backups/RemoteTargets, SSL:
Add-Buttons, quickToggle-Switches und Settings-Save-Buttons für Viewer deaktiviert.
ActionButtons-Komponente schützt Edit/Delete bereits zentral; hier wurden nur
die verbleibenden Mutationspunkte (Add, Switch, Submit) nachgezogen.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-24 13:56:24 +02:00

291 lines
10 KiB
TypeScript

import { useState } from 'react'
import { Button, Card, Form, Input, InputNumber, Modal, Select, Switch, Tag, Tooltip, Typography, message } from 'antd'
import { NodeIndexOutlined, PlusOutlined } from '@ant-design/icons'
import PageHeader from '../../components/PageHeader'
import ActionButtons from '../../components/ActionButtons'
import EmptyState from '../../components/EmptyState'
import type { ColumnsType } from 'antd/es/table'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import DataTable from '../../components/DataTable'
import apiClient, { isEnvelope } from '../../api/client'
import { useAuthStore } from '../../stores/auth'
interface IPAddress {
id: number
interface_id: number
address: string
prefix: number
is_vip: boolean
vip_priority?: number | null
description?: string | null
active: boolean
created_at: string
updated_at: string
}
interface SystemInterface {
ifname: string
flags?: string[]
link_type?: string
addr_info?: Array<{ family: 'inet' | 'inet6'; local: string; prefixlen: number }>
}
interface SystemAddress {
ifname: string
family: 'inet' | 'inet6'
address: string
prefix: number
}
interface IPFormValues {
interface_id: number
address: string
prefix: number
is_vip: boolean
vip_priority?: number
description?: string
active: boolean
}
interface NetworkInterface { id: number; name: string; role: string }
async function listIPs(): Promise<IPAddress[]> {
const r = await apiClient.get('/ip-addresses')
if (!isEnvelope(r.data)) return []
return (r.data.data as { ip_addresses?: IPAddress[] }).ip_addresses ?? []
}
async function listIfaces(): Promise<NetworkInterface[]> {
const r = await apiClient.get('/network-interfaces')
if (!isEnvelope(r.data)) return []
return (r.data.data as { interfaces?: NetworkInterface[] }).interfaces ?? []
}
// Flatten /system/interfaces into one row per (ifname, address) so
// the operator sees every kernel-side IP at a glance — including
// addresses that EdgeGuard hasn't taken under management yet.
async function listSystemAddresses(): Promise<SystemAddress[]> {
const r = await apiClient.get('/system/interfaces')
if (!isEnvelope(r.data)) return []
const ifs = (r.data.data as { interfaces?: SystemInterface[] }).interfaces ?? []
const out: SystemAddress[] = []
for (const i of ifs) {
for (const a of i.addr_info ?? []) {
out.push({
ifname: i.ifname,
family: a.family,
address: a.local,
prefix: a.prefixlen,
})
}
}
return out
}
export default function IPAddressesPage() {
const { t } = useTranslation()
const qc = useQueryClient()
const isViewer = useAuthStore((s) => s.user?.role) === 'viewer'
const { data: ips, isLoading } = useQuery({ queryKey: ['ip-addresses'], queryFn: listIPs })
const { data: ifs } = useQuery({ queryKey: ['network-interfaces'], queryFn: listIfaces })
const { data: sysAddrs } = useQuery({
queryKey: ['system', 'addresses'],
queryFn: listSystemAddresses,
refetchInterval: 60_000,
})
const ifaceLabel = (id: number) => {
const i = ifs?.find((x) => x.id === id)
return i ? `${i.name} (${i.role})` : `#${id}`
}
const [editing, setEditing] = useState<IPAddress | null>(null)
const [creating, setCreating] = useState(false)
const [form] = Form.useForm<IPFormValues>()
const create = useMutation({
mutationFn: async (v: IPFormValues) => { await apiClient.post('/ip-addresses', v) },
onSuccess: () => {
message.success(t('common.save'))
setCreating(false); form.resetFields()
void qc.invalidateQueries({ queryKey: ['ip-addresses'] })
},
})
const update = useMutation({
mutationFn: async ({ id, v }: { id: number; v: IPFormValues }) => { await apiClient.put(`/ip-addresses/${id}`, v) },
onSuccess: () => {
message.success(t('common.save'))
setEditing(null); form.resetFields()
void qc.invalidateQueries({ queryKey: ['ip-addresses'] })
},
})
const quickToggle = useMutation({
mutationFn: async ({ id, row, checked }: { id: number; row: IPAddress; checked: boolean }) => {
const { id: _id, created_at: _ca, updated_at: _ua, ...body } = row
await apiClient.put(`/ip-addresses/${id}`, { ...body, active: checked })
},
onSuccess: () => { void qc.invalidateQueries({ queryKey: ['ip-addresses'] }) },
onError: (e: Error) => message.error(e.message),
})
const del = useMutation({
mutationFn: async (id: number) => { await apiClient.delete(`/ip-addresses/${id}`) },
onSuccess: () => { void qc.invalidateQueries({ queryKey: ['ip-addresses'] }) },
})
const columns: ColumnsType<IPAddress> = [
{ title: t('ips.interface'), dataIndex: 'interface_id', key: 'iface', render: (id: number) => ifaceLabel(id) },
{
title: t('ips.address'), key: 'addr',
render: (_, row) => <code>{row.address}/{row.prefix}</code>,
},
{
title: t('ips.vip'), key: 'vip',
render: (_, row) => row.is_vip
? <Tag color="gold">VIP{row.vip_priority != null ? ` · prio ${row.vip_priority}` : ''}</Tag>
: '—',
},
{
title: t('ips.active'), dataIndex: 'active', key: 'active', width: 80,
render: (v: boolean, row: IPAddress) => (
<Switch
size="small"
checked={v}
disabled={isViewer}
loading={quickToggle.isPending && quickToggle.variables?.id === row.id}
onChange={(checked) => quickToggle.mutate({ id: row.id, row, checked })}
/>
),
},
{ title: t('ips.description'), dataIndex: 'description', key: 'desc', render: (v?: string) => v ?? '—' },
{
title: t('common.actions'), key: 'actions',
render: (_, row) => (
<ActionButtons
onEdit={() => {
setEditing(row)
form.setFieldsValue({
interface_id: row.interface_id,
address: row.address, prefix: row.prefix,
is_vip: row.is_vip, vip_priority: row.vip_priority ?? undefined,
description: row.description ?? undefined,
active: row.active,
})
}}
onDelete={() => del.mutate(row.id)}
deleteConfirm={t('ips.deleteConfirm', { addr: row.address })}
/>
),
},
]
const openCreate = () => {
setCreating(true); form.resetFields()
form.setFieldsValue({ prefix: 24, is_vip: false, active: true })
}
return (
<div>
<PageHeader
icon={<NodeIndexOutlined />}
title={t('ips.title')}
subtitle={t('ips.intro')}
/>
<Card title={t('ips.systemDiscovered')} size="small" className="mb-12">
{(sysAddrs ?? []).length === 0
? <Typography.Text type="secondary"></Typography.Text>
: (
<DataTable
size="small"
rowKey={(r) => `${r.ifname}-${r.address}`}
dataSource={sysAddrs ?? []}
columns={[
{ title: t('ips.interface'), dataIndex: 'ifname', key: 'ifname', render: (s: string) => <code>{s}</code> },
{ title: t('ips.address'), key: 'addr', render: (_, row: SystemAddress) => <code>{row.address}/{row.prefix}</code> },
{ title: t('ips.family'), dataIndex: 'family', key: 'family', render: (f: string) => <Tag>{f === 'inet' ? 'IPv4' : 'IPv6'}</Tag> },
]}
/>
)
}
</Card>
<Typography.Title level={5} style={{ marginTop: 8 }}>{t('ips.managedTitle')}</Typography.Title>
<DataTable
rowKey="id"
loading={isLoading}
dataSource={ips ?? []}
columns={columns}
extraActions={
<Tooltip title={isViewer ? t('auth.viewerBadge') : undefined}>
<Button type="primary" icon={<PlusOutlined />} disabled={isViewer} onClick={openCreate}>
{t('ips.addAddress')}
</Button>
</Tooltip>
}
emptyContent={
<EmptyState
icon={<NodeIndexOutlined />}
title={t('ips.emptyTitle')}
description={t('ips.emptyDesc')}
action={
<Tooltip title={isViewer ? t('auth.viewerBadge') : undefined}>
<Button type="primary" icon={<PlusOutlined />} disabled={isViewer} onClick={openCreate}>
{t('ips.addAddress')}
</Button>
</Tooltip>
}
/>
}
/>
<Modal
title={editing ? t('ips.editAddress') : t('ips.addAddress')}
open={editing !== null || creating}
onCancel={() => { setEditing(null); setCreating(false) }}
onOk={() => { void form.submit() }}
confirmLoading={create.isPending || update.isPending}
>
<Form
form={form}
layout="vertical"
onFinish={(v) => {
if (editing) update.mutate({ id: editing.id, v })
else create.mutate(v)
}}
>
<Form.Item label={t('ips.interface')} name="interface_id" rules={[{ required: true }]}>
<Select
options={(ifs ?? []).map((i) => ({ value: i.id, label: ifaceLabel(i.id) }))}
placeholder={t('ips.selectInterface')}
/>
</Form.Item>
<Form.Item label={t('ips.address')} name="address" rules={[{ required: true }]}>
<Input placeholder="192.0.2.10 oder fd00::1" />
</Form.Item>
<Form.Item label={t('ips.prefix')} name="prefix" rules={[{ required: true }]}>
<InputNumber min={0} max={128} style={{ width: '100%' }} />
</Form.Item>
<Form.Item label={t('ips.vipFlag')} name="is_vip" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item noStyle shouldUpdate={(p, c) => p.is_vip !== c.is_vip}>
{({ getFieldValue }) => getFieldValue('is_vip') ? (
<Form.Item label={t('ips.vipPriority')} name="vip_priority">
<InputNumber min={0} max={255} style={{ width: '100%' }} placeholder="100" />
</Form.Item>
) : null}
</Form.Item>
<Form.Item label={t('ips.description')} name="description">
<Input />
</Form.Item>
<Form.Item label={t('ips.active')} name="active" valuePropName="checked">
<Switch />
</Form.Item>
</Form>
</Modal>
</div>
)
}