-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample_auth_form.tsx
More file actions
278 lines (262 loc) · 10.2 KB
/
example_auth_form.tsx
File metadata and controls
278 lines (262 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import type { AuthError } from "@supabase/supabase-js";
import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { toast } from "sonner";
import { CheckCircle2, Loader2, AlertTriangle, X } from "lucide-react";
import { authSchema } from "@/schemas/auth.schema";
import { z } from "zod";
export const Auth = () => {
const [isSignUp, setIsSignUp] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const [validationSuggestion, setValidationSuggestion] = useState<string | null>(null);
const navigate = useNavigate();
useEffect(() => {
const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => {
if (session) {
navigate("/");
}
});
supabase.auth.getSession().then(({ data: { session } }) => {
if (session) {
navigate("/");
}
});
return () => subscription.unsubscribe();
}, [navigate]);
const getErrorMessage = (e: unknown): string => {
if (e instanceof Error) return e.message;
if (
typeof e === "object" &&
e !== null &&
"message" in e &&
typeof (e as { message?: unknown }).message === "string"
) {
return (e as { message: string }).message;
}
return "An unexpected error occurred.";
};
const handleAuth = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setValidationSuggestion(null);
try {
// Validate input with zod
const validated = authSchema.parse({ email, password });
const normalizedEmail = validated.email;
if (isSignUp) {
const { error } = await supabase.auth.signUp({
email: normalizedEmail,
password,
options: {
emailRedirectTo: `${window.location.origin}/`,
},
});
if (error) {
const message: string = error?.message ?? "Signup failed";
const details: string | undefined = (error as AuthError & { details?: string })?.details;
// Try to extract a suggested email from known error formats
let suggested: string | null = null;
const didYouMeanMatch = message.match(/Did you mean\s+([^?\s]+)\?/i);
if (didYouMeanMatch && didYouMeanMatch[1]) {
suggested = didYouMeanMatch[1].trim().toLowerCase();
}
if (!suggested && details) {
const detailMatch = details.match(/did_you_mean=([^,\s]+)/i);
if (detailMatch && detailMatch[1]) {
suggested = detailMatch[1].trim().toLowerCase();
}
}
if (suggested && suggested !== normalizedEmail) {
setValidationSuggestion(suggested);
setLoading(false);
return;
}
// Fallback: if GoTrue hides DB error as "unexpected_failure",
// ask the validator directly so we can surface a helpful message
const errorCode = (error as AuthError).code;
const looksGeneric =
errorCode === "unexpected_failure" || /Database error saving new user/i.test(message);
if (looksGeneric) {
try {
const { data, error: rpcError } = await supabase.rpc(
"validate_email_with_zerobounce",
{ p_email: normalizedEmail }
);
if (!rpcError && data) {
const result = data as unknown as {
valid: boolean;
email: string;
status?: string;
sub_status?: string;
did_you_mean?: string;
message?: string;
};
if (result.did_you_mean && result.did_you_mean !== normalizedEmail) {
setValidationSuggestion(result.did_you_mean);
setLoading(false);
return;
}
if (result.valid === false) {
toast.error("We couldn't verify this email. Please check and try again.");
setLoading(false);
return;
}
}
} catch (_) {
// Ignore and fall back to default error handling
}
}
throw error;
}
toast.success("Account created! You can now sign in.");
setIsSignUp(false);
} else {
const { error } = await supabase.auth.signInWithPassword({
email: normalizedEmail,
password,
});
if (error) throw error;
}
} catch (error: unknown) {
if (error instanceof z.ZodError) {
toast.error(error.errors[0].message);
} else {
toast.error(isSignUp ? "Signup failed. Please try again." : "Sign in failed. Please try again.");
}
} finally {
setLoading(false);
}
};
const useSuggestion = () => {
if (validationSuggestion) {
setEmail(validationSuggestion);
setValidationSuggestion(null);
}
};
const dismissSuggestion = () => {
setValidationSuggestion(null);
};
return (
<div className="min-h-screen flex items-center justify-center p-4" style={{ background: "var(--gradient-subtle)" }}>
<Card className="w-full max-w-md shadow-lg border-border/50" style={{ boxShadow: "var(--shadow-medium)" }}>
<CardHeader className="space-y-1 text-center">
<div className="flex justify-center mb-4">
<div className="w-12 h-12 rounded-xl flex items-center justify-center" style={{ background: "var(--gradient-primary)" }}>
<CheckCircle2 className="w-7 h-7 text-white" />
</div>
</div>
<CardTitle className="text-2xl font-bold bg-clip-text text-transparent" style={{ backgroundImage: "var(--gradient-primary)" }}>
{isSignUp ? "Create account" : "Welcome back"}
</CardTitle>
<CardDescription>
{isSignUp
? "Enter your email to create your account"
: "Enter your credentials to access your todos"}
</CardDescription>
</CardHeader>
<CardContent>
{validationSuggestion && (
<Alert aria-live="polite" className="mb-4 border-amber-300/60 bg-amber-50/80 text-amber-900 shadow-sm dark:border-amber-400/40 dark:bg-amber-950/30 dark:text-amber-200">
<AlertTriangle className="h-4 w-4 text-amber-500 dark:text-amber-400" />
<AlertDescription className="flex items-center justify-between gap-3">
<div className="text-sm">
<span className="opacity-90">Did you mean: </span>
<button
type="button"
onClick={useSuggestion}
className="font-semibold underline decoration-amber-400 underline-offset-2 hover:opacity-80"
>
{validationSuggestion}
</button>
<span>?</span>
</div>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={useSuggestion}
className="border-amber-300 text-amber-900 hover:bg-amber-100 dark:border-amber-400 dark:text-amber-100 dark:hover:bg-amber-900/40"
>
Use this
</Button>
<Button
type="button"
variant="ghost"
size="icon"
aria-label="Dismiss suggestion"
onClick={dismissSuggestion}
className="text-amber-700 hover:bg-amber-100 dark:text-amber-200 dark:hover:bg-amber-900/40"
>
<X className="h-4 w-4" />
</Button>
</div>
</AlertDescription>
</Alert>
)}
<form onSubmit={handleAuth} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="transition-all duration-200 focus:shadow-soft"
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={6}
className="transition-all duration-200 focus:shadow-soft"
/>
</div>
<Button
type="submit"
className="w-full hover:opacity-90 transition-opacity"
disabled={loading}
style={{ background: "var(--gradient-primary)" }}
>
{loading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Please wait
</>
) : isSignUp ? (
"Sign up"
) : (
"Sign in"
)}
</Button>
</form>
<div className="mt-4 text-center text-sm">
<button
type="button"
onClick={() => setIsSignUp(!isSignUp)}
className="text-muted-foreground hover:text-primary transition-colors"
>
{isSignUp ? "Already have an account? Sign in" : "Don't have an account? Sign up"}
</button>
</div>
</CardContent>
</Card>
</div>
);
};