SPB Git

Repository Public

Users.tsx 12.4 KB 154 lines tsx

1"use client";2import { useState } from "react";3import { apiDelete, apiPatch, type Schemas } from "@/api/client";4import { useApiList, useApiQuery } from "@/api/query";5import { useI18n } from "@/i18n";6import { useMe, useSession } from "@/shell/session";7import { Badge, Button, ConfirmDialog, DataStamp, DataTable, Drawer, ErrorState, KeyValue, LoadMore, QueryBoundary, SelectField, SkeletonRows, StateDot, Switch, TextField, type Column } from "@/ui";8import { InviteDialog } from "./Invitations";9import { Gate } from "./SettingsFrame";10import { useAct } from "./useAct";1112type User = Schemas["User"];13type Role = Schemas["UserRole"];14const ROLES: Role[] = ["owner", "admin", "operator", "viewer"];1516export function UsersSection() {17  return <Gate permission="users.manage"><Users /></Gate>;18}1920function Users() {21  const { t, fmt } = useI18n();22  const [q, setQ] = useState("");23  const [role, setRole] = useState<Role | "">("");24  const [disabled, setDisabled] = useState<"" | "true" | "false">("");25  const list = useApiList("/users", { query: { limit: 50, ...(q.trim() ? { q: q.trim() } : {}), ...(role ? { role } : {}), ...(disabled ? { disabled: disabled === "true" } : {}) } });26  const [open, setOpen] = useState<string | null>(null);2728  const columns: Column<User>[] = [29    { id: "name", header: t("common.name"), cell: (u) => <button type="button" className="aud-link set-userlink" onClick={() => setOpen(u.id)} data-testid="user-open" data-handle={u.handle}>{u.display_name}</button>, sortValue: (u) => u.display_name },30    { id: "handle", header: t("settings.handle"), mono: true, cell: (u) => `@${u.handle}`, sortValue: (u) => u.handle },31    { id: "role", header: t("settings.role"), cell: (u) => t(`states.role.${u.role}`), sortValue: (u) => ROLES.indexOf(u.role) },32    { id: "state", header: t("common.state"), cell: (u) => <StateDot tone={u.disabled ? "offline" : "ok"} label={u.disabled ? t("settings.users.disabled") : t("settings.users.active")} />, sortValue: (u) => (u.disabled ? 1 : 0) },33    { id: "keys", header: t("settings.users.passkeys"), align: "right", hide: "sm", cell: (u) => u.passkey_count ?? <span className="faint">{t("common.notObserved")}</span>, sortValue: (u) => u.passkey_count },34    { id: "seen", header: t("settings.users.lastSeen"), hide: "md", cell: (u) => (u.last_seen_at ? <time dateTime={u.last_seen_at} className="num" title={fmt.dateTime(u.last_seen_at)}>{fmt.relative(u.last_seen_at)}</time> : <span className="faint">{t("common.never")}</span>), sortValue: (u) => (u.last_seen_at ? Date.parse(u.last_seen_at) : undefined) },35  ];3637  return (38    <div className="stack-lg" data-testid="screen-settings-users">39      <section className="section" aria-labelledby="set-users">40        <div className="section-head"><h2 id="set-users">{t("settings.users.title")}</h2><DataStamp at={list.ready ? list.updatedAt : undefined} /></div>41        <p className="muted">{t("settings.users.intro")}</p>42        <div className="toolbar">43          <TextField label={t("common.search")} icon="search" type="search" value={q} onChange={setQ} />44          <SelectField label={t("settings.role")} value={role} onChange={setRole} options={[{ value: "", label: t("common.all") }, ...ROLES.map((r) => ({ value: r, label: t(`states.role.${r}`) }))]} />45          <SelectField label={t("common.state")} value={disabled} onChange={setDisabled} options={[{ value: "", label: t("common.all") }, { value: "false", label: t("settings.users.active") }, { value: "true", label: t("settings.users.disabled") }]} />46        </div>47        {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} /> : !list.ready ? <SkeletonRows rows={4} /> : (48          <DataTable caption={t("settings.users.title")} columns={columns} rows={list.items} rowKey={(u) => u.id} onRowClick={(u) => setOpen(u.id)} initialSort={{ id: "name", dir: "asc" }} empty={<span className="muted">{t("settings.users.empty")}</span>} />49        )}50        <LoadMore hasMore={list.hasMore} loading={list.loadingMore} onMore={list.loadMore} />51      </section>52      {open ? <UserDrawer id={open} onClose={() => setOpen(null)} /> : null}53    </div>54  );55}5657function UserDrawer({ id, onClose }: { id: string; onClose: () => void }) {58  const { t, fmt } = useI18n();59  const me = useMe();60  const { can } = useSession();61  const q = useApiQuery("/users/{id}", { path: { id } });62  const passkeys = useApiQuery("/users/{id}/passkeys", { path: { id } });63  const sessions = useApiQuery("/users/{id}/sessions", { path: { id } });64  const devices = useApiQuery("/users/{id}/devices", { path: { id } });65  const { busy, act } = useAct();66  const [confirm, setConfirm] = useState<{ title: string; body: string; run: () => Promise<unknown> } | null>(null);67  const [recover, setRecover] = useState<User | null>(null);68  const self = me.user.id === id;69  const ask = (title: string, body: string, fn: () => Promise<unknown>, ok: string, invalidate: string[]) => setConfirm({ title, body, run: () => act(fn, { ok, invalidate }) });7071  return (72    <Drawer open onClose={onClose} title={q.data?.display_name ?? t("settings.users.detail")} description={q.data ? `@${q.data.handle}` : undefined} size="wide" footer={<Button onClick={onClose}>{t("common.close")}</Button>}>73      <QueryBoundary query={q}>74        {(u) => {75          // an admin cannot create or modify an owner; nobody edits their own role or disables themselves here76          const locked = self || (u.role === "owner" && me.user.role !== "owner");77          const roles = ROLES.filter((r) => r !== "owner" || me.user.role === "owner" || u.role === "owner");78          return (79            <div className="stack-lg" data-testid="user-drawer" data-user-id={u.id}>80              <KeyValue items={[81                { label: t("common.state"), value: <StateDot tone={u.disabled ? "offline" : "ok"} label={u.disabled ? t("settings.users.disabled") : t("settings.users.active")} /> },82                { label: t("common.created"), value: <span className="num">{fmt.dateTime(u.created_at)}</span> },83                { label: t("settings.users.lastSeen"), value: u.last_seen_at ? <span className="num">{fmt.dateTime(u.last_seen_at)}</span> : <span className="faint">{t("common.never")}</span> },84                { label: t("settings.profile.language"), value: u.locale === "fr" ? "Français" : "English" },85              ]} />86              <div className="stack">87                <h3>{t("settings.users.access")}</h3>88                {locked ? <p className="mcc-hint">{self ? t("settings.users.selfLocked") : t("settings.users.ownerLocked")}</p> : null}89                <div className="mcc-form-row">90                  <SelectField label={t("settings.role")} value={u.role} disabled={locked || busy} options={roles.map((r) => ({ value: r, label: t(`states.role.${r}`) }))} data-testid="user-role"91                    onChange={(r) => { if (r !== u.role) ask(t("settings.users.roleTitle"), t("settings.users.roleBody", { name: u.display_name, role: t(`states.role.${r}`) }), () => apiPatch("/users/{id}", { path: { id }, body: { role: r } }), t("settings.users.roleChanged"), ["/users"]); }} />92                  <Switch label={t("settings.users.enabled")} hint={t("settings.users.enabledHint")} checked={!u.disabled} disabled={locked || busy}93                    onChange={(on) => ask(on ? t("settings.users.enableTitle") : t("settings.users.disableTitle"), on ? t("settings.users.enableBody", { name: u.display_name }) : t("settings.users.disableBody", { name: u.display_name }), () => apiPatch("/users/{id}", { path: { id }, body: { disabled: !on } }), on ? t("settings.users.enabledDone") : t("settings.users.disabledDone"), ["/users"])} />94                </div>95                {can("invitations.manage") ? <div className="row"><Button icon="key" onClick={() => setRecover(u)} data-testid="user-recovery">{t("settings.users.recovery")}</Button><span className="mcc-hint">{t("settings.users.recoveryHint")}</span></div> : null}96              </div>97              <div className="stack-sm">98                <h3>{t("settings.passkeys.title")}</h3>99                <QueryBoundary query={passkeys} compact>100                  {(d) => d.items.length === 0 ? <p className="muted">{t("settings.users.noPasskeys")}</p> : (101                    <ul className="set-list">102                      {d.items.map((p) => (103                        <li key={p.id} className="set-row">104                          <div className="grow stack-sm"><div className="row-wrap"><strong>{p.label || t("settings.passkeys.unnamed")}</strong>{p.revoked_at ? <Badge tone="offline">{t("settings.passkeys.revoked")}</Badge> : null}</div>105                            <div className="set-meta"><span>{t("settings.created", { time: fmt.dateTime(p.created_at) })}</span><span>{p.last_used_at ? t("settings.passkeys.lastUsed", { time: fmt.relative(p.last_used_at) }) : t("settings.passkeys.neverUsed")}</span></div></div>106                          {!p.revoked_at ? <Button size="sm" variant="danger" onClick={() => ask(t("settings.users.revokePasskeyTitle"), t("settings.users.revokePasskeyBody"), () => apiDelete("/users/{id}/passkeys/{passkeyId}", { path: { id, passkeyId: p.id } }), t("settings.passkeys.removed"), ["/users"])}>{t("settings.revoke")}</Button> : null}107                        </li>108                      ))}109                    </ul>110                  )}111                </QueryBoundary>112              </div>113              <div className="stack-sm">114                <h3>{t("settings.sessions.title")}</h3>115                <QueryBoundary query={sessions} compact>116                  {(d) => d.items.length === 0 ? <p className="muted">{t("settings.sessions.empty")}</p> : (117                    <ul className="set-list">118                      {d.items.map((s) => (119                        <li key={s.id} className="set-row">120                          <div className="grow stack-sm"><div className="row-wrap"><strong>{s.device_label || t("settings.sessions.unknownDevice")}</strong>{s.current ? <Badge tone="ok">{t("settings.current")}</Badge> : null}<Badge tone="neutral" icon={false}>{t(`settings.sessions.kind.${s.kind}`)}</Badge></div>121                            <div className="set-meta"><span>{t("settings.lastSeen", { time: fmt.relative(s.last_seen_at) })}</span>{s.ip ? <span className="mono">{s.ip}</span> : null}</div></div>122                          <Button size="sm" variant="danger" onClick={() => ask(t("settings.sessions.revokeTitle"), t("settings.sessions.revokeBody"), () => apiDelete("/sessions/{id}", { path: { id: s.id } }), t("settings.sessions.revoked"), ["/users"])}>{t("settings.revoke")}</Button>123                        </li>124                      ))}125                    </ul>126                  )}127                </QueryBoundary>128              </div>129              <div className="stack-sm">130                <h3>{t("settings.devices.title")}</h3>131                <QueryBoundary query={devices} compact>132                  {(d) => d.items.length === 0 ? <p className="muted">{t("settings.devices.empty")}</p> : (133                    <ul className="set-list">134                      {d.items.map((x) => (135                        <li key={x.id} className="set-row">136                          <div className="grow stack-sm"><div className="row-wrap"><strong>{x.label || t("settings.sessions.unknownDevice")}</strong>{x.revoked_at ? <Badge tone="offline">{t("settings.devices.revokedBadge")}</Badge> : null}<Badge tone="neutral" icon={false}>{t(`settings.devices.kind.${x.kind}`)}</Badge></div>137                            <div className="set-meta"><span>{x.last_seen_at ? t("settings.lastSeen", { time: fmt.relative(x.last_seen_at) }) : t("settings.neverSeen")}</span></div></div>138                          {!x.revoked_at ? <Button size="sm" variant="danger" onClick={() => ask(t("settings.devices.revokeTitle"), t("settings.devices.revokeBody"), () => apiDelete("/devices/{id}", { path: { id: x.id } }), t("settings.devices.revoked"), ["/users"])}>{t("settings.revoke")}</Button> : null}139                        </li>140                      ))}141                    </ul>142                  )}143                </QueryBoundary>144              </div>145            </div>146          );147        }}148      </QueryBoundary>149      <ConfirmDialog open={confirm !== null} onClose={() => setConfirm(null)} danger busy={busy} title={confirm?.title ?? ""} body={confirm?.body} confirmLabel={t("common.confirm")} onConfirm={() => { if (confirm) void confirm.run().then(() => setConfirm(null)); }} />150      {recover ? <InviteDialog targetUser={recover} onClose={() => setRecover(null)} /> : null}151    </Drawer>152  );153}154
Files main
Menu

Theme