-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-service.ts
More file actions
457 lines (392 loc) · 11.6 KB
/
Copy pathauth-service.ts
File metadata and controls
457 lines (392 loc) · 11.6 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Supabase authentication
import { createClient } from "../../database/supabase-client"
export interface User {
id: string
email: string
name: string
createdAt: string
language?: string
bio?: string
location?: string
website?: string
avatar?: string
}
export interface AuthState {
user: User | null
isAuthenticated: boolean
}
type MinimalCachedUser = Pick<User, "id" | "email" | "name" | "language" | "avatar">
let inMemoryUser: User | null = null
function readDashboardUserSnapshot(): User | null {
if (typeof document === "undefined") return null
const root = document.querySelector("[data-lab68-user]")
const encoded = root?.getAttribute("data-lab68-user")
if (!encoded) return null
try {
const decoded = window.atob(encoded)
const parsed = JSON.parse(decoded) as Partial<User>
if (!parsed?.id) return null
return {
id: parsed.id,
email: parsed.email || "",
name: parsed.name || "User",
createdAt: parsed.createdAt || "",
language: parsed.language,
avatar: parsed.avatar,
}
} catch {
return null
}
}
function toCachedUser(user: User): MinimalCachedUser {
return {
id: user.id,
email: user.email,
name: user.name,
language: user.language,
avatar: user.avatar,
}
}
export function setCachedUser(user: User | null) {
inMemoryUser = user
}
// Get current user from memory or dashboard server snapshot
export function getCurrentUser(): User | null {
if (inMemoryUser) return inMemoryUser
if (typeof window === "undefined") return null
const snapshot = readDashboardUserSnapshot()
if (snapshot) {
inMemoryUser = snapshot
return snapshot
}
return null
}
// Get current user session from Supabase (authoritative source)
export async function getCurrentUserAsync(): Promise<User | null> {
if (typeof window === "undefined") return null
try {
const supabase = createClient()
const { data: { user: authUser }, error } = await supabase.auth.getUser()
if (error || !authUser) return null
// Fetch user profile from database
const { data: profile, error: profileError } = await supabase
.from('profiles')
.select('*')
.eq('id', authUser.id)
.single()
if (profileError || !profile) {
// Return basic user info if profile doesn't exist
const user: User = {
id: authUser.id,
email: authUser.email || '',
name: authUser.user_metadata?.name || authUser.email?.split('@')[0] || 'User',
createdAt: authUser.created_at,
language: 'en'
}
setCachedUser(user)
return user
}
const user: User = {
id: profile.id,
email: authUser.email || '',
name: profile.name,
createdAt: profile.created_at,
language: profile.language,
bio: profile.bio,
location: profile.location,
website: profile.website,
avatar: profile.avatar
}
setCachedUser(user)
return user
} catch (error) {
console.error('Error getting current user:', error)
return null
}
}
// Sign up a new user with email and password
export async function signUp(
email: string,
password: string,
name?: string,
language?: string,
): Promise<{ success: boolean; error?: string; user?: User }> {
try {
const supabase = createClient()
const autoName = name || email.split('@')[0] || 'User';
// Sign up with Supabase Auth
const { data: authData, error: signUpError } = await supabase.auth.signUp({
email,
password,
options: {
data: {
name: autoName,
language: language || 'en'
},
emailRedirectTo: `${window.location.origin}/auth/callback`
}
})
if (signUpError) {
return { success: false, error: signUpError.message }
}
if (!authData.user) {
return { success: false, error: 'Sign up failed' }
}
const newUser: User = {
id: authData.user.id,
email,
name: autoName,
createdAt: new Date().toISOString(),
language: language || 'en',
}
setCachedUser(newUser)
return { success: true, user: newUser }
} catch (error: any) {
return { success: false, error: error.message || 'Sign up failed' }
}
}
// Sign in user with email and password
export async function signIn(
email: string,
password: string,
rememberMe = false,
): Promise<{ success: boolean; error?: string; user?: User }> {
try {
const supabase = createClient()
const { data: authData, error: signInError } = await supabase.auth.signInWithPassword({
email,
password,
})
if (signInError) {
return { success: false, error: signInError.message }
}
if (!authData.user) {
return { success: false, error: 'Sign in failed' }
}
// Fetch user profile
const { data: profile } = await supabase
.from('profiles')
.select('*')
.eq('id', authData.user.id)
.single()
const user: User = profile ? {
id: profile.id,
email: authData.user.email || '',
name: profile.name,
createdAt: profile.created_at,
language: profile.language,
bio: profile.bio,
location: profile.location,
website: profile.website,
avatar: profile.avatar
} : {
id: authData.user.id,
email: authData.user.email || '',
name: authData.user.user_metadata?.name || authData.user.email?.split('@')[0] || 'User',
createdAt: authData.user.created_at,
language: 'en'
}
setCachedUser(user)
if (rememberMe) {
localStorage.setItem("lab68_remember", "true")
} else {
localStorage.removeItem("lab68_remember")
}
return { success: true, user }
} catch (error: any) {
return { success: false, error: error.message || 'Sign in failed' }
}
}
// Passwordless authentication using magic link/OTP
// This sends a one-time password to the user's email
export async function signInWithOtp(
email: string,
rememberMe = true,
): Promise<{ success: boolean; error?: string; message?: string }> {
const controller = new AbortController()
const timeoutId = window.setTimeout(() => controller.abort(), 15000)
try {
const response = await fetch('/api/auth/magic-link', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
cache: 'no-store',
signal: controller.signal,
})
const result = await response.json().catch(() => null) as {
success?: boolean
error?: string
message?: string
} | null
if (!response.ok || !result?.success) {
return {
success: false,
error: result?.error || 'Failed to send login link',
}
}
// Store remember me preference for after OTP verification
if (rememberMe) {
localStorage.setItem("lab68_remember", "true")
} else {
localStorage.removeItem("lab68_remember")
}
return {
success: true,
message: result.message || 'Check your email for the magic link to sign in.'
}
} catch (error: any) {
if (error?.name === 'AbortError') {
return {
success: false,
error: 'The request took too long. The email may still arrive, but please try again if it does not.',
}
}
return { success: false, error: error.message || 'Failed to send login link' }
} finally {
window.clearTimeout(timeoutId)
}
}
// Verify OTP code
export async function verifyOtp(
email: string,
token: string,
rememberMe = true
): Promise<{ success: boolean; error?: string; user?: User }> {
try {
const supabase = createClient()
const { data: authData, error } = await supabase.auth.verifyOtp({
email,
token,
type: 'email',
})
if (error || !authData.user) {
return { success: false, error: error?.message || 'Invalid or expired code' }
}
// Fetch or create user profile
const { data: profile } = await supabase
.from('profiles')
.select('*')
.eq('id', authData.user.id)
.single()
const user: User = profile ? {
id: profile.id,
email: authData.user.email || '',
name: profile.name,
createdAt: profile.created_at,
language: profile.language,
bio: profile.bio,
location: profile.location,
website: profile.website,
avatar: profile.avatar
} : {
id: authData.user.id,
email: authData.user.email || '',
name: authData.user.user_metadata?.name || authData.user.email?.split('@')[0] || 'User',
createdAt: authData.user.created_at,
language: 'en'
}
setCachedUser(user)
if (rememberMe) {
localStorage.setItem("lab68_remember", "true")
}
return { success: true, user }
} catch (error: any) {
return { success: false, error: error.message || 'Verification failed' }
}
}
// Legacy function kept for backwards compatibility
// DEPRECATED: Use signInWithOtp instead
export async function signInOrSignUpWithEmailOnly(
email: string,
rememberMe = true,
): Promise<{ success: boolean; error?: string; user?: User }> {
// This now uses proper OTP-based authentication
const result = await signInWithOtp(email, rememberMe)
if (result.success) {
// For this flow, we return success but the user needs to verify their email
// The actual sign-in happens after clicking the magic link
return {
success: true,
user: undefined // User not fully authenticated yet
}
}
return { success: false, error: result.error }
}
// Sign out user
export async function signOut(): Promise<void> {
try {
const supabase = createClient()
await supabase.auth.signOut()
setCachedUser(null)
localStorage.removeItem("lab68_remember")
} catch (error) {
console.error('Error signing out:', error)
setCachedUser(null)
localStorage.removeItem("lab68_remember")
}
}
// Check if user is authenticated
export async function isAuthenticated(): Promise<boolean> {
try {
const supabase = createClient()
const { data: { user } } = await supabase.auth.getUser()
return !!user
} catch (error) {
return false
}
}
// Update user profile
export async function updateUserProfile(
userId: string,
updates: Partial<Omit<User, "id" | "email" | "createdAt">>,
): Promise<{ success: boolean; error?: string; user?: User }> {
try {
const supabase = createClient()
// Update profile in database
const { data, error } = await supabase
.from('profiles')
.update({
name: updates.name,
language: updates.language,
bio: updates.bio,
location: updates.location,
website: updates.website,
avatar: updates.avatar
})
.eq('id', userId)
.select()
.single()
if (error) {
return { success: false, error: error.message }
}
// Get updated user
const currentUser = await getCurrentUserAsync()
if (currentUser && currentUser.id === userId) {
setCachedUser(currentUser)
}
return { success: true, user: currentUser || undefined }
} catch (error: any) {
return { success: false, error: error.message || 'Update failed' }
}
}
// Check if user has a remembered session
export async function checkRememberMe(): Promise<User | null> {
if (typeof window === "undefined") return null
try {
const remember = localStorage.getItem("lab68_remember")
if (!remember) return null
const user = await getCurrentUserAsync()
return user
} catch (error) {
localStorage.removeItem("lab68_remember")
return null
}
}
// Clear all auth data (useful for debugging)
export function clearAuthData(): void {
if (typeof window === "undefined") return
setCachedUser(null)
localStorage.removeItem("lab68_remember")
}