@nexys/user-management-web 0.3.1

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