-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
526 lines (460 loc) · 15.1 KB
/
auth.js
File metadata and controls
526 lines (460 loc) · 15.1 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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// GreenToastSoftware Authentication System
// Powered by Supabase
// ============================================
// Session Management
// ============================================
/**
* Ensure session is available - restore from backup if needed
*/
async function ensureSession() {
// First check if Supabase has a session
const { data } = await supabaseClient.auth.getSession();
if (data?.session) {
console.log('Session available in Supabase');
return data.session;
}
// If not, try to restore from backup
const backupData = sessionStorage.getItem('gt-temp-session');
if (backupData) {
try {
console.log('Restoring session from backup for operation...');
const sessionData = JSON.parse(backupData);
const { data: restored, error } = await supabaseClient.auth.setSession({
access_token: sessionData.access_token,
refresh_token: sessionData.refresh_token
});
if (restored?.session) {
console.log('Session restored successfully');
return restored.session;
}
if (error) {
console.error('Error restoring session:', error);
}
} catch (e) {
console.error('Failed to restore session:', e);
}
}
console.warn('No session available');
return null;
}
// ============================================
// Authentication Functions
// ============================================
/**
* Sign up a new user
* @param {string} email
* @param {string} password
* @param {object} metadata - Additional user metadata (name, etc.)
*/
async function signUp(email, password, metadata = {}) {
try {
console.log('=== SIGN UP ATTEMPT ===' );
console.log('Email:', email);
const { data, error } = await supabaseClient.auth.signUp({
email: email,
password: password,
options: {
data: {
full_name: metadata.fullName || '',
avatar_url: metadata.avatarUrl || '',
preferences: {
theme: 'light',
language: 'en',
notifications: true
}
}
}
});
console.log('Sign up response:', data, error);
if (error) {
// Handle specific errors
if (error.message?.includes('rate limit') || error.status === 429) {
throw new Error('Too many attempts. Please wait a few minutes and try again.');
}
throw error;
}
// Check if email confirmation is required
if (data?.user && !data?.session) {
// User created but needs email confirmation
return {
success: true,
data: data,
needsConfirmation: true,
message: 'Account created! Check your email inbox and click the confirmation link to activate your account.'
};
} else if (data?.session) {
// Auto-confirmed (no email verification required)
return {
success: true,
data: data,
needsConfirmation: false,
message: 'Account created successfully!'
};
}
return { success: true, data: data, message: 'Account created!' };
} catch (error) {
console.error('Sign up error:', error);
return { success: false, error: error.message };
}
}
/**
* Sign in an existing user
* @param {string} email
* @param {string} password
*/
async function signIn(email, password) {
console.log('=== SIGN IN ATTEMPT ===');
console.log('Email:', email);
try {
const { data, error } = await supabaseClient.auth.signInWithPassword({
email: email,
password: password
});
console.log('Sign in response:');
console.log('- Data:', data);
console.log('- Session:', data?.session);
console.log('- User:', data?.user?.email);
console.log('- Error:', error);
if (error) throw error;
// Check if session was saved
setTimeout(() => {
const savedSession = localStorage.getItem(window.SUPABASE_STORAGE_KEY || 'sb-fgigiqnvrexvtmqketuh-auth-token');
console.log('Session saved in localStorage:', savedSession ? 'YES (length: ' + savedSession.length + ')' : 'NO');
console.log('All auth keys:', Object.keys(localStorage).filter(k => k.includes('sb-') || k.includes('auth')));
}, 500);
// Store session info
localStorage.setItem('gt_user_session', JSON.stringify({
loggedInAt: new Date().toISOString(),
userAgent: navigator.userAgent,
platform: navigator.platform
}));
return { success: true, data: data };
} catch (error) {
console.error('Sign in error:', error);
return { success: false, error: error.message };
}
}
/**
* Sign out the current user
*/
async function signOut() {
try {
// Clear session backup on sign out
sessionStorage.removeItem('gt-temp-session');
const { error } = await supabaseClient.auth.signOut();
if (error) throw error;
localStorage.removeItem('gt_user_session');
return { success: true };
} catch (error) {
console.error('Sign out error:', error);
return { success: false, error: error.message };
}
}
/**
* Get the current user
*/
async function getCurrentUser() {
try {
// First try to get from session (faster)
const { data: { session } } = await supabaseClient.auth.getSession();
if (session?.user) {
return session.user;
}
// Fallback to getUser if no session
const { data: { user }, error } = await supabaseClient.auth.getUser();
if (error) throw error;
return user;
} catch (error) {
console.error('Get user error:', error);
return null;
}
}
/**
* Get the current session
*/
async function getSession() {
try {
const { data: { session }, error } = await supabaseClient.auth.getSession();
if (error) throw error;
return session;
} catch (error) {
console.error('Get session error:', error);
return null;
}
}
/**
* Send password reset email
* @param {string} email
*/
async function resetPassword(email) {
try {
const { data, error } = await supabaseClient.auth.resetPasswordForEmail(email, {
redirectTo: `${window.location.origin}/account.html?tab=security`
});
if (error) throw error;
return { success: true, message: 'Password reset email sent!' };
} catch (error) {
console.error('Reset password error:', error);
return { success: false, error: error.message };
}
}
/**
* Update user password
* @param {string} newPassword
*/
async function updatePassword(newPassword) {
try {
// Ensure session is available before operation
const session = await ensureSession();
if (!session) {
throw new Error('Auth session missing! Please log in again.');
}
const { data, error } = await supabaseClient.auth.updateUser({
password: newPassword
});
if (error) throw error;
return { success: true, message: 'Password updated successfully!' };
} catch (error) {
console.error('Update password error:', error);
return { success: false, error: error.message };
}
}
/**
* Update user profile
* @param {object} profileData
*/
async function updateProfile(profileData) {
try {
// Ensure session is available before operation
const session = await ensureSession();
if (!session) {
throw new Error('Auth session missing! Please log in again.');
}
const { data, error } = await supabaseClient.auth.updateUser({
data: profileData
});
if (error) throw error;
return { success: true, data: data, message: 'Profile updated successfully!' };
} catch (error) {
console.error('Update profile error:', error);
return { success: false, error: error.message };
}
}
/**
* Update user email
* @param {string} newEmail
*/
async function updateEmail(newEmail) {
try {
// Ensure session is available before operation
const session = await ensureSession();
if (!session) {
throw new Error('Auth session missing! Please log in again.');
}
const { data, error } = await supabaseClient.auth.updateUser({
email: newEmail
});
if (error) throw error;
return { success: true, message: 'Verification email sent to your new address!' };
} catch (error) {
console.error('Update email error:', error);
return { success: false, error: error.message };
}
}
/**
* Upload avatar image
* @param {File} file
*/
async function uploadAvatar(file) {
try {
// Ensure session is available
const session = await ensureSession();
if (!session) {
throw new Error('Auth session missing! Please log in again.');
}
const user = await getCurrentUser();
if (!user) throw new Error('User not authenticated');
const fileExt = file.name.split('.').pop();
const fileName = `${user.id}/avatar.${fileExt}`;
const { data, error: uploadError } = await supabaseClient.storage
.from('avatares')
.upload(fileName, file, {
cacheControl: '3600',
upsert: true,
contentType: file.type,
metadata: {
'content-type': file.type,
'size': file.size.toString()
}
});
if (uploadError) throw uploadError;
const { data: { publicUrl } } = supabaseClient.storage
.from('avatares')
.getPublicUrl(fileName);
// Update user profile with avatar URL
await updateProfile({ avatar_url: publicUrl });
return { success: true, url: publicUrl };
} catch (error) {
console.error('Upload avatar error:', error);
return { success: false, error: error.message };
}
}
/**
* Get user preferences
*/
async function getPreferences() {
const user = await getCurrentUser();
if (!user) return null;
return user.user_metadata?.preferences || {
theme: 'light',
language: 'en',
notifications: true,
emailUpdates: false
};
}
/**
* Update user preferences
* @param {object} preferences
*/
async function updatePreferences(preferences) {
try {
const user = await getCurrentUser();
if (!user) throw new Error('User not authenticated');
const currentMetadata = user.user_metadata || {};
const updatedPreferences = {
...currentMetadata.preferences,
...preferences
};
const result = await updateProfile({
...currentMetadata,
preferences: updatedPreferences
});
return result;
} catch (error) {
console.error('Update preferences error:', error);
return { success: false, error: error.message };
}
}
/**
* Get session history from local storage
*/
function getSessionHistory() {
try {
const history = localStorage.getItem('gt_session_history');
return history ? JSON.parse(history) : [];
} catch {
return [];
}
}
/**
* Add current session to history
*/
function addSessionToHistory() {
const history = getSessionHistory();
const currentSession = {
id: Date.now(),
timestamp: new Date().toISOString(),
userAgent: navigator.userAgent,
platform: navigator.platform,
language: navigator.language,
screenResolution: `${window.screen.width}x${window.screen.height}`
};
// Keep only last 10 sessions
history.unshift(currentSession);
if (history.length > 10) {
history.pop();
}
localStorage.setItem('gt_session_history', JSON.stringify(history));
return history;
}
/**
* Clear session history
*/
function clearSessionHistory() {
localStorage.removeItem('gt_session_history');
return [];
}
/**
* Delete user account
*/
async function deleteAccount() {
try {
// Note: Account deletion requires server-side implementation via Supabase Edge Functions
// This is a placeholder that signs out the user
await signOut();
localStorage.clear();
return {
success: true,
message: 'Please contact support at [email protected] to complete account deletion.'
};
} catch (error) {
console.error('Delete account error:', error);
return { success: false, error: error.message };
}
}
// ============================================
// Auth State Listener (for navbar only - pages handle their own redirects)
// ============================================
/**
* Update navbar to show auth state
*/
function updateNavbarAuthState(isLoggedIn, user) {
const authBtn = document.getElementById('auth-nav-btn');
const authBtnMobile = document.getElementById('auth-nav-btn-mobile');
if (authBtn) {
if (isLoggedIn && user) {
const displayName = user.user_metadata?.full_name || user.email?.split('@')[0] || 'Account';
authBtn.innerHTML = `
<span class="user-avatar-small">
${user.user_metadata?.avatar_url
? `<img src="${user.user_metadata.avatar_url}" alt="Avatar">`
: displayName.charAt(0).toUpperCase()}
</span>
<span class="user-name">${displayName}</span>
`;
authBtn.href = 'account.html';
} else {
authBtn.innerHTML = 'Sign In';
authBtn.href = 'login.html';
}
}
if (authBtnMobile) {
authBtnMobile.href = isLoggedIn ? 'account.html' : 'login.html';
authBtnMobile.textContent = isLoggedIn ? 'My Account' : 'Sign In';
}
}
// Global auth state listener - only updates navbar, doesn't redirect
supabaseClient.auth.onAuthStateChange((event, session) => {
console.log('Global auth state changed:', event);
if (event === 'SIGNED_IN' || event === 'TOKEN_REFRESHED') {
addSessionToHistory();
updateNavbarAuthState(true, session?.user);
} else if (event === 'SIGNED_OUT') {
updateNavbarAuthState(false, null);
}
});
// Check auth state on page load for navbar
document.addEventListener('DOMContentLoaded', async () => {
const session = await getSession();
updateNavbarAuthState(!!session, session?.user);
});
// Export functions
window.auth = {
signUp,
signIn,
signOut,
getCurrentUser,
getSession,
ensureSession,
resetPassword,
updatePassword,
updateProfile,
updateEmail,
uploadAvatar,
getPreferences,
updatePreferences,
getSessionHistory,
addSessionToHistory,
clearSessionHistory,
deleteAccount
};