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