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

266 lines
11 KiB
TypeScript

import Apple from '@mui/icons-material/Apple'
import Delete from '@mui/icons-material/Delete'
import Download from '@mui/icons-material/Download'
import Key from '@mui/icons-material/Key'
import Password from '@mui/icons-material/Password'
import {
Alert, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Stack, Table, TableBody, TableCell,
TableHead, TableRow, TextField, Tooltip, Typography,
} from '@mui/material'
import { useEffect, useState, type FormEvent } from 'react'
import OtpDialog from './OtpDialog.tsx'
import PasskeyDialog from './PasskeyDialog.tsx'
import ProfileDialog from './ProfileDialog.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import Toolbar from './Toolbar.tsx'
import { ACCOUNT_SHAPE, CODE_PATTERN, USER_SHAPE, request, type Account, type User } from './api.ts'
/** The localStorage key of the page's layout. */
const LAYOUT_KEY = 'linux-manager-ui.account-layout'
/**
* The account of the signed-in user, from the server's /account, in two columns: the details with Change password,
* which opens the password dialog, and the passkeys in the first row, the enrolment for one-time passwords and the
* OpenVPN and the Apple VPN profile of a user with a certificate in the second. Each change but the removal of a
* passkey takes the current password and, for an enrolled user, a current code. A changed password ends the session,
* through onPasswordChanged. The panels are on a PanelBoard whose layout is kept in the browser.
*/
export default function AccountPanel(props: { onPasswordChanged: () => void }) {
const [account, setAccount] = useState<Account | null>(null)
const [error, setError] = useState<string | null>(null)
const [enrolling, setEnrolling] = useState(false)
const [currentPassword, setCurrentPassword] = useState('')
const [currentCode, setCurrentCode] = useState('')
const [password, setPassword] = useState('')
const [again, setAgain] = useState('')
const [saving, setSaving] = useState(false)
const [passwordError, setPasswordError] = useState<string | null>(null)
const [changingPassword, setChangingPassword] = useState(false)
const [addingPasskey, setAddingPasskey] = useState(false)
const [profile, setProfile] = useState<'openvpn' | 'apple' | null>(null)
const [passkeyError, setPasskeyError] = useState<string | null>(null)
const board = useBoard(LAYOUT_KEY)
useEffect(() => {
request<Account>('GET', '/account', ACCOUNT_SHAPE)
.then(setAccount)
.catch((caught: Error) => setError(caught.message))
}, [])
if (account === null) {
return error ? <Alert severity="error">{error}</Alert> : <CircularProgress />
}
const againProblem = again !== '' && again !== password ? 'The passwords differ.' : ''
const blocked = currentPassword === '' || (account.otp && !CODE_PATTERN.test(currentCode)) || password === '' || again !== password
async function changePassword(event: FormEvent) {
event.preventDefault()
if (account === null || blocked) {
return
}
setSaving(true)
setPasswordError(null)
try {
const proof = account.otp ? { current_password: currentPassword, current_code: currentCode } : { current_password: currentPassword }
await request('PUT', '/account/password', USER_SHAPE, { ...proof, password })
props.onPasswordChanged()
} catch (caught) {
setPasswordError((caught as Error).message)
setSaving(false)
}
}
/** Closes the password dialog, unless a change is being saved, and empties its fields. */
function closePasswordDialog() {
if (saving) {
return
}
setChangingPassword(false)
setCurrentPassword('')
setCurrentCode('')
setPassword('')
setAgain('')
setPasswordError(null)
}
async function removePasskey(id: string) {
if (account === null) {
return
}
setPasskeyError(null)
try {
setAccount({ ...(await request<User>('DELETE', `/account/passkeys/${encodeURIComponent(id)}`, USER_SHAPE)), admin: account.admin })
} catch (caught) {
setPasskeyError((caught as Error).message)
}
}
const rows: [string, string][] = [
['User name', account.name],
['Kind', account.manager_only ? 'Manager-only account' : 'VPN user'],
...(account.manager_only ? [] : [['First name', account.first_name ?? '-'], ['Last name', account.last_name ?? '-']] as [string, string][]),
['E-mail address', account.email ?? '-'],
['Router administrator', account.admin ? 'yes' : 'no'],
['One-time passwords', account.otp ? 'enrolled' : 'not enrolled'],
]
const panels: BoardPanel[] = [
{
id: 'account',
title: 'Account',
content: (
<>
<Box component="dl" sx={{ display: 'grid', gridTemplateColumns: 'max-content 1fr', columnGap: 2, rowGap: 0.5, m: 0 }}>
{rows.map(([label, value]) => (
<Box key={label} sx={{ display: 'contents' }}>
<Typography component="dt" variant="body2" color="text.secondary">{label}</Typography>
<Typography component="dd" variant="body2" sx={{ m: 0 }}>{value}</Typography>
</Box>
))}
</Box>
<Button variant="outlined" startIcon={<Password />} sx={{ mt: 2 }} onClick={() => setChangingPassword(true)}>Change password</Button>
</>
),
},
{
id: 'passkeys',
title: 'Passkeys',
content: (
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
{passkeyError && <Alert severity="error" sx={{ whiteSpace: 'pre-line', alignSelf: 'stretch' }}>{passkeyError}</Alert>}
{account.passkeys.length === 0
? <Typography variant="body2" color="text.secondary">No passkeys.</Typography>
: (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Label</TableCell>
<TableCell>Added</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{account.passkeys.map((passkey) => (
<TableRow key={passkey.id}>
<TableCell>{passkey.label}</TableCell>
<TableCell sx={{ whiteSpace: 'nowrap' }}>{new Date(passkey.created).toLocaleString()}</TableCell>
<TableCell align="right">
<Tooltip title="Remove">
<IconButton size="small" color="error" onClick={() => void removePasskey(passkey.id)}><Delete fontSize="small" /></IconButton>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
<Button variant="outlined" startIcon={<Key />} onClick={() => setAddingPasskey(true)}>Add a passkey</Button>
</Stack>
),
},
{
id: 'otp',
title: 'One-time passwords',
content: (
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
<Typography variant="body2" color="text.secondary">
{account.otp
? 'Signing in takes a code of the authenticator app. Enrolling again replaces the authenticator; an administrator removes the enrolment.'
: 'Enrol an authenticator app; signing in then takes a code of it.'}
</Typography>
<Button variant="outlined" onClick={() => setEnrolling(true)}>{account.otp ? 'Replace the authenticator' : 'Enrol'}</Button>
</Stack>
),
},
...(account.certificate ? [{
id: 'profiles',
title: 'VPN profiles',
content: (
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
<Button variant="outlined" startIcon={<Download />} onClick={() => setProfile('openvpn')}>Download the OpenVPN profile</Button>
<Button variant="outlined" startIcon={<Apple />} onClick={() => setProfile('apple')}>Download the Apple VPN profile (IKEv2)</Button>
</Stack>
),
}] : []),
]
return (
<Box component="section">
<Toolbar description="The account you are signed in with.">
<BoardButtons board={board} />
</Toolbar>
<Board board={board} panels={panels} />
<Dialog open={changingPassword} onClose={closePasswordDialog} fullWidth maxWidth="xs">
<form onSubmit={changePassword}>
<DialogTitle>Change password</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{passwordError && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{passwordError}</Alert>}
<Typography variant="body2" color="text.secondary">Changing the password signs you out.</Typography>
<TextField label="Current password" type="password" value={currentPassword} autoComplete="current-password" autoFocus onChange={(event) => setCurrentPassword(event.target.value)} />
{account.otp && (
<TextField
label="Code"
value={currentCode}
autoComplete="one-time-code"
helperText="A code not used to sign in."
slotProps={{ htmlInput: { inputMode: 'numeric', maxLength: 6 } }}
onChange={(event) => setCurrentCode(event.target.value.trim())}
/>
)}
<TextField label="New password" type="password" value={password} autoComplete="new-password" onChange={(event) => setPassword(event.target.value)} />
<TextField
label="New password again"
type="password"
value={again}
autoComplete="new-password"
error={againProblem !== ''}
helperText={againProblem}
onChange={(event) => setAgain(event.target.value)}
/>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={closePasswordDialog}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || blocked}>Change password</Button>
</DialogActions>
</form>
</Dialog>
{profile && (
<ProfileDialog
kind={profile}
name={account.name}
path={profile === 'apple' ? '/account/apple-profile' : '/account/profile'}
own
otp={account.otp}
onClose={() => setProfile(null)}
/>
)}
{addingPasskey && (
<PasskeyDialog
otp={account.otp}
onCancel={() => setAddingPasskey(false)}
onSaved={(user) => {
setAccount({ ...user, admin: account.admin })
setAddingPasskey(false)
}}
/>
)}
{enrolling && (
<OtpDialog
name={account.name}
path="/account/otp"
proof={{ otp: account.otp }}
onCancel={() => setEnrolling(false)}
onSave={async (secret, code, proof) => {
setAccount({ ...(await request<User>('PUT', '/account/otp', USER_SHAPE, { ...proof, secret, code })), admin: account.admin })
setEnrolling(false)
}}
/>
)}
</Box>
)
}