Files
jobtrackingapp/job-tracker-ui/src/views/AdminUsersPage.tsx
T

326 lines
15 KiB
TypeScript

import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Alert,
Box,
Button,
Checkbox,
Chip,
FormControlLabel,
Paper,
Stack,
TextField,
Tooltip,
Typography,
} from "@mui/material";
import useMediaQuery from "@mui/material/useMediaQuery";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useDialogActions } from "../dialogs";
import { useI18n } from "../i18n/I18nProvider";
import { useViewResource } from "../hooks/useViewResource";
import ViewStateNotice from "../components/ViewStateNotice";
import { PageHeader, PageSection } from "../layout/PageLayout";
import { checkSessionCookie, getSessionContext, isSessionInvalidated } from "../sessionBoundary";
type UserDto = {
id: string;
email?: string | null;
userName?: string | null;
emailConfirmed: boolean;
roles: string[];
isCurrentUser: boolean;
canRemoveAdmin: boolean;
};
export default function AdminUsersPage() {
const isMobile = useMediaQuery("(max-width:767.95px)");
const { toast } = useToast();
const { confirmAction } = useDialogActions();
const { t } = useI18n();
const [busy, setBusy] = useState(false);
const owner = useRef({ mounted: true, generation: 0, busy: false });
const body = useRef<HTMLDivElement>(null);
const currentTranslation = useRef(t);
useEffect(() => { currentTranslation.current=t; }, [t]);
useEffect(() => { const lifetime=owner.current; lifetime.mounted=true; lifetime.generation+=1; return () => { lifetime.mounted=false; lifetime.generation+=1; }; }, []);
const userResource=useViewResource(async () => (await api.get<UserDto[]>("/users")).data ?? [], { initialData: [], errorMessage: t("adminUsersLoadFailed") });
const users=userResource.data;
const loading=userResource.loading || userResource.refreshing;
const load=userResource.reload;
const [newEmail, setNewEmail] = useState("");
const [newPassword, setNewPassword] = useState("");
const [newIsAdmin, setNewIsAdmin] = useState(false);
const canCreate = newEmail.trim().length > 3 && newPassword.length >= 6;
const beginAction=useCallback(() => {
checkSessionCookie(); const lifetime=owner.current;
if (!lifetime.mounted || lifetime.busy || isSessionInvalidated()) return null;
lifetime.busy=true; setBusy(true);
if (body.current?.contains(document.activeElement)) body.current.focus();
const context=getSessionContext(); const generation=lifetime.generation;
return () => { checkSessionCookie(); return lifetime.mounted && lifetime.generation===generation && !isSessionInvalidated() && getSessionContext()===context; };
}, []);
const finishAction=useCallback((active: () => boolean) => { owner.current.busy=false; if (active()) setBusy(false); }, []);
const createUser=async () => {
if (!canCreate) return;
const active=beginAction(); if (!active) return;
const submitted={ email: newEmail, password: newPassword, isAdmin: newIsAdmin };
try {
await api.post("/users", { email: submitted.email, password: submitted.password, roles: submitted.isAdmin ? ["Admin"] : [] });
if (!active()) return;
setNewEmail(current => current===submitted.email ? "" : current);
setNewPassword(current => current===submitted.password ? "" : current);
setNewIsAdmin(current => current===submitted.isAdmin ? false : current);
toast(currentTranslation.current("adminUsersCreated"), "success");
await load();
} catch (error) { if (active()) toast(getApiErrorMessage(error, currentTranslation.current("adminUsersCreateFailed")), "error"); }
finally { finishAction(active); }
};
const rows = useMemo(() => users.map((u) => ({
id: u.id,
email: u.email || "",
userName: u.userName || "",
roles: u.roles || [],
emailConfirmed: u.emailConfirmed,
raw: u,
})), [users]);
const setAdminRole = useCallback(async (u: UserDto, grantAdmin: boolean) => {
const active=beginAction(); if (!active) return;
try {
if (!grantAdmin) {
const name = u.userName || u.email || u.id;
const confirmed = await confirmAction(
u.isCurrentUser
? t("adminUsersSelfDemoteWarning")
: t("adminUsersDemoteWarning", { name }),
{
title: u.isCurrentUser ? t("adminUsersSelfDemoteTitle") : t("adminUsersDemoteTitle"),
confirmLabel: t("adminUsersRemoveAdmin"),
destructive: true,
},
);
if (!active() || !confirmed) return;
}
const roles = grantAdmin
? Array.from(new Set([...(u.roles || []), "Admin"]))
: (u.roles || []).filter((role) => role.toLowerCase() !== "admin");
await api.put(`/users/${u.id}/roles`, { roles });
if (!active()) return;
toast(currentTranslation.current("adminUsersRolesUpdated"), "success");
await load();
} catch (e) {
if (active()) toast(getApiErrorMessage(e, currentTranslation.current("adminUsersRolesUpdateFailed")), "error");
}
finally { finishAction(active); }
}, [beginAction, confirmAction, finishAction, load, t, toast]);
const sendReset = useCallback(async (u: UserDto) => {
const active=beginAction(); if (!active) return;
try {
await api.post(`/users/${u.id}/send-password-reset`);
if (active()) toast(currentTranslation.current("adminUsersResetSent"), "success");
} catch (e: any) {
if (active()) toast(getApiErrorMessage(e, currentTranslation.current("adminUsersResetFailed")), "error");
}
finally { finishAction(active); }
}, [beginAction, finishAction, toast]);
const remove = useCallback(async (u: UserDto) => {
const active=beginAction(); if (!active) return;
try {
const name = u.userName || u.email || u.id;
const message = u.isCurrentUser
? t("adminUsersDeleteSelfWarning")
: t("adminUsersDeleteConfirmNamed", { name });
if (!(await confirmAction(message, { title: t("adminUsersDeleteConfirmTitle"), confirmLabel: t("adminUsersDelete"), destructive: true })) || !active()) return;
const response=await api.delete(`/users/${u.id}`, { headers: { "X-Confirm-Account-Deletion": u.email || u.userName || "" } });
if (!active()) return;
toast(currentTranslation.current(response.status===202 ? "adminUsersDeletionQueued" : "adminUsersDeleted"), "info");
await load();
} catch (e) {
if (active()) toast(getApiErrorMessage(e, currentTranslation.current("adminUsersDeleteFailed")), "error");
}
finally { finishAction(active); }
}, [beginAction, confirmAction, finishAction, load, t, toast]);
const columns = useMemo<GridColDef[]>(() => [
{
field: "email",
headerName: t("profileEmail"),
flex: 1.2,
minWidth: 220,
renderCell: (params) => (
<Box sx={{ display: "flex", alignItems: "center", gap: 0.75, minWidth: 0 }}>
<Typography variant="body2" noWrap>{params.value}</Typography>
{(params.row.raw as UserDto).isCurrentUser ? <Chip size="small" label={t("adminUsersYou")} color="primary" variant="outlined" /> : null}
</Box>
),
},
{ field: "userName", headerName: t("profileUsername"), flex: 1, minWidth: 180 },
{
field: "roles",
headerName: t("adminUsersRolesLabel"),
flex: 1,
minWidth: 180,
sortable: false,
renderCell: (params) => {
const roles = params.row.roles as string[];
return (
<Box sx={{ display: "flex", gap: 0.75, flexWrap: "wrap", py: 0.5 }}>
{roles.length ? roles.map((role) => <Chip key={role} size="small" label={role} variant="outlined" />) : <Typography variant="body2" sx={{ color: "text.secondary" }}>—</Typography>}
</Box>
);
},
},
{
field: "emailConfirmed",
headerName: t("adminUsersConfirmed"),
width: 130,
renderCell: (params) => (
<Chip size="small" label={params.value ? t("yes") : t("noWord")} color={params.value ? "success" : "default"} variant={params.value ? "filled" : "outlined"} />
),
},
{
field: "actions",
headerName: t("adminUsersActions"),
minWidth: 300,
flex: 1.4,
sortable: false,
filterable: false,
renderCell: (params) => {
const user = params.row.raw as UserDto;
const isAdmin = (user.roles || []).includes("Admin");
return (
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", py: 0.5 }}>
<Tooltip title={isAdmin && !user.canRemoveAdmin ? t("adminUsersLastAdminHelp") : ""}>
<span>
<Button size="small" variant={isAdmin ? "contained" : "outlined"} disabled={busy || isAdmin && !user.canRemoveAdmin} onClick={() => void setAdminRole(user, !isAdmin)}>
{isAdmin ? t("adminUsersRemoveAdmin") : t("adminUsersMakeAdmin")}
</Button>
</span>
</Tooltip>
<Button size="small" variant="outlined" disabled={busy} onClick={() => void sendReset(user)}>
{t("adminUsersSendReset")}
</Button>
<Tooltip title={isAdmin && !user.canRemoveAdmin ? t("adminUsersLastAdminHelp") : ""}>
<span><Button size="small" color="error" variant="outlined" disabled={busy || isAdmin && !user.canRemoveAdmin} onClick={() => void remove(user)}>{t("adminUsersDelete")}</Button></span>
</Tooltip>
</Box>
);
},
},
], [busy, remove, sendReset, setAdminRole, t]);
return (
<Box ref={body} role="group" aria-label={t("adminUsersTitle")} tabIndex={-1} aria-busy={busy} sx={{ display: "grid", gap: "var(--app-section-gap)", minWidth: 0, "& button": { whiteSpace: "normal", overflowWrap: "anywhere", "@media (pointer: coarse)": { minHeight: 44 } } }}>
<PageHeader level="h2" title={t("adminUsersTitle")} description={t("adminUsersSubtitle")} />
<Alert severity="info" sx={{ mb: 2 }}>{t("adminUsersSafetyNotice")}</Alert>
<PageSection level="h3" surface title={t("adminUsersCreateUser")}>
<Box component="form" onSubmit={event => { event.preventDefault(); void createUser(); }}>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" }, gap: 1.5 }}>
<TextField label={t("profileEmail")} value={newEmail} onChange={(e) => setNewEmail(e.target.value)} fullWidth />
<TextField label={t("profileNewPassword")} type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} fullWidth />
</Box>
<Box sx={{ display: "flex", alignItems: { xs: "stretch", sm: "center" }, justifyContent: "space-between", gap: 2, mt: 1.5, flexWrap: "wrap" }}>
<FormControlLabel control={<Checkbox checked={newIsAdmin} onChange={(e) => setNewIsAdmin(e.target.checked)} />} label={t("adminUsersAdmin")} />
<Button
variant="contained"
disabled={!canCreate || loading || busy}
type="submit"
sx={{ width: { xs: "100%", sm: "auto" } }}
>
{t("create")}
</Button>
</Box>
</Box>
</PageSection>
<ViewStateNotice loading={userResource.loading} error={userResource.error} title={t("adminUsersLoadFailed")} onRetry={async () => { body.current?.focus(); await load(); }} />
{!userResource.error ? isMobile ? (
<Stack spacing={1.5}>
{!loading && rows.length === 0 ? (
<Typography sx={{ color: "text.secondary", py: 2, textAlign: "center" }}>{t("adminUsersNoUsers")}</Typography>
) : null}
{rows.map((row) => {
const user = row.raw as UserDto;
const isAdmin = user.roles.includes("Admin");
return (
<Paper key={row.id} variant="outlined" sx={{ p: "var(--app-card-padding)", borderRadius: 1, minWidth: 0 }}>
<Stack spacing={1.25}>
<Box>
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
<Typography component="span" sx={{ fontWeight: 900, overflowWrap: "anywhere" }}>{row.userName || row.email || row.id}</Typography>
{user.isCurrentUser ? <Chip size="small" label={t("adminUsersYou")} color="primary" variant="outlined" /> : null}
</Box>
<Typography variant="body2" sx={{ color: "text.secondary", overflowWrap: "anywhere" }}>
{row.email || "—"}
</Typography>
</Box>
<Box sx={{ display: "flex", gap: 0.75, flexWrap: "wrap" }}>
{(row.roles as string[]).length ? (row.roles as string[]).map((role) => (
<Chip key={role} size="small" label={role} variant="outlined" />
)) : <Chip size="small" label="—" variant="outlined" />}
<Chip size="small" label={row.emailConfirmed ? t("yes") : t("noWord")} color={row.emailConfirmed ? "success" : "default"} variant={row.emailConfirmed ? "filled" : "outlined"} />
</Box>
<Stack spacing={1}>
<Tooltip title={isAdmin && !user.canRemoveAdmin ? t("adminUsersLastAdminHelp") : ""}>
<span><Button variant={isAdmin ? "contained" : "outlined"} disabled={busy || isAdmin && !user.canRemoveAdmin} onClick={() => void setAdminRole(user, !isAdmin)} fullWidth>{isAdmin ? t("adminUsersRemoveAdmin") : t("adminUsersMakeAdmin")}</Button></span>
</Tooltip>
<Button variant="outlined" disabled={busy} onClick={() => void sendReset(user)} fullWidth>
{t("adminUsersSendReset")}
</Button>
<Tooltip title={isAdmin && !user.canRemoveAdmin ? t("adminUsersLastAdminHelp") : ""}>
<span><Button color="error" variant="outlined" disabled={busy || isAdmin && !user.canRemoveAdmin} onClick={() => void remove(user)} fullWidth>{t("adminUsersDelete")}</Button></span>
</Tooltip>
</Stack>
</Stack>
</Paper>
);
})}
</Stack>
) : (
<Paper variant="outlined" role="region" aria-label={t("adminUsersTitle")} tabIndex={0} sx={{ borderRadius: 1, minWidth: 0, overflow: "auto" }}>
<DataGrid
autoHeight
getRowHeight={() => "auto"}
rows={rows}
columns={columns}
disableRowSelectionOnClick
loading={loading}
pageSizeOptions={[5, 10, 25]}
initialState={{
pagination: { paginationModel: { pageSize: 10, page: 0 } },
sorting: { sortModel: [{ field: "email", sort: "asc" }] },
}}
sx={{
border: 0,
'& .MuiDataGrid-columnHeaders': {
backgroundColor: 'action.hover',
fontWeight: 800,
},
'& .MuiDataGrid-cell': {
alignItems: 'center',
},
}}
/>
{!loading && rows.length === 0 ? (
<Typography sx={{ color: "text.secondary", py: 2, textAlign: "center" }}>{t("adminUsersNoUsers")}</Typography>
) : null}
</Paper>
) : null}
</Box>
);
}