Skip to content

Commit d64a674

Browse files
committed
fix(auth): stabilize magic link submission
1 parent a362d77 commit d64a674

1 file changed

Lines changed: 33 additions & 10 deletions

File tree

lib/features/auth/auth-service.ts

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -239,32 +239,55 @@ export async function signInWithOtp(
239239
email: string,
240240
rememberMe = true,
241241
): Promise<{ success: boolean; error?: string; message?: string }> {
242-
try {
243-
const supabase = createClient()
242+
const controller = new AbortController()
243+
const timeoutId = window.setTimeout(() => controller.abort(), 15000)
244244

245-
// Send OTP to user's email
246-
const { error } = await supabase.auth.signInWithOtp({
247-
email,
248-
options: {
249-
emailRedirectTo: `${window.location.origin}/auth/callback`,
245+
try {
246+
const response = await fetch('/api/auth/magic-link', {
247+
method: 'POST',
248+
headers: {
249+
'Content-Type': 'application/json',
250250
},
251+
body: JSON.stringify({ email }),
252+
cache: 'no-store',
253+
signal: controller.signal,
251254
})
252255

253-
if (error) {
254-
return { success: false, error: error.message }
256+
const result = await response.json().catch(() => null) as {
257+
success?: boolean
258+
error?: string
259+
message?: string
260+
} | null
261+
262+
if (!response.ok || !result?.success) {
263+
return {
264+
success: false,
265+
error: result?.error || 'Failed to send login link',
266+
}
255267
}
256268

257269
// Store remember me preference for after OTP verification
258270
if (rememberMe) {
259271
localStorage.setItem("lab68_remember", "true")
272+
} else {
273+
localStorage.removeItem("lab68_remember")
260274
}
261275

262276
return {
263277
success: true,
264-
message: 'Check your email for the magic link to sign in.'
278+
message: result.message || 'Check your email for the magic link to sign in.'
265279
}
266280
} catch (error: any) {
281+
if (error?.name === 'AbortError') {
282+
return {
283+
success: false,
284+
error: 'The request took too long. The email may still arrive, but please try again if it does not.',
285+
}
286+
}
287+
267288
return { success: false, error: error.message || 'Failed to send login link' }
289+
} finally {
290+
window.clearTimeout(timeoutId)
268291
}
269292
}
270293

0 commit comments

Comments
 (0)