@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,504 @@
1
+ import {
2
+ getProviders,
3
+ isConsentChallenge,
4
+ isTwoFactorChallenge,
5
+ passkeySignInFinish,
6
+ passkeySignInStart,
7
+ requestMagicLink,
8
+ signIn,
9
+ socialSignIn,
10
+ verifyBackupCode,
11
+ verifyTotp,
12
+ } from "@nexys/user-management-client";
13
+ import { AlertCircle, Fingerprint, Mail, MailCheck, ShieldCheck, Wand2 } from "lucide-react";
14
+ import { useEffect, useState, type FormEvent, type ReactNode } from "react";
15
+
16
+ import { useUmClient } from "../../context/auth-context.js";
17
+ import { errorMessage } from "../../lib/error-message.js";
18
+ import {
19
+ getPasskeyAssertion,
20
+ webauthnErrorMessage,
21
+ webauthnSupported,
22
+ } from "../../lib/webauthn.js";
23
+ import { Alert, AlertDescription } from "../ui/alert.js";
24
+ import { Button } from "../ui/button.js";
25
+ import {
26
+ Card,
27
+ CardContent,
28
+ CardDescription,
29
+ CardHeader,
30
+ CardTitle,
31
+ } from "../ui/card.js";
32
+ import { Field } from "../ui/field.js";
33
+ import { Input } from "../ui/input.js";
34
+ import { Separator } from "../ui/separator.js";
35
+
36
+ const providerLabel: Record<string, string> = {
37
+ google: "Google",
38
+ github: "GitHub",
39
+ microsoft: "Microsoft",
40
+ discord: "Discord",
41
+ facebook: "Facebook",
42
+ };
43
+
44
+ const ProviderIcon = ({ provider }: { provider: string }) => {
45
+ switch (provider) {
46
+ case "google":
47
+ return (
48
+ <svg className="size-4" viewBox="0 0 24 24">
49
+ <path
50
+ fill="currentColor"
51
+ d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z"
52
+ />
53
+ <path
54
+ fill="currentColor"
55
+ d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
56
+ />
57
+ <path
58
+ fill="currentColor"
59
+ d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
60
+ />
61
+ <path
62
+ fill="currentColor"
63
+ d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
64
+ />
65
+ </svg>
66
+ );
67
+ case "github":
68
+ return (
69
+ <svg className="size-4" viewBox="0 0 24 24" fill="currentColor">
70
+ <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" />
71
+ </svg>
72
+ );
73
+ default:
74
+ return null;
75
+ }
76
+ };
77
+
78
+ export interface SignInFormProps {
79
+ onSuccess?: (user: { id: string; email: string }) => void;
80
+ forgotPasswordSlot?: ReactNode;
81
+ signUpSlot?: ReactNode;
82
+ title?: ReactNode;
83
+ description?: ReactNode;
84
+ }
85
+
86
+ export const SignInForm = ({
87
+ onSuccess,
88
+ forgotPasswordSlot,
89
+ signUpSlot,
90
+ title = "Welcome back",
91
+ description = "Sign in to your account to continue.",
92
+ }: SignInFormProps) => {
93
+ const client = useUmClient();
94
+ const [email, setEmail] = useState("");
95
+ const [password, setPassword] = useState("");
96
+ const [loading, setLoading] = useState(false);
97
+ const [error, setError] = useState<string | null>(null);
98
+ const [providers, setProviders] = useState<string[]>([]);
99
+ const [socialLoading, setSocialLoading] = useState<string | null>(null);
100
+ const [passkeyLoading, setPasskeyLoading] = useState(false);
101
+ // Non-null once a password sign-in came back `twoFactorRequired` —
102
+ // the form switches to the one-time-code step.
103
+ const [challengeToken, setChallengeToken] = useState<string | null>(null);
104
+ const [otp, setOtp] = useState("");
105
+ const [useBackupCode, setUseBackupCode] = useState(false);
106
+ // Magic-link flow: "form" is the email-only step, "sent" the
107
+ // check-your-inbox confirmation.
108
+ const [magicStep, setMagicStep] = useState<"off" | "form" | "sent">("off");
109
+
110
+ useEffect(() => {
111
+ client.call(getProviders).then((res) => {
112
+ if (res.ok) setProviders(res.data.providers);
113
+ });
114
+ }, [client]);
115
+
116
+ const submit = async (e: FormEvent) => {
117
+ e.preventDefault();
118
+ setLoading(true);
119
+ setError(null);
120
+ const res = await client.call(signIn, { email: email.trim(), password });
121
+ setLoading(false);
122
+ if (res.ok) {
123
+ if (isTwoFactorChallenge(res.data)) {
124
+ setChallengeToken(res.data.twoFactorToken);
125
+ } else if (isConsentChallenge(res.data)) {
126
+ // A blocking agreement is outstanding, so no session was issued.
127
+ // The console isn't the place to accept product terms — point the
128
+ // user at the app that asked for them.
129
+ setError(
130
+ `You need to accept "${res.data.documents[0]?.title ?? "an agreement"}" before signing in.`
131
+ );
132
+ } else {
133
+ onSuccess?.({ id: res.data.user.id, email: res.data.user.email });
134
+ }
135
+ } else {
136
+ setError(errorMessage(res.error, "Sign-in failed. Please try again."));
137
+ }
138
+ };
139
+
140
+ const submitOtp = async (e: FormEvent) => {
141
+ e.preventDefault();
142
+ if (!challengeToken) return;
143
+ setLoading(true);
144
+ setError(null);
145
+ const endpoint = useBackupCode ? verifyBackupCode : verifyTotp;
146
+ const res = await client.call(endpoint, {
147
+ token: challengeToken,
148
+ code: otp.trim(),
149
+ });
150
+ setLoading(false);
151
+ if (res.ok) {
152
+ onSuccess?.({ id: res.data.user.id, email: res.data.user.email });
153
+ } else {
154
+ setError(errorMessage(res.error, "That code didn't match — try again."));
155
+ }
156
+ };
157
+
158
+ const handleSocial = async (provider: string) => {
159
+ setSocialLoading(provider);
160
+ setError(null);
161
+ const callbackURL = window.location.origin + "/";
162
+ const res = await client.call(socialSignIn, { provider, callbackURL });
163
+ if (res.ok) {
164
+ window.location.href = res.data.url;
165
+ } else {
166
+ setSocialLoading(null);
167
+ setError(errorMessage(res.error, `Sign-in with ${providerLabel[provider] ?? provider} failed.`));
168
+ }
169
+ };
170
+
171
+ const handlePasskey = async () => {
172
+ setPasskeyLoading(true);
173
+ setError(null);
174
+ try {
175
+ const start = await client.call(passkeySignInStart, {
176
+ email: email.trim() || undefined,
177
+ });
178
+ if (!start.ok) {
179
+ setError(errorMessage(start.error, "Couldn't start passkey sign-in."));
180
+ return;
181
+ }
182
+ const assertion = await getPasskeyAssertion(start.data.options);
183
+ const finish = await client.call(passkeySignInFinish, {
184
+ challenge: start.data.challenge,
185
+ response: assertion,
186
+ });
187
+ if (finish.ok) {
188
+ if (isConsentChallenge(finish.data)) {
189
+ // Same gate as password sign-in — no session was issued.
190
+ setError(
191
+ `You need to accept "${finish.data.documents[0]?.title ?? "an agreement"}" before signing in.`
192
+ );
193
+ } else {
194
+ onSuccess?.({ id: finish.data.user.id, email: finish.data.user.email });
195
+ }
196
+ } else {
197
+ setError(errorMessage(finish.error, "Passkey sign-in failed."));
198
+ }
199
+ } catch (err) {
200
+ // The browser throws when the user dismisses the platform dialog.
201
+ setError(webauthnErrorMessage(err, "Passkey sign-in failed."));
202
+ } finally {
203
+ setPasskeyLoading(false);
204
+ }
205
+ };
206
+
207
+ const submitMagicLink = async (e: FormEvent) => {
208
+ e.preventDefault();
209
+ setLoading(true);
210
+ setError(null);
211
+ const res = await client.call(requestMagicLink, { email: email.trim() });
212
+ setLoading(false);
213
+ if (res.ok) {
214
+ setMagicStep("sent");
215
+ } else {
216
+ setError(errorMessage(res.error, "Couldn't send the sign-in link."));
217
+ }
218
+ };
219
+
220
+ // ── Magic-link steps ──────────────────────────────────────────────
221
+ if (magicStep === "sent") {
222
+ return (
223
+ <Card className="w-full max-w-md">
224
+ <CardHeader className="space-y-1.5">
225
+ <CardTitle className="flex items-center gap-2 text-2xl">
226
+ <MailCheck className="size-5 text-muted-foreground" />
227
+ Check your inbox
228
+ </CardTitle>
229
+ <CardDescription>
230
+ If an account exists for <span className="font-medium">{email.trim()}</span>,
231
+ a sign-in link is on its way. It expires in 15 minutes and works once.
232
+ </CardDescription>
233
+ </CardHeader>
234
+ <CardContent>
235
+ <Button
236
+ type="button"
237
+ variant="outline"
238
+ className="w-full"
239
+ onClick={() => {
240
+ setMagicStep("off");
241
+ setError(null);
242
+ }}
243
+ >
244
+ Back to sign-in
245
+ </Button>
246
+ </CardContent>
247
+ </Card>
248
+ );
249
+ }
250
+
251
+ if (magicStep === "form") {
252
+ return (
253
+ <Card className="w-full max-w-md">
254
+ <CardHeader className="space-y-1.5">
255
+ <CardTitle className="flex items-center gap-2 text-2xl">
256
+ <Wand2 className="size-5 text-muted-foreground" />
257
+ Email me a sign-in link
258
+ </CardTitle>
259
+ <CardDescription>
260
+ No password needed — we&apos;ll send a one-time link to your inbox.
261
+ </CardDescription>
262
+ </CardHeader>
263
+ <CardContent>
264
+ <form onSubmit={submitMagicLink} className="grid gap-4" noValidate>
265
+ <Field label="Email" htmlFor="magic-email" required>
266
+ <div className="relative">
267
+ <Mail
268
+ className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
269
+ aria-hidden
270
+ />
271
+ <Input
272
+ id="magic-email"
273
+ type="email"
274
+ autoComplete="email"
275
+ autoFocus
276
+ required
277
+ value={email}
278
+ onChange={(e) => setEmail(e.target.value)}
279
+ className="pl-9"
280
+ placeholder="you@example.com"
281
+ />
282
+ </div>
283
+ </Field>
284
+ {error ? (
285
+ <Alert variant="destructive">
286
+ <AlertCircle />
287
+ <AlertDescription>{error}</AlertDescription>
288
+ </Alert>
289
+ ) : null}
290
+ <Button
291
+ type="submit"
292
+ className="w-full"
293
+ loading={loading}
294
+ disabled={!email.trim()}
295
+ >
296
+ Send sign-in link
297
+ </Button>
298
+ <button
299
+ type="button"
300
+ className="text-center text-sm text-muted-foreground underline-offset-4 hover:underline"
301
+ onClick={() => {
302
+ setMagicStep("off");
303
+ setError(null);
304
+ }}
305
+ >
306
+ Back to sign-in
307
+ </button>
308
+ </form>
309
+ </CardContent>
310
+ </Card>
311
+ );
312
+ }
313
+
314
+ // ── 2FA challenge step ────────────────────────────────────────────
315
+ if (challengeToken) {
316
+ return (
317
+ <Card className="w-full max-w-md">
318
+ <CardHeader className="space-y-1.5">
319
+ <CardTitle className="flex items-center gap-2 text-2xl">
320
+ <ShieldCheck className="size-5 text-muted-foreground" />
321
+ Two-factor check
322
+ </CardTitle>
323
+ <CardDescription>
324
+ {useBackupCode
325
+ ? "Enter one of your single-use backup codes."
326
+ : "Enter the 6-digit code from your authenticator app."}
327
+ </CardDescription>
328
+ </CardHeader>
329
+ <CardContent>
330
+ <form onSubmit={submitOtp} className="grid gap-4" noValidate>
331
+ <Field
332
+ label={useBackupCode ? "Backup code" : "Verification code"}
333
+ htmlFor="otp"
334
+ required
335
+ >
336
+ <Input
337
+ id="otp"
338
+ inputMode={useBackupCode ? "text" : "numeric"}
339
+ autoComplete="one-time-code"
340
+ autoFocus
341
+ required
342
+ placeholder={useBackupCode ? "XXXX-XXXX" : "123456"}
343
+ value={otp}
344
+ onChange={(e) => setOtp(e.target.value)}
345
+ className="font-mono"
346
+ />
347
+ </Field>
348
+ {error ? (
349
+ <Alert variant="destructive">
350
+ <AlertCircle />
351
+ <AlertDescription>{error}</AlertDescription>
352
+ </Alert>
353
+ ) : null}
354
+ <Button type="submit" className="w-full" loading={loading}>
355
+ Verify
356
+ </Button>
357
+ <div className="flex items-center justify-between text-sm">
358
+ <button
359
+ type="button"
360
+ className="text-muted-foreground underline-offset-4 hover:underline"
361
+ onClick={() => {
362
+ setUseBackupCode((v) => !v);
363
+ setOtp("");
364
+ setError(null);
365
+ }}
366
+ >
367
+ {useBackupCode ? "Use authenticator code" : "Use a backup code"}
368
+ </button>
369
+ <button
370
+ type="button"
371
+ className="text-muted-foreground underline-offset-4 hover:underline"
372
+ onClick={() => {
373
+ setChallengeToken(null);
374
+ setOtp("");
375
+ setError(null);
376
+ }}
377
+ >
378
+ Back to sign-in
379
+ </button>
380
+ </div>
381
+ </form>
382
+ </CardContent>
383
+ </Card>
384
+ );
385
+ }
386
+
387
+ return (
388
+ <Card className="w-full max-w-md">
389
+ <CardHeader className="space-y-1.5">
390
+ <CardTitle className="text-2xl">{title}</CardTitle>
391
+ {description ? <CardDescription>{description}</CardDescription> : null}
392
+ </CardHeader>
393
+ <CardContent>
394
+ <div className="grid gap-4">
395
+ {providers.length > 0 && (
396
+ <>
397
+ <div className="grid gap-2">
398
+ {providers.map((p) => (
399
+ <Button
400
+ key={p}
401
+ type="button"
402
+ variant="outline"
403
+ className="w-full"
404
+ loading={socialLoading === p}
405
+ disabled={!!socialLoading || loading}
406
+ onClick={() => handleSocial(p)}
407
+ >
408
+ <ProviderIcon provider={p} />
409
+ Continue with {providerLabel[p] ?? p}
410
+ </Button>
411
+ ))}
412
+ </div>
413
+ <div className="relative">
414
+ <div className="absolute inset-0 flex items-center">
415
+ <Separator className="w-full" />
416
+ </div>
417
+ <div className="relative flex justify-center text-xs uppercase">
418
+ <span className="bg-card px-2 text-muted-foreground">or</span>
419
+ </div>
420
+ </div>
421
+ </>
422
+ )}
423
+ <form onSubmit={submit} className="grid gap-4" noValidate>
424
+ <Field label="Email" htmlFor="email" required>
425
+ <div className="relative">
426
+ <Mail
427
+ className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
428
+ aria-hidden
429
+ />
430
+ <Input
431
+ id="email"
432
+ type="email"
433
+ autoComplete="email"
434
+ required
435
+ value={email}
436
+ onChange={(e) => setEmail(e.target.value)}
437
+ className="pl-9"
438
+ placeholder="you@example.com"
439
+ />
440
+ </div>
441
+ </Field>
442
+ <Field
443
+ label={
444
+ <span className="flex w-full items-center justify-between">
445
+ <span>Password</span>
446
+ {forgotPasswordSlot}
447
+ </span>
448
+ }
449
+ htmlFor="password"
450
+ required
451
+ >
452
+ <Input
453
+ id="password"
454
+ type="password"
455
+ autoComplete="current-password"
456
+ required
457
+ value={password}
458
+ onChange={(e) => setPassword(e.target.value)}
459
+ />
460
+ </Field>
461
+ {error ? (
462
+ <Alert variant="destructive">
463
+ <AlertCircle />
464
+ <AlertDescription>{error}</AlertDescription>
465
+ </Alert>
466
+ ) : null}
467
+ <Button type="submit" className="w-full" loading={loading}>
468
+ {loading ? "Signing in…" : "Sign in"}
469
+ </Button>
470
+ {webauthnSupported() ? (
471
+ <Button
472
+ type="button"
473
+ variant="outline"
474
+ className="w-full"
475
+ loading={passkeyLoading}
476
+ disabled={loading || !!socialLoading}
477
+ onClick={handlePasskey}
478
+ >
479
+ <Fingerprint />
480
+ Sign in with a passkey
481
+ </Button>
482
+ ) : null}
483
+ <Button
484
+ type="button"
485
+ variant="outline"
486
+ className="w-full"
487
+ disabled={loading || !!socialLoading || passkeyLoading}
488
+ onClick={() => {
489
+ setMagicStep("form");
490
+ setError(null);
491
+ }}
492
+ >
493
+ <Wand2 />
494
+ Email me a sign-in link
495
+ </Button>
496
+ {signUpSlot ? (
497
+ <p className="text-center text-sm text-muted-foreground">{signUpSlot}</p>
498
+ ) : null}
499
+ </form>
500
+ </div>
501
+ </CardContent>
502
+ </Card>
503
+ );
504
+ };
@@ -0,0 +1,124 @@
1
+ import { signUp } from "@nexys/user-management-client";
2
+ import { AlertCircle } from "lucide-react";
3
+ import { useState, type FormEvent, type ReactNode } from "react";
4
+
5
+ import { useUmClient } from "../../context/auth-context.js";
6
+ import { errorMessage } from "../../lib/error-message.js";
7
+ import { Alert, AlertDescription } from "../ui/alert.js";
8
+ import { Button } from "../ui/button.js";
9
+ import {
10
+ Card,
11
+ CardContent,
12
+ CardDescription,
13
+ CardHeader,
14
+ CardTitle,
15
+ } from "../ui/card.js";
16
+ import { Field } from "../ui/field.js";
17
+ import { Input } from "../ui/input.js";
18
+
19
+ export interface SignUpFormProps {
20
+ onSuccess?: (user: { id: string; email: string }) => void;
21
+ signInSlot?: ReactNode;
22
+ title?: ReactNode;
23
+ description?: ReactNode;
24
+ /** Server enforces ≥8 chars; this is the client-side hint. */
25
+ minPasswordLength?: number;
26
+ }
27
+
28
+ export const SignUpForm = ({
29
+ onSuccess,
30
+ signInSlot,
31
+ title = "Create your account",
32
+ description = "Just a few details to get started.",
33
+ minPasswordLength = 8,
34
+ }: SignUpFormProps) => {
35
+ const client = useUmClient();
36
+ const [name, setName] = useState("");
37
+ const [email, setEmail] = useState("");
38
+ const [password, setPassword] = useState("");
39
+ const [loading, setLoading] = useState(false);
40
+ const [error, setError] = useState<string | null>(null);
41
+
42
+ const tooShort = password.length > 0 && password.length < minPasswordLength;
43
+
44
+ const submit = async (e: FormEvent) => {
45
+ e.preventDefault();
46
+ if (tooShort) return;
47
+ setLoading(true);
48
+ setError(null);
49
+ const res = await client.call(signUp, {
50
+ name: name.trim(),
51
+ email: email.trim(),
52
+ password,
53
+ });
54
+ setLoading(false);
55
+ if (res.ok) {
56
+ onSuccess?.({ id: res.data.user.id, email: res.data.user.email });
57
+ } else {
58
+ setError(errorMessage(res.error, "Sign-up failed. Please try again."));
59
+ }
60
+ };
61
+
62
+ return (
63
+ <Card className="w-full max-w-md">
64
+ <CardHeader className="space-y-1.5">
65
+ <CardTitle className="text-2xl">{title}</CardTitle>
66
+ {description ? <CardDescription>{description}</CardDescription> : null}
67
+ </CardHeader>
68
+ <CardContent>
69
+ <form onSubmit={submit} className="grid gap-4" noValidate>
70
+ <Field label="Name" htmlFor="name" required>
71
+ <Input
72
+ id="name"
73
+ autoComplete="name"
74
+ required
75
+ value={name}
76
+ onChange={(e) => setName(e.target.value)}
77
+ placeholder="Ada Lovelace"
78
+ />
79
+ </Field>
80
+ <Field label="Email" htmlFor="email" required>
81
+ <Input
82
+ id="email"
83
+ type="email"
84
+ autoComplete="email"
85
+ required
86
+ value={email}
87
+ onChange={(e) => setEmail(e.target.value)}
88
+ placeholder="you@example.com"
89
+ />
90
+ </Field>
91
+ <Field
92
+ label="Password"
93
+ htmlFor="password"
94
+ required
95
+ description={`At least ${minPasswordLength} characters.`}
96
+ error={tooShort ? `Password must be at least ${minPasswordLength} characters.` : undefined}
97
+ >
98
+ <Input
99
+ id="password"
100
+ type="password"
101
+ autoComplete="new-password"
102
+ required
103
+ value={password}
104
+ onChange={(e) => setPassword(e.target.value)}
105
+ aria-invalid={tooShort || undefined}
106
+ />
107
+ </Field>
108
+ {error ? (
109
+ <Alert variant="destructive">
110
+ <AlertCircle />
111
+ <AlertDescription>{error}</AlertDescription>
112
+ </Alert>
113
+ ) : null}
114
+ <Button type="submit" className="w-full" loading={loading} disabled={tooShort}>
115
+ {loading ? "Creating account…" : "Create account"}
116
+ </Button>
117
+ {signInSlot ? (
118
+ <p className="text-center text-sm text-muted-foreground">{signInSlot}</p>
119
+ ) : null}
120
+ </form>
121
+ </CardContent>
122
+ </Card>
123
+ );
124
+ };