@nexys/user-management-web 0.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +61 -0
  2. package/components.json +21 -0
  3. package/package.json +66 -0
  4. package/src/components/audit/audit-log-table.test.tsx +91 -0
  5. package/src/components/audit/audit-log-table.tsx +226 -0
  6. package/src/components/auth/accept-invitation-card.tsx +100 -0
  7. package/src/components/auth/forgot-password-form.tsx +92 -0
  8. package/src/components/auth/reset-password-form.tsx +143 -0
  9. package/src/components/auth/sign-in-form.test.tsx +140 -0
  10. package/src/components/auth/sign-in-form.tsx +509 -0
  11. package/src/components/auth/sign-up-form.tsx +123 -0
  12. package/src/components/layout/app-shell.tsx +189 -0
  13. package/src/components/layout/auth-shell.tsx +28 -0
  14. package/src/components/layout/theme-toggle.tsx +55 -0
  15. package/src/components/layout/user-menu.tsx +84 -0
  16. package/src/components/primitives/empty-state.tsx +40 -0
  17. package/src/components/primitives/page-header.tsx +27 -0
  18. package/src/components/primitives/spinner.tsx +28 -0
  19. package/src/components/profile/api-tokens-card.tsx +235 -0
  20. package/src/components/profile/change-password-form.tsx +158 -0
  21. package/src/components/profile/passkeys-card.tsx +180 -0
  22. package/src/components/profile/profile-card.tsx +33 -0
  23. package/src/components/profile/two-factor-card.tsx +226 -0
  24. package/src/components/projects/project-consents.tsx +572 -0
  25. package/src/components/projects/project-create-dialog.tsx +209 -0
  26. package/src/components/projects/project-detail-tabs.tsx +63 -0
  27. package/src/components/projects/project-email-templates.tsx +282 -0
  28. package/src/components/projects/project-notices.tsx +458 -0
  29. package/src/components/projects/project-settings.tsx +1133 -0
  30. package/src/components/projects/project-tenants.tsx +107 -0
  31. package/src/components/projects/projects-table.test.tsx +95 -0
  32. package/src/components/projects/projects-table.tsx +240 -0
  33. package/src/components/roles/role-badge.tsx +91 -0
  34. package/src/components/roles/role-select.tsx +76 -0
  35. package/src/components/tenants/tenant-create-dialog.tsx +163 -0
  36. package/src/components/tenants/tenant-detail-tabs.tsx +51 -0
  37. package/src/components/tenants/tenant-members.tsx +578 -0
  38. package/src/components/tenants/tenant-roles.test.tsx +91 -0
  39. package/src/components/tenants/tenant-roles.tsx +414 -0
  40. package/src/components/tenants/tenant-settings.tsx +385 -0
  41. package/src/components/tenants/tenants-table.test.tsx +71 -0
  42. package/src/components/tenants/tenants-table.tsx +245 -0
  43. package/src/components/ui/alert.tsx +52 -0
  44. package/src/components/ui/avatar.tsx +46 -0
  45. package/src/components/ui/badge.tsx +32 -0
  46. package/src/components/ui/button.tsx +64 -0
  47. package/src/components/ui/card.tsx +65 -0
  48. package/src/components/ui/dialog.tsx +99 -0
  49. package/src/components/ui/dropdown-menu.tsx +97 -0
  50. package/src/components/ui/field.tsx +44 -0
  51. package/src/components/ui/input.tsx +23 -0
  52. package/src/components/ui/label.tsx +19 -0
  53. package/src/components/ui/select.tsx +87 -0
  54. package/src/components/ui/separator.tsx +22 -0
  55. package/src/components/ui/skeleton.tsx +13 -0
  56. package/src/components/ui/switch.tsx +29 -0
  57. package/src/components/ui/table.tsx +87 -0
  58. package/src/components/ui/tabs.tsx +51 -0
  59. package/src/components/ui/textarea.tsx +22 -0
  60. package/src/components/ui/tooltip.tsx +27 -0
  61. package/src/components/users/user-create-dialog.tsx +267 -0
  62. package/src/components/users/user-delete-dialog.tsx +88 -0
  63. package/src/components/users/user-detail.tsx +843 -0
  64. package/src/components/users/users-table.test.tsx +97 -0
  65. package/src/components/users/users-table.tsx +382 -0
  66. package/src/context/auth-context.tsx +124 -0
  67. package/src/context/theme-context.test.tsx +78 -0
  68. package/src/context/theme-context.tsx +110 -0
  69. package/src/hooks/use-call.ts +64 -0
  70. package/src/index.ts +159 -0
  71. package/src/lib/error-message.ts +16 -0
  72. package/src/lib/utils.test.ts +61 -0
  73. package/src/lib/utils.ts +79 -0
  74. package/src/lib/webauthn.ts +36 -0
  75. package/src/styles.css +107 -0
  76. package/src/test-setup.ts +5 -0
  77. package/tailwind.preset.cjs +15 -0
@@ -0,0 +1,843 @@
1
+ import {
2
+ type AdminUserRow,
3
+ type AuthAccount,
4
+ type TenantRole,
5
+ type UserRole,
6
+ type UserStatus,
7
+ } from "@nexys/user-management-client";
8
+ import {
9
+ AlertCircle,
10
+ Building2,
11
+ Fingerprint,
12
+ KeyRound,
13
+ Mail,
14
+ Plus,
15
+ ShieldCheck,
16
+ Trash2,
17
+ X,
18
+ } from "lucide-react";
19
+ import { useMemo, useState, type FormEvent, type ReactNode } from "react";
20
+
21
+ import { useUmClient } from "../../context/auth-context.js";
22
+ import { useCall } from "../../hooks/use-call.js";
23
+ import { errorMessage } from "../../lib/error-message.js";
24
+ import { formatRelative, initialsOf } from "../../lib/utils.js";
25
+ import { EmptyState } from "../primitives/empty-state.js";
26
+ import { StatusBadge, TenantRoleBadge, UserRoleBadge } from "../roles/role-badge.js";
27
+ import { TenantRoleSelect, UserRoleSelect } from "../roles/role-select.js";
28
+ import { Alert, AlertDescription } from "../ui/alert.js";
29
+ import { Avatar, AvatarFallback } from "../ui/avatar.js";
30
+ import { Badge } from "../ui/badge.js";
31
+ import { Button } from "../ui/button.js";
32
+ import {
33
+ Card,
34
+ CardContent,
35
+ CardDescription,
36
+ CardHeader,
37
+ CardTitle,
38
+ } from "../ui/card.js";
39
+ import { Field } from "../ui/field.js";
40
+ import { Input } from "../ui/input.js";
41
+ import {
42
+ Select,
43
+ SelectContent,
44
+ SelectItem,
45
+ SelectTrigger,
46
+ SelectValue,
47
+ } from "../ui/select.js";
48
+ import { Skeleton } from "../ui/skeleton.js";
49
+ import { Table, TableBody, TableCell, TableRow } from "../ui/table.js";
50
+ import { UserDeleteDialog } from "./user-delete-dialog.js";
51
+
52
+ export interface UserDetailViewProps {
53
+ userId: string;
54
+ /** Called after a successful delete — navigate back to the list. */
55
+ onDeleted?: () => void;
56
+ }
57
+
58
+ /**
59
+ * Full-page admin view of one user: profile, status, global role,
60
+ * tenant memberships, and sign-in methods. Superadmin surface — the
61
+ * page hosting it should gate on the role.
62
+ */
63
+ export const UserDetailView = ({ userId, onDeleted }: UserDetailViewProps) => {
64
+ const { data: user, error, loading, refresh } = useCall("adminGetUser", { userId });
65
+
66
+ if (loading) {
67
+ return (
68
+ <div className="grid gap-6">
69
+ <div className="flex items-center gap-4">
70
+ <Skeleton className="size-14 rounded-full" />
71
+ <div className="grid gap-2">
72
+ <Skeleton className="h-5 w-44" />
73
+ <Skeleton className="h-3.5 w-60" />
74
+ </div>
75
+ </div>
76
+ <Skeleton className="h-40 w-full rounded-xl" />
77
+ <Skeleton className="h-40 w-full rounded-xl" />
78
+ </div>
79
+ );
80
+ }
81
+ if (error || !user) {
82
+ return (
83
+ <Alert variant="destructive">
84
+ <AlertCircle />
85
+ <AlertDescription>
86
+ {error ? errorMessage(error) : "User not found."}
87
+ </AlertDescription>
88
+ </Alert>
89
+ );
90
+ }
91
+
92
+ return (
93
+ <div className="grid gap-6">
94
+ <div className="flex flex-wrap items-center gap-4">
95
+ <Avatar className="size-14 text-base">
96
+ <AvatarFallback>{initialsOf(user.name, user.email)}</AvatarFallback>
97
+ </Avatar>
98
+ <div className="grid gap-0.5">
99
+ <div className="flex items-center gap-2">
100
+ <h2 className="text-xl font-semibold">{user.name || user.email}</h2>
101
+ <StatusBadge status={user.status} />
102
+ <UserRoleBadge role={user.role} />
103
+ </div>
104
+ <p className="text-sm text-muted-foreground">
105
+ {user.email} · joined {formatRelative(user.createdAt)}
106
+ </p>
107
+ </div>
108
+ </div>
109
+
110
+ <div className="grid gap-6 lg:grid-cols-2">
111
+ <ProfileCard user={user} onSaved={refresh} />
112
+ <AccessCard user={user} onChanged={refresh} />
113
+ </div>
114
+ <AuthMethodsCard user={user} onChanged={refresh} />
115
+ <TenantsCard userId={user.id} />
116
+ <DangerCard user={user} onDeleted={onDeleted} />
117
+ </div>
118
+ );
119
+ };
120
+
121
+ /* ── profile ─────────────────────────────────────────────────────── */
122
+
123
+ const ProfileCard = ({ user, onSaved }: { user: AdminUserRow; onSaved: () => void }) => {
124
+ const client = useUmClient();
125
+ // Older accounts only carry a display name — seed first from it.
126
+ const [firstName, setFirstName] = useState(user.firstName ?? user.name);
127
+ const [lastName, setLastName] = useState(user.lastName ?? "");
128
+ const [email, setEmail] = useState(user.email);
129
+ const [loading, setLoading] = useState(false);
130
+ const [error, setError] = useState<string | null>(null);
131
+
132
+ const dirty =
133
+ firstName.trim() !== (user.firstName ?? user.name) ||
134
+ lastName.trim() !== (user.lastName ?? "") ||
135
+ email.trim().toLowerCase() !== user.email;
136
+
137
+ const submit = async (e: FormEvent) => {
138
+ e.preventDefault();
139
+ setLoading(true);
140
+ setError(null);
141
+ const res = await client.adminUpdateUser({
142
+ userId: user.id,
143
+ firstName: firstName.trim(),
144
+ lastName: lastName.trim() || undefined,
145
+ email: email.trim().toLowerCase() !== user.email ? email.trim() : undefined,
146
+ });
147
+ setLoading(false);
148
+ if (res.ok) onSaved();
149
+ else setError(errorMessage(res.error, "Couldn't update user."));
150
+ };
151
+
152
+ return (
153
+ <Card>
154
+ <CardHeader>
155
+ <CardTitle>Profile</CardTitle>
156
+ <CardDescription>Name and email. The email stays verified.</CardDescription>
157
+ </CardHeader>
158
+ <CardContent>
159
+ <form onSubmit={submit} className="grid gap-4" noValidate>
160
+ <div className="grid gap-4 sm:grid-cols-2">
161
+ <Field label="First name" htmlFor="detail-first-name" required>
162
+ <Input
163
+ id="detail-first-name"
164
+ required
165
+ value={firstName}
166
+ onChange={(e) => setFirstName(e.target.value)}
167
+ />
168
+ </Field>
169
+ <Field label="Last name" htmlFor="detail-last-name">
170
+ <Input
171
+ id="detail-last-name"
172
+ value={lastName}
173
+ onChange={(e) => setLastName(e.target.value)}
174
+ />
175
+ </Field>
176
+ </div>
177
+ <Field label="Email" htmlFor="detail-email" required>
178
+ <Input
179
+ id="detail-email"
180
+ type="email"
181
+ required
182
+ value={email}
183
+ onChange={(e) => setEmail(e.target.value)}
184
+ />
185
+ </Field>
186
+ {error ? (
187
+ <Alert variant="destructive">
188
+ <AlertCircle />
189
+ <AlertDescription>{error}</AlertDescription>
190
+ </Alert>
191
+ ) : null}
192
+ <div>
193
+ <Button
194
+ type="submit"
195
+ loading={loading}
196
+ disabled={!dirty || !firstName.trim() || !email.trim()}
197
+ >
198
+ Save changes
199
+ </Button>
200
+ </div>
201
+ </form>
202
+ </CardContent>
203
+ </Card>
204
+ );
205
+ };
206
+
207
+ /* ── status + global role ────────────────────────────────────────── */
208
+
209
+ const STATUSES: UserStatus[] = ["active", "inactive", "pending"];
210
+
211
+ const AccessCard = ({ user, onChanged }: { user: AdminUserRow; onChanged: () => void }) => {
212
+ const client = useUmClient();
213
+ const [busy, setBusy] = useState<string | null>(null);
214
+ const [error, setError] = useState<string | null>(null);
215
+
216
+ const run = async (key: string, op: () => Promise<{ ok: boolean; error?: unknown }>) => {
217
+ setBusy(key);
218
+ setError(null);
219
+ const res = await op();
220
+ setBusy(null);
221
+ if (res.ok) onChanged();
222
+ else setError(errorMessage(res.error as never, "Action failed."));
223
+ };
224
+
225
+ const setStatus = (status: UserStatus) =>
226
+ run("status", () => client.adminSetUserStatus({ userId: user.id, status }));
227
+ const setRole = (role: UserRole) =>
228
+ run("role", () => client.adminSetUserRole({ userId: user.id, role }));
229
+ const revoke = () =>
230
+ run("revoke", () => client.adminRevokeUserTokens({ userId: user.id }));
231
+
232
+ // active/inactive → pending is rejected by the server.
233
+ const allowed = STATUSES.filter(
234
+ (s) => s === user.status || s !== "pending" || user.status === "pending"
235
+ );
236
+
237
+ return (
238
+ <Card>
239
+ <CardHeader>
240
+ <CardTitle>Access</CardTitle>
241
+ <CardDescription>
242
+ Status, system role and sessions. Deactivating revokes all sessions.
243
+ </CardDescription>
244
+ </CardHeader>
245
+ <CardContent className="grid gap-4">
246
+ {error ? (
247
+ <Alert variant="destructive">
248
+ <AlertCircle />
249
+ <AlertDescription>{error}</AlertDescription>
250
+ </Alert>
251
+ ) : null}
252
+ <Field label="Status" htmlFor="detail-status">
253
+ <Select
254
+ value={user.status}
255
+ onValueChange={(v) => void setStatus(v as UserStatus)}
256
+ disabled={busy !== null}
257
+ >
258
+ <SelectTrigger id="detail-status" className="h-8 w-[10.5rem]">
259
+ <SelectValue />
260
+ </SelectTrigger>
261
+ <SelectContent>
262
+ {allowed.map((s) => (
263
+ <SelectItem key={s} value={s} className="capitalize">
264
+ {s}
265
+ </SelectItem>
266
+ ))}
267
+ </SelectContent>
268
+ </Select>
269
+ </Field>
270
+ <Field label="System role" htmlFor="detail-role">
271
+ <UserRoleSelect value={user.role} onChange={(r) => void setRole(r)} disabled={busy !== null} />
272
+ </Field>
273
+ <div>
274
+ <Button variant="outline" size="sm" onClick={() => void revoke()} loading={busy === "revoke"}>
275
+ <KeyRound />
276
+ Revoke all sessions
277
+ </Button>
278
+ </div>
279
+ </CardContent>
280
+ </Card>
281
+ );
282
+ };
283
+
284
+ /* ── auth methods ────────────────────────────────────────────────── */
285
+
286
+ const providerLabel = (p: string) => (p === "credential" ? "password" : p);
287
+
288
+ const SOCIAL_AUTH_TYPES = ["google", "microsoft", "github", "discord", "facebook"];
289
+
290
+ const AuthMethodsCard = ({ user, onChanged }: { user: AdminUserRow; onChanged: () => void }) => {
291
+ const client = useUmClient();
292
+ const { data, error, loading, refresh } = useCall("adminAuthMethods", { userId: user.id });
293
+ const [busy, setBusy] = useState<string | null>(null);
294
+ const [actionError, setActionError] = useState<string | null>(null);
295
+ const [notice, setNotice] = useState<string | null>(null);
296
+
297
+ const run = async (key: string, op: () => Promise<{ ok: boolean; error?: unknown }>) => {
298
+ setBusy(key);
299
+ setActionError(null);
300
+ setNotice(null);
301
+ const res = await op();
302
+ setBusy(null);
303
+ if (res.ok) {
304
+ await refresh();
305
+ onChanged();
306
+ } else {
307
+ setActionError(errorMessage(res.error as never, "Action failed."));
308
+ }
309
+ return res.ok;
310
+ };
311
+
312
+ const methodCount = (data?.accounts.length ?? 0) + (data?.passkeys.length ?? 0);
313
+
314
+ return (
315
+ <Card>
316
+ <CardHeader>
317
+ <CardTitle className="flex items-center gap-2">
318
+ <Fingerprint className="size-4 text-muted-foreground" />
319
+ Sign-in methods
320
+ </CardTitle>
321
+ <CardDescription>
322
+ How this user can authenticate. A user always keeps at least one
323
+ method. A social login links for good once the user signs in with
324
+ the provider; until then a pre-link only matches when the provider
325
+ reports the pre-linked email as that user's verified address.
326
+ </CardDescription>
327
+ </CardHeader>
328
+ <CardContent className="grid gap-4">
329
+ {error ? (
330
+ <Alert variant="destructive">
331
+ <AlertCircle />
332
+ <AlertDescription>{errorMessage(error)}</AlertDescription>
333
+ </Alert>
334
+ ) : null}
335
+ {actionError ? (
336
+ <Alert variant="destructive">
337
+ <AlertCircle />
338
+ <AlertDescription>{actionError}</AlertDescription>
339
+ </Alert>
340
+ ) : null}
341
+ {notice ? (
342
+ <Alert variant="success">
343
+ <ShieldCheck />
344
+ <AlertDescription>{notice}</AlertDescription>
345
+ </Alert>
346
+ ) : null}
347
+
348
+ {loading ? (
349
+ <Skeleton className="h-24 w-full rounded-lg" />
350
+ ) : data ? (
351
+ <>
352
+ <PasswordRow
353
+ hasCredential={data.accounts.some((a) => a.providerId === "credential")}
354
+ busy={busy !== null}
355
+ settingBusy={busy === "pw-set"}
356
+ emailBusy={busy === "pw-email"}
357
+ onSet={(password) =>
358
+ void run("pw-set", () =>
359
+ client.adminSetUserPassword({ userId: user.id, password })
360
+ ).then((ok) => {
361
+ if (ok) setNotice("Password updated — the user's sessions were signed out.");
362
+ })
363
+ }
364
+ onSendReset={() =>
365
+ void run("pw-email", () =>
366
+ client.adminSetUserPassword({ userId: user.id, sendResetEmail: true })
367
+ ).then((ok) => {
368
+ if (ok) setNotice(`Reset link emailed to ${user.email}.`);
369
+ })
370
+ }
371
+ />
372
+ <AddMethodRow
373
+ busy={busy !== null}
374
+ onAdd={(authType, value) =>
375
+ void run("add", () =>
376
+ client.adminAddAccount({ userId: user.id, authType, value })
377
+ )
378
+ }
379
+ />
380
+ <div className="overflow-hidden rounded-lg border">
381
+ <Table>
382
+ <TableBody>
383
+ {data.accounts.map((a) => (
384
+ <MethodRow
385
+ key={a.id}
386
+ icon={<KeyRound className="size-4 text-muted-foreground" />}
387
+ label={providerLabel(a.providerId)}
388
+ detail={<AccountDetail account={a} />}
389
+ action={
390
+ <Button
391
+ variant="ghost"
392
+ size="icon"
393
+ aria-label={`Unlink ${providerLabel(a.providerId)}`}
394
+ onClick={() =>
395
+ void run(a.id, () =>
396
+ client.adminUnlinkAccount({ userId: user.id, accountId: a.id })
397
+ )
398
+ }
399
+ loading={busy === a.id}
400
+ disabled={(busy !== null && busy !== a.id) || methodCount <= 1}
401
+ >
402
+ <X className="text-destructive" />
403
+ </Button>
404
+ }
405
+ />
406
+ ))}
407
+ {data.passkeys.map((p) => (
408
+ <MethodRow
409
+ key={p.id}
410
+ icon={<Fingerprint className="size-4 text-muted-foreground" />}
411
+ label={p.name || "passkey"}
412
+ detail={`webauthn · ${p.deviceType}${p.createdAt ? ` · added ${formatRelative(p.createdAt)}` : ""}`}
413
+ action={
414
+ <Button
415
+ variant="ghost"
416
+ size="icon"
417
+ aria-label="Remove passkey"
418
+ onClick={() =>
419
+ void run(p.id, () =>
420
+ client.adminDeletePasskey({ userId: user.id, passkeyId: p.id })
421
+ )
422
+ }
423
+ loading={busy === p.id}
424
+ disabled={(busy !== null && busy !== p.id) || methodCount <= 1}
425
+ >
426
+ <Trash2 className="text-destructive" />
427
+ </Button>
428
+ }
429
+ />
430
+ ))}
431
+ {methodCount === 0 ? (
432
+ <TableRow>
433
+ <TableCell className="p-0">
434
+ <EmptyState
435
+ icon={Fingerprint}
436
+ title="No sign-in methods"
437
+ description="This user can't sign in."
438
+ className="border-0 rounded-none bg-transparent"
439
+ />
440
+ </TableCell>
441
+ </TableRow>
442
+ ) : null}
443
+ </TableBody>
444
+ </Table>
445
+ </div>
446
+
447
+ <div className="flex items-center justify-between rounded-lg border px-4 py-3">
448
+ <div className="flex items-center gap-2 text-sm">
449
+ <ShieldCheck className="size-4 text-muted-foreground" />
450
+ Two-factor authentication
451
+ <Badge variant={data.twoFactorEnabled ? "default" : "outline"}>
452
+ {data.twoFactorEnabled ? "enabled" : "off"}
453
+ </Badge>
454
+ </div>
455
+ {data.twoFactorEnabled ? (
456
+ <Button
457
+ variant="outline"
458
+ size="sm"
459
+ onClick={() =>
460
+ void run("2fa", () =>
461
+ client.adminDisableTwoFactor({ userId: user.id })
462
+ )
463
+ }
464
+ loading={busy === "2fa"}
465
+ >
466
+ Disable 2FA
467
+ </Button>
468
+ ) : null}
469
+ </div>
470
+ </>
471
+ ) : null}
472
+ </CardContent>
473
+ </Card>
474
+ );
475
+ };
476
+
477
+ /**
478
+ * Password management: set (or overwrite) the user's password
479
+ * directly, or email them a reset link. The emailed token also works
480
+ * for accounts with no password yet — consuming it creates the
481
+ * credential — so both actions are always available.
482
+ */
483
+ const PasswordRow = ({
484
+ hasCredential,
485
+ busy,
486
+ settingBusy,
487
+ emailBusy,
488
+ onSet,
489
+ onSendReset,
490
+ }: {
491
+ hasCredential: boolean;
492
+ busy: boolean;
493
+ settingBusy: boolean;
494
+ emailBusy: boolean;
495
+ onSet: (password: string) => void;
496
+ onSendReset: () => void;
497
+ }) => {
498
+ const [password, setPassword] = useState("");
499
+
500
+ const submit = (e: FormEvent) => {
501
+ e.preventDefault();
502
+ if (password.length < 8) return;
503
+ onSet(password);
504
+ setPassword("");
505
+ };
506
+
507
+ return (
508
+ <form
509
+ onSubmit={submit}
510
+ className="grid items-end gap-3 rounded-lg border px-4 py-3 sm:grid-cols-[1fr_auto_auto]"
511
+ >
512
+ <Field
513
+ label={hasCredential ? "Reset password" : "Set password"}
514
+ htmlFor="admin-set-password"
515
+ description={
516
+ hasCredential
517
+ ? "Replaces the current password and signs the user out everywhere."
518
+ : "This account has no password yet."
519
+ }
520
+ >
521
+ <Input
522
+ id="admin-set-password"
523
+ type="password"
524
+ value={password}
525
+ onChange={(e) => setPassword(e.target.value)}
526
+ placeholder="At least 8 characters"
527
+ autoComplete="new-password"
528
+ />
529
+ </Field>
530
+ <Button type="submit" size="sm" disabled={password.length < 8 || busy} loading={settingBusy}>
531
+ <KeyRound />
532
+ {hasCredential ? "Reset" : "Set"}
533
+ </Button>
534
+ <Button
535
+ type="button"
536
+ variant="outline"
537
+ size="sm"
538
+ onClick={onSendReset}
539
+ disabled={busy}
540
+ loading={emailBusy}
541
+ >
542
+ <Mail />
543
+ Email reset link
544
+ </Button>
545
+ </form>
546
+ );
547
+ };
548
+
549
+ /**
550
+ * `{authType, value}` entry row for social pre-links: the value is the
551
+ * provider handle (GitHub/Discord username), the provider-side account
552
+ * id, or an email (the user's first sign-in with that provider lands on
553
+ * this account). Passwords are managed by `PasswordRow` above.
554
+ */
555
+ const AddMethodRow = ({
556
+ busy,
557
+ onAdd,
558
+ }: {
559
+ busy: boolean;
560
+ onAdd: (authType: string, value: string) => void;
561
+ }) => {
562
+ const [authType, setAuthType] = useState("");
563
+ const [value, setValue] = useState("");
564
+
565
+ const submit = (e: FormEvent) => {
566
+ e.preventDefault();
567
+ if (!authType || !value.trim()) return;
568
+ onAdd(authType, value.trim());
569
+ setAuthType("");
570
+ setValue("");
571
+ };
572
+
573
+ return (
574
+ <form
575
+ onSubmit={submit}
576
+ className="grid items-end gap-3 rounded-lg border border-dashed bg-muted/30 p-3 sm:grid-cols-[auto_1fr_auto]"
577
+ >
578
+ <Field label="Pre-link provider" htmlFor="add-method-type">
579
+ <Select value={authType} onValueChange={setAuthType}>
580
+ <SelectTrigger id="add-method-type" className="h-8 w-[10.5rem]">
581
+ <SelectValue placeholder="Provider…" />
582
+ </SelectTrigger>
583
+ <SelectContent>
584
+ {SOCIAL_AUTH_TYPES.map((t) => (
585
+ <SelectItem key={t} value={t} className="capitalize">
586
+ {providerLabel(t)}
587
+ </SelectItem>
588
+ ))}
589
+ </SelectContent>
590
+ </Select>
591
+ </Field>
592
+ <Field label="Username, account id or email" htmlFor="add-method-value">
593
+ <Input
594
+ id="add-method-value"
595
+ type="text"
596
+ value={value}
597
+ onChange={(e) => setValue(e.target.value)}
598
+ placeholder="octocat or user@gmail.com"
599
+ autoComplete="off"
600
+ />
601
+ </Field>
602
+ <Button type="submit" size="sm" disabled={!authType || !value.trim() || busy}>
603
+ <Plus />
604
+ Add
605
+ </Button>
606
+ </form>
607
+ );
608
+ };
609
+
610
+ /**
611
+ * Whether a social row already holds the provider's own subject id —
612
+ * numeric for GitHub/Google/Discord/Facebook, a GUID for Microsoft —
613
+ * or still an admin-typed pre-link (a handle or an email) waiting for
614
+ * the user's first sign-in to re-key it.
615
+ */
616
+ const isProviderSubject = (providerId: string, accountId: string) =>
617
+ providerId === "microsoft"
618
+ ? /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(accountId)
619
+ : /^\d+$/.test(accountId);
620
+
621
+ /**
622
+ * What a social row is keyed on. A real login stores the IdP subject
623
+ * (GitHub's numeric id, Google's `sub`); an admin pre-link stores the
624
+ * handle or email typed in, which resolves on the user's first sign-in
625
+ * when the provider reports that handle, or that email as verified.
626
+ */
627
+ const AccountDetail = ({ account }: { account: AuthAccount }) => {
628
+ const added = `added ${formatRelative(account.createdAt)}`;
629
+ if (!account.accountId) return <>{added}</>;
630
+ const linked = isProviderSubject(account.providerId, account.accountId);
631
+ return (
632
+ <span className="inline-flex flex-wrap items-center gap-x-2 gap-y-1">
633
+ <code
634
+ className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs text-foreground"
635
+ title={linked ? "Provider account id" : "Pre-linked on this handle or email"}
636
+ >
637
+ {account.accountId}
638
+ </code>
639
+ {linked ? (
640
+ <Badge variant="success">linked</Badge>
641
+ ) : (
642
+ <Badge variant="muted">pre-link · awaiting first sign-in</Badge>
643
+ )}
644
+ <span>{added}</span>
645
+ </span>
646
+ );
647
+ };
648
+
649
+ const MethodRow = ({
650
+ icon,
651
+ label,
652
+ detail,
653
+ action,
654
+ }: {
655
+ icon: ReactNode;
656
+ label: string;
657
+ detail: ReactNode;
658
+ action: ReactNode;
659
+ }) => (
660
+ <TableRow>
661
+ <TableCell>
662
+ <div className="flex items-center gap-2">
663
+ {icon}
664
+ <span className="text-sm font-medium capitalize">{label}</span>
665
+ </div>
666
+ </TableCell>
667
+ <TableCell className="text-sm text-muted-foreground">{detail}</TableCell>
668
+ <TableCell className="text-right">{action}</TableCell>
669
+ </TableRow>
670
+ );
671
+
672
+ /* ── tenants ─────────────────────────────────────────────────────── */
673
+
674
+ const TenantsCard = ({ userId }: { userId: string }) => {
675
+ const client = useUmClient();
676
+ const memberships = useCall("adminListUserTenants", { userId });
677
+ const tenants = useCall("adminListTenants");
678
+ const [orgId, setOrgId] = useState("");
679
+ const [role, setRole] = useState<TenantRole>("member");
680
+ const [busy, setBusy] = useState<string | null>(null);
681
+ const [error, setError] = useState<string | null>(null);
682
+
683
+ const memberOf = new Set(
684
+ (memberships.data?.memberships ?? []).map((m) => m.organizationId)
685
+ );
686
+ const assignable = useMemo(
687
+ () => (tenants.data?.tenants ?? []).filter((t) => !memberOf.has(t.id)),
688
+ [tenants.data, memberships.data]
689
+ );
690
+
691
+ const assign = async () => {
692
+ if (!orgId) return;
693
+ setBusy("assign");
694
+ setError(null);
695
+ const res = await client.addMember({ organizationId: orgId, userId, role });
696
+ setBusy(null);
697
+ if (res.ok) {
698
+ setOrgId("");
699
+ setRole("member");
700
+ await memberships.refresh();
701
+ } else {
702
+ setError(errorMessage(res.error, "Couldn't assign tenant."));
703
+ }
704
+ };
705
+
706
+ const remove = async (memberId: string, organizationId: string) => {
707
+ setBusy(memberId);
708
+ setError(null);
709
+ const res = await client.removeMember({ memberId, organizationId });
710
+ setBusy(null);
711
+ if (res.ok) await memberships.refresh();
712
+ else setError(errorMessage(res.error, "Couldn't remove from tenant."));
713
+ };
714
+
715
+ const rows = memberships.data?.memberships ?? [];
716
+
717
+ return (
718
+ <Card>
719
+ <CardHeader>
720
+ <CardTitle className="flex items-center gap-2">
721
+ <Building2 className="size-4 text-muted-foreground" />
722
+ Tenants
723
+ </CardTitle>
724
+ <CardDescription>Memberships and tenant-level roles.</CardDescription>
725
+ </CardHeader>
726
+ <CardContent className="grid gap-4">
727
+ {error ? (
728
+ <Alert variant="destructive">
729
+ <AlertCircle />
730
+ <AlertDescription>{error}</AlertDescription>
731
+ </Alert>
732
+ ) : null}
733
+
734
+ <div className="grid items-end gap-3 rounded-lg border border-dashed bg-muted/30 p-3 sm:grid-cols-[1fr_auto_auto]">
735
+ <Select value={orgId} onValueChange={setOrgId}>
736
+ <SelectTrigger className="h-8">
737
+ <SelectValue placeholder="Pick a tenant…" />
738
+ </SelectTrigger>
739
+ <SelectContent>
740
+ {assignable.map((t) => (
741
+ <SelectItem key={t.id} value={t.id}>
742
+ {t.name}
743
+ </SelectItem>
744
+ ))}
745
+ </SelectContent>
746
+ </Select>
747
+ <TenantRoleSelect value={role} onChange={setRole} />
748
+ <Button
749
+ size="sm"
750
+ onClick={() => void assign()}
751
+ loading={busy === "assign"}
752
+ disabled={!orgId || busy !== null}
753
+ >
754
+ <Plus />
755
+ Assign
756
+ </Button>
757
+ </div>
758
+
759
+ <div className="overflow-hidden rounded-lg border">
760
+ <Table>
761
+ <TableBody>
762
+ {memberships.loading ? (
763
+ <TableRow>
764
+ <TableCell><Skeleton className="h-5 w-40" /></TableCell>
765
+ </TableRow>
766
+ ) : rows.length === 0 ? (
767
+ <TableRow>
768
+ <TableCell className="p-0">
769
+ <EmptyState
770
+ icon={Building2}
771
+ title="No tenants"
772
+ description="This user isn't a member of any tenant yet."
773
+ className="border-0 rounded-none bg-transparent"
774
+ />
775
+ </TableCell>
776
+ </TableRow>
777
+ ) : (
778
+ rows.map((m) => (
779
+ <TableRow key={m.memberId}>
780
+ <TableCell>
781
+ <div className="flex items-center gap-2">
782
+ <Building2 className="size-4 text-muted-foreground" />
783
+ <span className="text-sm font-medium">{m.organizationName}</span>
784
+ </div>
785
+ </TableCell>
786
+ <TableCell>
787
+ <TenantRoleBadge role={m.role} />
788
+ </TableCell>
789
+ <TableCell className="text-sm text-muted-foreground">
790
+ joined {formatRelative(m.createdAt)}
791
+ </TableCell>
792
+ <TableCell className="text-right">
793
+ <Button
794
+ variant="ghost"
795
+ size="icon"
796
+ onClick={() => void remove(m.memberId, m.organizationId)}
797
+ loading={busy === m.memberId}
798
+ disabled={busy !== null && busy !== m.memberId}
799
+ aria-label={`Remove from ${m.organizationName}`}
800
+ >
801
+ <Trash2 className="text-destructive" />
802
+ </Button>
803
+ </TableCell>
804
+ </TableRow>
805
+ ))
806
+ )}
807
+ </TableBody>
808
+ </Table>
809
+ </div>
810
+ </CardContent>
811
+ </Card>
812
+ );
813
+ };
814
+
815
+ /* ── danger zone ─────────────────────────────────────────────────── */
816
+
817
+ const DangerCard = ({ user, onDeleted }: { user: AdminUserRow; onDeleted?: () => void }) => {
818
+ const [confirming, setConfirming] = useState(false);
819
+ return (
820
+ <Card className="border-destructive/40">
821
+ <CardHeader>
822
+ <CardTitle className="text-destructive">Danger zone</CardTitle>
823
+ <CardDescription>
824
+ Soft-deletes the account and revokes every session. The record is
825
+ kept for audit.
826
+ </CardDescription>
827
+ </CardHeader>
828
+ <CardContent>
829
+ <Button variant="destructive" onClick={() => setConfirming(true)}>
830
+ <Trash2 />
831
+ Delete user
832
+ </Button>
833
+ <UserDeleteDialog
834
+ user={confirming ? user : null}
835
+ onOpenChange={(open) => {
836
+ if (!open) setConfirming(false);
837
+ }}
838
+ onDeleted={onDeleted}
839
+ />
840
+ </CardContent>
841
+ </Card>
842
+ );
843
+ };