1import { A, useNavigate, useParams, useSearchParams } from "@solidjs/router";
2import ArrowLeft from "lucide-solid/icons/arrow-left";
3import ChevronDown from "lucide-solid/icons/chevron-down";
4import Search from "lucide-solid/icons/search";
5import UserPlus from "lucide-solid/icons/user-plus";
6import X from "lucide-solid/icons/x";
7import { type Accessor, createEffect, createSignal, For, type Resource, Show } from "solid-js";
8import { Dynamic } from "solid-js/web";
9import { parseResponse } from "hono/client";
10import { canOpen, sectionsOf, type ServiceSummary } from "../types/model.ts";
11import type { Group } from "../types/users.ts";
12import { api, query, reason } from "../api.ts";
13import { Ago } from "../components/Ago.tsx";
14import { Checkbox } from "../components/Checkbox.tsx";
15import { AppIcon } from "../components/AppIcon.tsx";
16import { Copy } from "../components/Copy.tsx";
17import { showConfirmDialog, showTextDialog } from "../components/Dialog.tsx";
18import { ListPage } from "../components/ListPage.tsx";
19import { lastGood, Loaded, SkeletonRows } from "../components/Loaded.tsx";
20import { Reveal } from "../components/Reveal.tsx";
21import { PAGES } from "../components/Sidebar.tsx";
22import { TabBar } from "../components/TabBar.tsx";
23import { toast } from "../components/Toast.tsx";
24import { ago, count, date, datetime, plural } from "../format.ts";
25import "./Users.css";
26import { CommitIdentity } from "./Account.tsx";
27import { FolderAccess } from "./Shares.tsx";
28
29const STEPS: [string, string][] = [["SETUP", "finish setup"], ["UPDATE_PASSWORD", "new password"], ["UPDATE_PROFILE", "check profile"]];
30
31const GUESTS = {
32 github: { name: "GitHub", field: "GitHub username", placeholder: "octocat" },
33 astheno: { name: "Astheno", field: "Astheno username", placeholder: "janedoe" },
34 atproto: { name: "AT Protocol", field: "AT handle", placeholder: "alice.bsky.social" },
35} as const;
36
37const ASTHENO_HINT = "Whoever holds this Astheno username can sign in as this account, on Snow Globe and Shale. Their first sign-in binds it.";
38
39const STATES = { all: "users", guests: "guests", disabled: "disabled", pending: "setup pending" } as const;
40
41type Params = { q?: string; group?: string; state?: keyof typeof STATES };
42
43const load = () => Promise.all([parseResponse(api.users.$get()), parseResponse(api.services.$get())])
44 .then(([{ users, groups }, services]) => ({ users, groups, services }));
45type Data = Awaited<ReturnType<typeof load>>;
46export const directory = query("users", load);
47const identityOf = query("commit-identity", (id: string) => parseResponse(api.users[":id"]["commit-identity"].$get({ param: { id } })));
48const credentialsOf = query("credentials", (id: string) => parseResponse(api.users[":id"].credentials.$get({ param: { id } })));
49type User = Data["users"][number];
50
51const fullName = (user: User) => [user.firstName, user.lastName].filter(Boolean).join(" ");
52const names = (user: User) => user.groups.map((group) => group.name);
53const inState = (user: User, state: keyof typeof STATES) =>
54 state === "guests" ? user.kind === "guest" : user.kind !== "guest" &&
55 (state === "all" || (state === "disabled" ? !user.enabled : user.enabled && user.requiredActions.length > 0));
56
57/** The apps a set of groups opens, and dashboard pages; `everything` when nothing is out of reach. */
58function reach(groups: string[], services: ServiceSummary[]) {
59 const apps = services.filter((app) => app.id === "copyparty" && app.url);
60 const open = {
61 apps: apps.filter((app) => canOpen(groups, app.access)),
62 pages: PAGES.filter((page) => sectionsOf(groups).includes(page.section)),
63 };
64 return { ...open, everything: open.apps.length === apps.length && open.pages.length === PAGES.length };
65}
66
67/** What joining `group` opens beyond what every signed-in user already can. */
68function adds(group: string, services: ServiceSummary[]) {
69 const base = reach([], services);
70 const own = reach([group], services);
71 return {
72 everything: own.everything,
73 apps: own.apps.filter((app) => !base.apps.includes(app)),
74 pages: own.pages.filter((page) => !base.pages.includes(page)),
75 };
76}
77
78/** "30 members · opens Jellyfin, Navidrome" */
79function groupTip(group: string, d: Data) {
80 if (group === "knife-native") return `${plural(d.users.filter((user) => names(user).includes(group)).length, "member")} · opens The Knife’s Native UI`;
81 const more = adds(group, d.services);
82 const members = d.users.filter((user) => names(user).includes(group)).length;
83 const metrics = sectionsOf([group]).includes("metrics") ? ["machine metrics"] : [];
84 const opens = more.everything ? "everything"
85 : [...more.apps.map((app) => app.name), ...more.pages.map((page) => page.label), ...metrics].join(", ");
86 return `${plural(members, "member")} · opens ${opens}`;
87}
88
89
90const appName = (clientId: string, services: ServiceSummary[]) =>
91 clientId === "dashboard" ? "Snow Globe" : clientId === "file" ? "Files" : services.find((service) => service.id === clientId)?.name ?? clientId;
92
93/** "active 3h ago in Jellyfin, Shale", from their open sessions. */
94function seen(user: User, services: ServiceSummary[]) {
95 if (!user.sessions.length) return "not signed in";
96 const last = Math.max(...user.sessions.map((session) => session.lastAccess));
97 const used = [...new Set(user.sessions.flatMap((session) => Object.values(session.clients)))].map((id) => appName(id, services));
98 return `active ${ago(last / 1000)} in ${used.join(", ")}`;
99}
100
101/** Tailscale hands out 100.64.0.0/10; the rest of the private ranges are the home network. */
102function network(ip: string) {
103 const [a, b] = ip.split(".").map(Number) as [number, number];
104 if (a === 100 && b >= 64 && b < 128) return "via Tailscale";
105 if (a === 10 || (a === 172 && b >= 16 && b < 32) || (a === 192 && b === 168)) return "local network";
106}
107
108/** Where the list was scrolled when a user page opened, so going back lands in the same place. */
109let listScroll = 0;
110/** Whether the open user page was reached from the list, so "back" can return to it with its filters. */
111let fromList = false;
112
113export function Users() {
114 const params = useParams<{ name?: string }>();
115 const [data, { refetch }] = directory.use();
116 const ready = lastGood(data);
117 return (
118 <Show when={params.name} keyed fallback={<List data={data} ready={ready} refetch={refetch} />}>
119 {(name) => <Person name={name} data={data} refetch={refetch} />}
120 </Show>
121 );
122}
123
124function StateTag(props: { user: User }) {
125 return (
126 <>
127 <Show when={props.user.kind === "guest"}><span class="chip">Shale guest</span></Show>
128 <Show when={props.user.enabled} fallback={<span class="chip">disabled</span>}>
129 <Show when={props.user.requiredActions.length}>
130 <span class="chip warn" tabindex="0"
131 data-tip={props.user.requiredActions.map((action) => STEPS.find(([step]) => step === action)?.[1] ?? action).join(", ")}>
132 setup pending
133 </span>
134 </Show>
135 </Show>
136 </>
137 );
138}
139
140/** Apps and dashboard pages; `used` links each to its page and tips an app with when it was last used. */
141function Grants(props: { apps: ServiceSummary[]; pages: typeof PAGES; used?: Map<string, number> }) {
142 const tag = () => (props.used ? A : "span");
143 return (
144 <span class="grants">
145 <For each={props.apps}>
146 {(app) => (
147 <Dynamic component={tag()} class="grant" href={`/services/${app.id}`}
148 data-tip={props.used?.has(app.id) ? `used ${ago(props.used.get(app.id)! / 1000)}` : undefined}>
149 <AppIcon id={app.id} name={app.name} icon={app.icon} />{app.name}
150 </Dynamic>
151 )}
152 </For>
153 <For each={props.pages}>
154 {(page) => (
155 <Dynamic component={tag()} class="grant dash" href={page.href} data-tip="dashboard page">
156 <page.icon class="icon" />{page.label}
157 </Dynamic>
158 )}
159 </For>
160 </span>
161 );
162}
163
164function List(props: { data: Resource<Data>; ready: Accessor<Data | undefined>; refetch: () => void }) {
165 const [params, setParams] = useSearchParams<Params>();
166 const navigate = useNavigate();
167 const state = () => params.state ?? "all";
168 const ready = props.ready;
169 const [selection, setSelection] = createSignal(new Set<string>());
170 const selected = () => ready()?.users.filter((user) => user.kind !== "guest" && selection().has(user.id)) ?? [];
171 createEffect(() => { params.q; params.group; params.state; setSelection(new Set<string>()); });
172 const select = (users: User[], checked: boolean) => setSelection((previous) => {
173 const next = new Set(previous);
174 for (const user of users) checked ? next.add(user.id) : next.delete(user.id);
175 return next;
176 });
177 const editGroups = () => {
178 const users = selected();
179 const [changes, setChanges] = createSignal<Record<string, boolean>>({});
180 showConfirmDialog({
181 title: "Edit groups",
182 description: `Update ${plural(users.length, "selected user")}. Other memberships stay unchanged.`,
183 confirmLabel: "apply changes",
184 canConfirm: () => Object.keys(changes()).length > 0,
185 body: () => <div class="field" role="group" aria-label="Groups">
186 <p class="hint">A dash means some users belong to the group. Leave it unchanged to keep their current memberships.</p>
187 <For each={ready()!.groups}>{(group) => {
188 const members = () => users.filter((user) => user.groups.some((g) => g.id === group.id)).length;
189 return <Checkbox checked={changes()[group.id] ?? members() === users.length}
190 indeterminate={changes()[group.id] === undefined && members() > 0 && members() < users.length}
191 onChange={(checked) => setChanges((previous) => {
192 const next = { ...previous };
193 if (members() === (checked ? users.length : 0)) delete next[group.id];
194 else next[group.id] = checked;
195 return next;
196 })}>{group.name}</Checkbox>;
197 }}</For>
198 </div>,
199 onConfirm: async () => {
200 await parseResponse(api.users.groups.$put({ json: {
201 users: users.map((user) => user.id),
202 add: Object.keys(changes()).filter((id) => changes()[id]),
203 remove: Object.keys(changes()).filter((id) => !changes()[id]),
204 } }));
205 await props.refetch();
206 setSelection(new Set<string>());
207 },
208 });
209 };
210 fromList = false;
211 const pick = (group?: string) => setParams({ group: group === params.group ? undefined : group });
212 const href = (user: User) => `/users/${user.username}`;
213 const open = (user: User) => {
214 fromList = true;
215 navigate(href(user));
216 };
217 const shown = (users: User[]) => {
218 const q = params.q?.trim().toLowerCase() ?? "";
219 return users
220 .filter((user) => !q || [user.username, fullName(user), user.email, ...names(user)].some((v) => v?.toLowerCase().includes(q)))
221 .filter((user) => !params.group || names(user).includes(params.group))
222 .filter((user) => inState(user, state()))
223 .toSorted((a, b) => a.username.localeCompare(b.username));
224 };
225 const selectable = () => shown(ready()?.users ?? []).filter((user) => user.kind !== "guest");
226 let guestMenu!: HTMLDivElement;
227 let guestTrigger!: HTMLButtonElement;
228 const addGuest = (provider: keyof typeof GUESTS) => {
229 const guest = GUESTS[provider];
230 guestMenu.hidePopover();
231 showTextDialog({
232 title: `Add ${guest.name} guest`,
233 description: "They can sign in to Shale and open The Knife’s Native UI.",
234 label: guest.field,
235 placeholder: guest.placeholder,
236 body: provider === "astheno" ? () => <div class="field"><span class="hint">Astheno can’t look names up. The first person to sign in with this username gets the access.</span></div> : undefined,
237 confirmLabel: "add guest",
238 returnFocus: guestTrigger,
239 onConfirm: async (handle) => {
240 const { id, created } = await parseResponse(api.users.guests.$post({ json: { provider, handle } }));
241 await props.refetch();
242 const user = ready()?.users.find((user) => user.id === id);
243 if (user) open(user);
244 if (!created) toast(`${user?.username ?? "That person"} was already a guest`);
245 },
246 });
247 };
248 const create = (groups: Group[]) => showConfirmDialog({
249 title: "New user",
250 confirmLabel: "create user",
251 body: () => {
252 const [kind, setKind] = createSignal<"invite" | "password" | "astheno">("invite");
253 return (
254 <>
255 <label class="field">username<input name="username" class="search" required autocomplete="off" spellcheck={false} autofocus /></label>
256 <label class="field">email<input name="email" type="email" class="search" autocomplete="off" spellcheck={false} /></label>
257 <div class="row">
258 <label class="field">first name<input name="firstName" class="search" autocomplete="off" /></label>
259 <label class="field">last name<input name="lastName" class="search" autocomplete="off" /></label>
260 </div>
261 <div class="field" role="group" aria-label="Groups">
262 groups
263 <span class="toggles">
264 <For each={groups}>
265 {(g) => <label class="chip toggle"><input type="checkbox" name="groups" value={g.id} />{g.name}</label>}
266 </For>
267 </span>
268 </div>
269 <div class="field">
270 first sign-in
271 <TabBar label="First sign-in">
272 <button type="button" aria-pressed={kind() === "invite"} onClick={() => setKind("invite")}>create an invitation link</button>
273 <button type="button" aria-pressed={kind() === "password"} onClick={() => setKind("password")}>set a password</button>
274 <button type="button" aria-pressed={kind() === "astheno"} onClick={() => setKind("astheno")}>astheno only</button>
275 </TabBar>
276 <input type="hidden" name="kind" value={kind()} />
277 </div>
278 <label class="field">astheno username{kind() === "astheno" ? "" : " (optional)"}
279 <input name="astheno" class="search" required={kind() === "astheno"} maxLength={17} autocomplete="off" spellcheck={false} placeholder="janedoe" />
280 <span class="hint">{ASTHENO_HINT}</span>
281 </label>
282 <Show when={kind() === "password"}>
283 <label class="field">temporary password
284 <input name="password" class="search" type="password" required minLength={8} maxLength={1024} autocomplete="new-password" />
285 <span class="hint">They pick their own at first sign-in</span>
286 </label>
287 </Show>
288 </>
289 );
290 },
291 onConfirm: async (form) => {
292 const text = (name: string) => String(form.get(name) ?? "");
293 const { id, url } = await parseResponse(api.users.$post({
294 json: {
295 profile: { username: text("username"), email: text("email"), firstName: text("firstName"), lastName: text("lastName") },
296 groups: form.getAll("groups").map(String),
297 setup: text("kind") === "password" ? { kind: "password", password: text("password") } : { kind: text("kind") as "invite" | "astheno" },
298 astheno: text("astheno") || undefined,
299 },
300 }));
301 await props.refetch();
302 const user = ready()?.users.find((user) => user.id === id);
303 if (user) open(user);
304 if (url) showConfirmDialog({ title: "Invitation link", description: "Works once and expires in 24 hours. Send it to this person.", body: <Copy value={url} />, confirmLabel: "done", onConfirm: async () => {} });
305 },
306 });
307
308 return (
309 <ListPage id="users" flush head={
310 <div class="page-head">
311 <h1>users</h1>
312 <Show when={selected().length}>
313 <span class="muted" role="status">{count(selected().length)} selected</span>
314 <button class="button" onClick={editGroups}>edit groups</button>
315 <button class="button" onClick={() => setSelection(new Set<string>())}>clear selection</button>
316 </Show>
317 <span class="spacer" />
318 <button ref={guestTrigger} class="button" popovertarget="add-guest" style={{ "anchor-name": "--add-guest" }}>
319 add guest<ChevronDown size={14} />
320 </button>
321 <div ref={guestMenu} id="add-guest" popover class="guest-menu" style={{ "position-anchor": "--add-guest" }}>
322 <For each={Object.keys(GUESTS) as (keyof typeof GUESTS)[]}>
323 {(provider) => <button type="button" onClick={() => addGuest(provider)}>{GUESTS[provider].field}</button>}
324 </For>
325 </div>
326 <button class="button primary" disabled={!ready()} onClick={() => create(ready()!.groups)}>
327 <UserPlus size={14} />new user
328 </button>
329 </div>
330 } summary={
331 <Show when={ready()} fallback={props.data.loading && (
332 <div class="card access" inert>
333 <For each={Array(8)}>
334 {(_, i) => (
335 <div class="access-row">
336 <span class="skeleton" style={{ height: "12px" }} />
337 <span />
338 <span class="skeleton" style={{ height: "12px", width: `${20 + ((i() * 37) % 50)}%` }} />
339 </div>
340 )}
341 </For>
342 </div>
343 )}>
344 {(d) => {
345 const everyone = () => reach([], d().services);
346 const rows = () => d().groups.map((group) => ({
347 group, ...adds(group.name, d().services),
348 members: d().users.filter((user) => names(user).includes(group.name)).map((user) => user.username).sort(),
349 }));
350 const preview = (members: string[]) =>
351 members.length > 6 ? `${members.slice(0, 5).join(", ")} +${members.length - 5} more` : members.join(", ");
352 return (
353 <div class="card access" role="group" aria-label="Filter by group">
354 <button class="access-row" aria-pressed={!params.group} onClick={() => pick()}>
355 <span class="who">everyone</span>
356 <span class="num">{count(d().users.length)}</span>
357 <Grants apps={everyone().apps} pages={everyone().pages} />
358 </button>
359 <For each={rows()}>
360 {(row) => (
361 <button class="access-row" aria-pressed={params.group === row.group.name} onClick={() => pick(row.group.name)}
362 data-tip={row.members.length ? preview(row.members) : undefined}>
363 <span class="who">{row.group.name}</span>
364 <span class="num">{count(row.members.length)}</span>
365 <Show when={!row.everything} fallback={<span class="grants muted">everything</span>}>
366 <Grants apps={row.apps} pages={row.pages} />
367 </Show>
368 </button>
369 )}
370 </For>
371 </div>
372 );
373 }}
374 </Show>
375 }>
376 <Loaded data={props.data} what="users" retry={props.refetch} skeleton={
377 <>
378 <div class="users-toolbar"><span class="skeleton" style={{ width: "260px", height: "30px" }} /></div>
379 <div class="edge"><SkeletonRows count={8} /></div>
380 </>
381 }>
382 {(d) => (
383 <>
384 <div class="users-toolbar">
385 <label class="search-box">
386 <Search size={14} aria-hidden="true" />
387 <input type="search" placeholder="mika, Tanaka, media…" aria-label="Search users" value={params.q ?? ""}
388 onInput={(event) => setParams({ q: event.currentTarget.value || undefined }, { replace: true })} />
389 </label>
390 <Reveal when={!!params.group} axis="x">
391 <button class="chip filter" aria-label={`Show every group, not just ${params.group}`} data-tip="show every group"
392 onClick={() => pick()}>
393 {params.group}<X size={12} />
394 </button>
395 </Reveal>
396 <span class="spacer" />
397 <TabBar label="Filter by state">
398 <For each={Object.entries(STATES) as [keyof typeof STATES, string][]}>
399 {([key, label]) => (
400 <button aria-pressed={state() === key} onClick={() => setParams({ state: key === "all" ? undefined : key })}>
401 {label}
402 <Show when={key !== "all"}>
403 <span class="count">{count(d().users.filter((user) => inState(user, key)).length)}</span>
404 </Show>
405 </button>
406 )}
407 </For>
408 </TabBar>
409 </div>
410 <div class="fill users-table" ref={(el) => requestAnimationFrame(() => (el.scrollTop = listScroll))}
411 onScroll={(event) => (listScroll = event.currentTarget.scrollTop)}>
412 <Show when={shown(d().users).length} fallback={
413 <div class="empty">
414 No users match.{" "}
415 <button class="button small" onClick={() => setParams({ q: undefined, group: undefined, state: undefined })}>
416 clear filters
417 </button>
418 </div>
419 }>
420 <table class="data">
421 <thead><tr><th class="user-select">
422 <Checkbox checked={selectable().length > 0 && selectable().every((user) => selection().has(user.id))}
423 indeterminate={selectable().some((user) => selection().has(user.id)) && selectable().some((user) => !selection().has(user.id))}
424 disabled={!selectable().length}
425 onChange={(checked) => select(selectable(), checked)}>
426 <span class="sr-only">Select visible users</span>
427 </Checkbox>
428 </th><th>username</th><th>name</th><th>email</th><th>groups</th></tr></thead>
429 <tbody>
430 <For each={shown(d().users)}>
431 {(user) => (
432 <tr classList={{ disabled: !user.enabled, selected: selection().has(user.id) }}
433 onClick={(event) => !(event.target as Element).closest("a, button, input, label") && open(user)}>
434 <td class="user-select"><Checkbox checked={selection().has(user.id)}
435 disabled={user.kind === "guest" ? "Guests can use Shale only" : false}
436 onChange={(checked) => select([user], checked)}><span class="sr-only">Select {user.username}</span></Checkbox></td>
437 <td class="username">
438 <span class="inline">
439 <a class="name" href={href(user)} onClick={() => (fromList = true)} data-tip={seen(user, d().services)}>
440 {user.username}
441 </a>
442 <StateTag user={user} />
443 </span>
444 </td>
445 <td>{fullName(user) || "–"}</td>
446 <td class="email">
447 <Show when={user.email} fallback="–">{(email) => <Copy value={email()} />}</Show>
448 </td>
449 <td class="groups">
450 <div class="chips">
451 <For each={user.groups}>
452 {(g) => (
453 <button class="chip" aria-pressed={params.group === g.name} data-tip={groupTip(g.name, d())}
454 onClick={() => pick(g.name)}>
455 {g.name}
456 </button>
457 )}
458 </For>
459 </div>
460 </td>
461 </tr>
462 )}
463 </For>
464 </tbody>
465 </table>
466 </Show>
467 </div>
468 </>
469 )}
470 </Loaded>
471 </ListPage>
472 );
473}
474
475/** Back to the list, through history when it's the page behind this one, so its filters and scroll come back. */
476function useBack() {
477 const navigate = useNavigate();
478 return () => (fromList ? history.back() : navigate("/users"));
479}
480
481function Person(props: { name: string; data: Resource<Data>; refetch: () => unknown }) {
482 const back = useBack();
483 return (
484 <Loaded data={props.data} what="users" retry={props.refetch} skeleton={
485 <div class="page user-page">
486 <div class="page-head"><span class="skeleton" style={{ width: "180px", height: "26px" }} /></div>
487 <div class="user-grid">
488 <For each={[0, 1]}>
489 {() => (
490 <div class="column">
491 <div class="skeleton" style={{ height: "180px" }} />
492 <div class="skeleton" style={{ height: "140px" }} />
493 </div>
494 )}
495 </For>
496 </div>
497 </div>
498 }>
499 {(d) => (
500 <Show when={d().users.find((user) => user.username === props.name)} fallback={
501 <div class="page user-page">
502 <div class="empty">
503 No user named {props.name}.{" "}
504 <button class="button small" onClick={back}>back to users</button>
505 </div>
506 </div>
507 }>
508 {(user) => <Profile user={user()} data={d()} refetch={props.refetch} />}
509 </Show>
510 )}
511 </Loaded>
512 );
513}
514
515function Profile(props: { user: User; data: Data; refetch: () => unknown }) {
516 const back = useBack();
517 const param = () => ({ id: props.user.id });
518 const [credentials, credentialActions] = credentialsOf.use(() => props.user.id);
519 const [identity, identityActions] = identityOf.use(() => props.user.id);
520 const [busy, setBusy] = createSignal<string>();
521
522 const patch = async (json: Parameters<typeof api.users[":id"]["$patch"]>[0]["json"]) => {
523 await parseResponse(api.users[":id"].$patch({ param: param(), json }));
524 await props.refetch();
525 };
526 /** Runs a quick change, marking `key` busy and toasting the reason if it fails. */
527 const run = async (key: string, change: () => Promise<unknown>) => {
528 setBusy(key);
529 try {
530 await change();
531 } catch (failure) {
532 toast(reason(failure));
533 } finally {
534 setBusy();
535 }
536 };
537 const member = (group: Group) => props.user.groups.some((g) => g.id === group.id);
538 const toggleGroup = (group: Group) => run(group.id, async () => {
539 const route = api.users[":id"].groups[":group"];
540 const args = { param: { ...param(), group: group.id } };
541 await parseResponse(member(group) ? route.$delete(args) : route.$put(args));
542 await props.refetch();
543 });
544 const setEnabled = (enabled: boolean) => run("enabled", async () => {
545 await patch({ enabled });
546 if (!enabled) toast(`${props.user.username} can't sign in now`, { label: "undo", run: () => patch({ enabled: true }) });
547 });
548 const [setupLink, setSetupLink] = createSignal("");
549 const createLink = () => run("link", async () => {
550 const { url } = await parseResponse(api.users[":id"]["setup-link"].$post({param:param()}));
551 setSetupLink(url);
552 });
553 const revokeLink = () => run("link", async () => {
554 await parseResponse(api.users[":id"]["setup-link"].$delete({param:param()}));
555 setSetupLink(""); toast("Revoked the setup link");
556 });
557
558 const astheno = () => props.user.attributes?.astheno?.[0];
559 const linkAstheno = () => showTextDialog({
560 title: `Astheno sign-in for ${props.user.username}`,
561 label: "Astheno username",
562 placeholder: "janedoe",
563 body: () => <div class="field"><span class="hint">{ASTHENO_HINT}</span></div>,
564 confirmLabel: "link",
565 onConfirm: async (handle) => {
566 await parseResponse(api.users[":id"].astheno.$put({ param: param(), json: { handle } }));
567 await props.refetch();
568 },
569 });
570 const unlinkAstheno = () => run("astheno", async () => {
571 await parseResponse(api.users[":id"].astheno.$delete({ param: param() }));
572 await props.refetch();
573 });
574 const setPassword = () => showConfirmDialog({
575 title: `Set ${props.user.username}'s password`,
576 body: <><label class="field">new password, at least 8 characters<input name="password" class="search" type="password" required minLength={8} maxLength={1024} autocomplete="new-password" /></label><Checkbox name="temporary" checked>ask for a new one at next sign-in</Checkbox></>,
577 confirmLabel: "set password",
578 onConfirm: async (form) => {
579 const password = String(form.get("password") ?? "");
580 await parseResponse(api.users[":id"].password.$put({ param: param(), json: { password, temporary: form.has("temporary") } }));
581 await Promise.all([props.refetch(), credentialActions.refetch()]);
582 },
583 });
584 const signOut = (sessions: number) => showConfirmDialog({
585 title: `Sign ${props.user.username} out?`,
586 description: `${sessions === 1 ? "Ends their one session" : `Ends all ${sessions} sessions`}. They can sign in again.`,
587 confirmLabel: "sign out",
588 onConfirm: async () => {
589 await parseResponse(api.users[":id"].logout.$post({ param: param() }));
590 await props.refetch();
591 },
592 });
593 const remove = () => {
594 const name = props.user.username;
595 showTextDialog({
596 title: `Delete ${name}?`,
597 description: `${name} is signed out and loses access to Snow Globe and Files. This can't be undone.`,
598 label: `type ${name} to confirm`,
599 validateInput: (value) => value === name,
600 confirmLabel: "delete user",
601 destructive: true,
602 onConfirm: async () => {
603 await parseResponse(api.users[":id"].$delete({ param: param() }));
604 back();
605 await props.refetch();
606 toast(`Deleted ${name}`);
607 },
608 });
609 };
610
611 const access = () => reach(props.user.enabled ? names(props.user) : [], props.data.services);
612
613 const used = () => {
614 const last = new Map<string, number>();
615 for (const session of props.user.sessions) {
616 for (const id of Object.values(session.clients)) last.set(id, Math.max(last.get(id) ?? 0, session.lastAccess));
617 }
618 return last;
619 };
620
621 return (
622 <div class="page user-page">
623 <div class="page-head">
624 <button class="button icon-only" aria-label="Back to users" data-tip="users" onClick={back}>
625 <ArrowLeft size={16} />
626 </button>
627 <h1>{props.user.username}</h1>
628 <span class="sub">{fullName(props.user)}</span>
629 <StateTag user={props.user} />
630 <span class="spacer" />
631 <button class="button danger" onClick={remove}>delete user</button>
632 </div>
633
634 <div class="user-grid">
635 <div class="column">
636 <section class="card">
637 <h2 class="card-title">groups</h2>
638 <div class="toggles" role="group" aria-label="Groups">
639 <For each={props.data.groups}>
640 {(group) => (
641 <button class="chip toggle" aria-pressed={member(group)} disabled={props.user.kind === "guest" && group.name !== "knife-native" || busy() === group.id}
642 data-tip={groupTip(group.name, props.data)} onClick={() => toggleGroup(group)}>
643 {group.name}
644 </button>
645 )}
646 </For>
647 </div>
648 <h2 class="card-title opens">
649 can open
650 </h2>
651 <Show when={props.user.enabled} fallback={<p class="muted">nothing while disabled</p>}>
652 <Show when={props.user.kind !== "guest"} fallback={<p class="muted">Shale only</p>}>
653 <Show when={!access().everything} fallback={<p class="muted">everything</p>}>
654 <Grants apps={access().apps} pages={access().pages} used={used()} />
655 </Show>
656 </Show>
657 </Show>
658 </section>
659 <Show when={props.user.kind !== "guest"}><FolderAccess subject={`user:${props.user.id}`} enabled={props.user.enabled} /></Show>
660 <section class="card">
661 <h2 class="card-title">
662 sign-in
663 <span class="spacer" />
664 <Show when={props.user.kind !== "guest"}><button class="button small" onClick={setPassword}>set password</button></Show>
665 </h2>
666 <Show when={props.user.kind !== "guest"} fallback={<p>signs in with {GUESTS[props.user.guestProvider ?? "github"].name}</p>}>
667 <Loaded data={credentials} what="sign-in methods" retry={credentialActions.refetch}
668 skeleton={<div class="skeleton" style={{ height: "60px" }} />}>
669 {(list) => {
670 const password = () => list().find((c) => c.type === "password");
671 const passkeys = () => list().filter((c) => c.type.startsWith("webauthn"));
672 return (
673 <dl class="kv">
674 <dt>password</dt>
675 <dd>{password() ? `set ${date(password()!.createdDate / 1000)}` : "none"}</dd>
676 <dt>passkeys</dt>
677 <dd class="passkeys">
678 <For each={passkeys()} fallback="none">
679 {(c) => <span tabindex="0" data-tip={`added ${date(c.createdDate / 1000)}`}>{c.userLabel ?? "unnamed"}</span>}
680 </For>
681 </dd>
682 </dl>
683 );
684 }}
685 </Loaded>
686 <h2 class="card-title opens">astheno</h2>
687 <Show when={astheno()} fallback={<p class="muted">Not linked. Only linked accounts can sign in with Astheno.</p>}>
688 <p>{astheno()}</p>
689 </Show>
690 <button class="button small" disabled={!!astheno() || busy() === "astheno"} onClick={linkAstheno}>link</button>{" "}
691 <button class="button small" disabled={!astheno() || busy() === "astheno"} onClick={unlinkAstheno}>unlink</button>
692 <h2 class="card-title opens">setup link</h2>
693 <p class="muted">One use, valid for 24 hours. A new link replaces the previous one.</p>
694 <button class="button small" disabled={!props.user.enabled || busy() === "link"} onClick={createLink}>create setup link</button>{" "}
695 <button class="button small" disabled={busy() === "link"} onClick={revokeLink}>revoke link</button>
696 <Show when={setupLink()}><p style={{"overflow-wrap":"anywhere"}}><Copy value={setupLink()} /></p></Show>
697 </Show>
698 </section>
699 </div>
700
701 <div class="column">
702 <section class="card">
703 <h2 class="card-title">profile</h2>
704 <div class="fields">
705 <span class="label">username</span><span>{props.user.username}</span>
706 <Field label="email" type="email" value={props.user.email} onSave={(email) => patch({ email })} />
707 <span />
708 <Checkbox checked={props.user.emailVerified} disabled={busy() === "verified"}
709 onChange={(emailVerified) => run("verified", () => patch({ emailVerified }))}>
710 verified
711 </Checkbox>
712 <Field label="first name" value={props.user.firstName} onSave={(firstName) => patch({ firstName })} />
713 <Field label="last name" value={props.user.lastName} onSave={(lastName) => patch({ lastName })} />
714 <span class="label">sign-in</span>
715 <Checkbox checked={props.user.enabled} disabled={busy() === "enabled"} onChange={setEnabled}>allowed</Checkbox>
716 <span class="label">created</span>
717 <span><Ago t={props.user.createdTimestamp / 1000} /></span>
718 </div>
719 </section>
720
721 <Show when={props.user.kind !== "guest"}>
722 <Loaded data={identity} what="commit identity" retry={identityActions.refetch} skeleton={<div class="skeleton" style={{height:"100px"}} />}>
723 {data => <CommitIdentity user={props.user} identity={data()} refetch={identityActions.refetch} admin />}
724 </Loaded>
725 </Show>
726
727 <section class="card">
728 <h2 class="card-title">
729 sessions
730 <span class="spacer" />
731 <button class="button small" disabled={!props.user.sessions.length}
732 onClick={() => signOut(props.user.sessions.length)}>
733 sign out
734 </button>
735 </h2>
736 <Show when={props.user.sessions.length} fallback={<p class="muted">Not signed in anywhere</p>}>
737 <table class="data">
738 <tbody>
739 <For each={props.user.sessions}>
740 {(session) => (
741 <tr>
742 <td class="mono"><span tabindex="0" data-tip={network(session.ipAddress)}>{session.ipAddress}</span></td>
743 <td>{Object.values(session.clients).map((id) => appName(id, props.data.services)).join(", ")}</td>
744 <td class="num">
745 <time tabindex="0" datetime={new Date(session.lastAccess).toISOString()}
746 data-tip={`signed in ${datetime(session.start / 1000)}`}>
747 {ago(session.lastAccess / 1000)}
748 </time>
749 </td>
750 </tr>
751 )}
752 </For>
753 </tbody>
754 </table>
755 </Show>
756 </section>
757 </div>
758 </div>
759 </div>
760 );
761}
762
763/** A profile value that is always an input: saves on Enter or blur, Esc puts the old value back. */
764function Field(props: { label: string; value: string | null; type?: string; onSave: (value: string) => Promise<unknown> }) {
765 const [error, setError] = createSignal("");
766 const [pending, setPending] = createSignal(false);
767 const id = `field-${props.label.replace(/\W+/g, "-")}`;
768 return (
769 <>
770 <label class="label" for={id}>{props.label}</label>
771 <span class="field">
772 <input id={id} class="inline" type={props.type ?? "text"} value={props.value ?? ""} placeholder="–" autocomplete="off"
773 spellcheck={false} readOnly={pending()} aria-busy={pending()} aria-invalid={!!error()}
774 aria-describedby={error() ? `${id}-error` : undefined}
775 onChange={async (event) => {
776 const input = event.currentTarget;
777 if (input.value === (props.value ?? "")) return setError("");
778 setPending(true);
779 try {
780 await props.onSave(input.value);
781 setError("");
782 } catch (failure) {
783 setError(reason(failure));
784 } finally {
785 setPending(false);
786 }
787 }}
788 onKeyDown={(event) => {
789 if (event.key === "Enter") event.currentTarget.blur();
790 if (event.key === "Escape") {
791 event.currentTarget.value = props.value ?? "";
792 setError("");
793 event.currentTarget.blur();
794 }
795 }} />
796 <Show when={error()}><span id={`${id}-error`} class="field-error" role="alert">{error()}</span></Show>
797 </span>
798 </>
799 );
800}