-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauthentication.html
More file actions
569 lines (500 loc) · 32.7 KB
/
authentication.html
File metadata and controls
569 lines (500 loc) · 32.7 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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>4SP - AUTHENTICATION</title>
<meta name="description" content="Log into or create your 4SP account to access the student toolkit.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Geist:wght@100..900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
<script src="../navigation-mini.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script>
// Unified Tailwind CSS configuration for a consistent dark theme
tailwind.config = {
theme: {
extend: {
colors: {
'custom-darkest-gray': '#040404', // Body background
'custom-dark-gray': '#111111', // Form container background
'custom-medium-gray': '#252525', // Borders, inputs, buttons
'custom-light-gray': '#505050', // Labels and secondary text
'custom-lighter-gray': '#808080', // Hover states and subtle text
'custom-white-gray': '#c0c0c0', // Main text and headings
}
}
}
}
</script>
<style>
:root {
--geist-foreground: 192, 192, 192; /* custom-white-gray */
--geist-background: 7, 7, 7; /* custom-darkest-gray */
}
body {
font-family: 'Geist', sans-serif;
background-color: rgb(var(--geist-background));
color: rgb(var(--geist-foreground));
transition: all 0.3s ease;
font-weight: 300; /* CUSTOM: Lighter base font weight */
}
/* CUSTOM: Lighter bold/headings to match notes.html */
h1, h2, h3, .font-bold, .font-semibold, strong, .tracking-tighter {
font-weight: 400 !important;
}
.btn-social {
transition: background-color 0.3s ease, border-color 0.3s ease;
}
.btn-social:hover {
/* Keep existing hover effect for social buttons */
background-color: rgba(37, 37, 37, 0.7); /* custom-medium-gray with transparency */
border-color: #383838;
}
.message-area { min-height: 20px; }
.error-message { color: #f87171; font-weight: 400; /* Match new heading weight */ }
.success-message { color: #4ade80; font-weight: 400; }
.warning-message { color: #fbbf24; font-weight: 400; }
.auth-split-container { max-width: 1200px; margin: 0 auto; }
@media (min-width: 768px) { .auth-col { } }
@media (max-width: 767px) {
.right-col { display: none; }
.left-col { border-right: none; }
}
</style>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-1D4F692C1Q"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-1D4F692C1Q');
</script>
</head>
<body class="bg-custom-darkest-gray text-custom-white-gray min-h-screen flex flex-col">
<div id="navbar-container"></div>
<main class="flex-grow flex items-stretch justify-center p-0">
<div class="auth-split-container bg-custom-darkest-gray flex flex-wrap w-full border-0 overflow-hidden p-0">
<div class="auth-col left-col flex-1 p-8 flex flex-col justify-center items-center bg-custom-darkest-gray min-w-[300px]">
<div id="loginContainer" class="w-full flex flex-col items-center">
<h2 class="text-3xl font-normal text-custom-white-gray mb-6 text-center w-full tracking-tighter">Login to Your Account</h2>
<form id="loginForm" novalidate class="w-full max-w-md">
<div class="mb-5">
<label for="loginEmail" class="block mb-2 text-custom-light-gray text-sm font-light text-left">Email</label>
<input type="email" id="loginEmail" placeholder="Enter your email" required class="w-full p-3 border border-custom-medium-gray bg-custom-dark-gray rounded-xl text-custom-white-gray transition focus:border-custom-light-gray focus:ring focus:ring-custom-light-gray/50 focus:outline-none">
</div>
<div class="mb-5">
<label for="loginPassword" class="block mb-2 text-custom-light-gray text-sm font-light text-left">Password</label>
<input type="password" id="loginPassword" placeholder="Enter your password" required class="w-full p-3 border border-custom-medium-gray bg-custom-dark-gray rounded-xl text-custom-white-gray transition focus:border-custom-light-gray focus:ring focus:ring-custom-light-gray/50 focus:outline-none">
</div>
<button type="submit" class="w-full p-3 text-lg rounded-xl font-normal ring-1 ring-white/20 text-white bg-white/5 hover:bg-white/10 transition">LOGIN</button>
</form>
<div id="loginMessage" class="message-area w-full max-w-md mt-4 text-center text-sm"></div>
<div class="w-full max-w-md mt-4 text-center">
<a id="forgotPasswordLink" class="text-white hover:text-gray-300 font-normal text-sm cursor-pointer">Forgot Password?</a>
</div>
<p class="text-sm text-custom-light-gray mt-6 text-center w-full max-w-md">
Don't have an account?
<a id="showSignupLink" href="#" class="text-white hover:text-gray-300 font-normal transition">Sign up here</a>
</p>
</div>
<div id="resetPasswordContainer" class="w-full flex-col items-center" style="display: none;">
<h2 class="text-3xl font-normal text-custom-white-gray mb-6 text-center w-full tracking-tighter">Reset Your Password</h2>
<p class="text-custom-light-gray text-base mb-6 text-center max-w-md font-normal">Enter your email address and we'll send you a link to reset your password.</p>
<form id="resetPasswordForm" novalidate class="w-full max-w-md">
<div class="mb-5">
<label for="resetEmail" class="block mb-2 text-custom-light-gray text-sm font-light text-left">Email</label>
<input type="email" id="resetEmail" placeholder="Enter your registered email" required class="w-full p-3 border border-custom-medium-gray bg-custom-dark-gray rounded-xl text-custom-white-gray transition focus:border-custom-light-gray focus:ring focus:ring-custom-light-gray/50 focus:outline-none">
</div>
<button type="submit" class="w-full p-3 text-lg rounded-xl font-normal ring-1 ring-white/20 text-white bg-white/5 hover:bg-white/10 transition">SEND RESET LINK</button>
</form>
<div id="resetMessage" class="message-area w-full max-w-md mt-4 text-center text-sm"></div>
<div class="w-full max-w-md mt-6 text-center">
<a id="backToLoginLink" class="text-white hover:text-gray-300 font-normal text-sm cursor-pointer">← Back to Login</a>
</div>
</div>
<div id="usernameContainer" class="w-full flex-col items-center" style="display: none;">
<h2 class="text-3xl font-normal text-custom-white-gray mb-6 text-center w-full tracking-tighter">Choose Your Username</h2>
<form id="usernameForm" novalidate class="w-full max-w-md">
<div class="mb-5">
<label for="signupUsername" class="block mb-2 text-custom-light-gray text-sm font-light text-left">Username</label>
<input type="text" id="signupUsername" placeholder="6-24 characters, including symbols" required class="w-full p-3 border border-custom-medium-gray bg-custom-dark-gray rounded-xl text-custom-white-gray transition focus:border-custom-light-gray focus:ring focus:ring-custom-light-gray/50 focus:outline-none">
<p class="text-xs text-custom-lighter-gray mt-2 text-left font-light">Allowed symbols: .,-+\_!?$</p>
</div>
<button type="submit" class="w-full p-3 text-lg rounded-xl font-normal ring-1 ring-white/20 text-white bg-white/5 hover:bg-white/10 transition">NEXT</button>
</form>
<div id="usernameMessage" class="message-area w-full max-w-md mt-4 text-center text-sm"></div>
<p class="text-sm text-custom-light-gray mt-6 text-center w-full max-w-md">
Already have an account?
<a id="showLoginLink" href="#" class="text-white hover:text-gray-300 font-normal transition">Login here</a>
</p>
</div>
<div id="signupContainer" class="w-full flex-col items-center" style="display: none;">
<h2 class="text-3xl font-normal text-custom-white-gray mb-6 text-center w-full tracking-tighter">Set Your Credentials</h2>
<form id="signupForm" novalidate class="w-full max-w-md">
<div class="mb-5">
<label for="signupEmail" class="block mb-2 text-custom-light-gray text-sm font-light text-left">Email</label>
<input type="email" id="signupEmail" placeholder="Enter your email" required class="w-full p-3 border border-custom-medium-gray bg-custom-dark-gray rounded-xl text-custom-white-gray transition focus:border-custom-light-gray focus:ring focus:ring-custom-light-gray/50 focus:outline-none">
</div>
<div class="mb-5">
<label for="signupPassword" class="block mb-2 text-custom-light-gray text-sm font-light text-left">Password</label>
<input type="password" id="signupPassword" placeholder="Enter your password" required class="w-full p-3 border border-custom-medium-gray bg-custom-dark-gray rounded-xl text-custom-white-gray transition focus:border-custom-light-gray focus:ring focus:ring-custom-light-gray/50 focus:outline-none">
<p class="text-xs text-custom-lighter-gray mt-2 text-left font-light">At least 8 characters, including a number, an uppercase, and a lowercase letter.</p>
</div>
<button type="submit" class="w-full p-3 text-lg rounded-xl font-normal ring-1 ring-white/20 text-white bg-white/5 hover:bg-white/10 transition">CREATE ACCOUNT</button>
</form>
<div id="signupMessage" class="message-area w-full max-w-md mt-4 text-center text-sm"></div>
<div class="w-full max-w-md mt-6 text-center">
<a id="backToUsernameLink" class="text-white hover:text-gray-300 font-normal text-sm cursor-pointer">← Back to Username</a>
</div>
</div>
</div>
<div class="auth-col right-col flex-1 p-8 flex flex-col justify-center items-center bg-custom-darkest-gray">
<div class="w-full flex flex-col items-center justify-center">
<h2 class="text-3xl font-normal text-custom-white-gray mb-6 text-center w-full tracking-tighter">Continue instantly</h2>
<p class="text-lg text-custom-light-gray mb-8 text-center max-w-md font-normal">
Use a trusted provider to sign in or create an account in one click.
</p>
<button id="googleAuthBtn" class="btn-social flex items-center justify-center w-full max-w-md p-3 bg-custom-dark-gray text-custom-white-gray border border-custom-medium-gray rounded-xl font-normal cursor-pointer mb-3">
<img src="images/google-icon.png" alt="Google Logo" class="w-6 h-6 mr-3">
Continue with Google
</button>
<button id="microsoftAuthBtn" class="btn-social flex items-center justify-center w-full max-w-md p-3 bg-custom-dark-gray text-custom-white-gray border border-custom-medium-gray rounded-xl font-normal cursor-pointer mb-3">
<img src="images/microsoft.png" alt="Microsoft Logo" class="w-6 h-6 mr-3">
Continue with Microsoft
</button>
<button id="githubAuthBtn" class="btn-social flex items-center justify-center w-full max-w-md p-3 bg-custom-dark-gray text-custom-white-gray border border-custom-medium-gray rounded-xl font-normal cursor-pointer mb-3">
<img src="images/github-mark-white.png" alt="GitHub Logo" class="w-6 h-6 mr-3">
Continue with GitHub
</button>
<button id="twitterAuthBtn" class="btn-social flex items-center justify-center w-full max-w-md p-3 bg-custom-dark-gray text-custom-white-gray border border-custom-medium-gray rounded-xl font-normal cursor-pointer mb-3">
<img src="../images/x.png" alt="X Logo" class="w-6 h-6 mr-3">
Continue with X
</button>
<p class="text-xs italic text-custom-light-gray text-center max-w-md mt-4 leading-relaxed font-light">
By continuing, you agree to our
<a href="legal.html#terms-of-service" target="_blank" class="text-white hover:text-gray-300 font-normal">Terms of Service</a> and
<a href="legal.html#privacy-policy" target="_blank" class="text-white hover:text-gray-300 font-normal">Privacy Policy</a>.
</p>
</div>
</div>
</div>
</main>
<footer class="border-t border-gray-900 py-6">
<div class="mx-auto max-w-7xl px-4 text-center text-gray-500 text-sm">
© 2025 4simpleproblems (4SP). Built for students.
<span class="mx-2">|</span>
<a href="legal.html#terms-of-service" class="hover:underline">Terms of Service</a>
<span class="mx-2">|</span>
<a href="legal.html#privacy-policy" class="hover:underline">Privacy Policy</a>
</div>
</footer>
<script type="module">
// --- Firebase Imports (Combined) ---
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import {
getAuth,
onAuthStateChanged,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
sendPasswordResetEmail,
sendEmailVerification,
fetchSignInMethodsForEmail,
signOut,
GoogleAuthProvider,
GithubAuthProvider,
TwitterAuthProvider,
OAuthProvider,
signInWithPopup,
setPersistence,
browserLocalPersistence,
getAdditionalUserInfo
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";
import {
getFirestore,
doc,
getDoc,
setDoc,
collection,
query,
where,
getDocs,
serverTimestamp,
setLogLevel
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";
// --- Import Firebase Config ---
import { firebaseConfig } from "./firebase-config.js";
// --- Canvas Global Variables (MANDATORY USE) ---
const appId = typeof __app_id !== 'undefined' ? __app_id : 'default-app-id';
if (!firebaseConfig || !firebaseConfig.apiKey) {
console.error("FATAL ERROR: Firebase configuration is missing or invalid.");
}
// --- Firebase Initialization ---
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
setLogLevel('debug'); // Enable Firestore logging
let hasRedirected = false;
onAuthStateChanged(auth, async (user) => {
if (user) {
// User is signed in.
if (!hasRedirected && window.location.pathname.endsWith('authentication.html')) {
const userDoc = await getDoc(getUserDocRef(user.uid));
if (userDoc.exists()) {
// Ensure user document exists before redirecting
hasRedirected = true;
navigateToDashboard();
}
}
} else {
// User is signed out.
hasRedirected = false;
}
});
// --- Unified Data Model ---
// All user profile data will be stored in a top-level 'users' collection.
const getUserDocRef = (userId) => doc(db, 'users', userId);
let selectedUsername = null; // Store username between signup steps
// --- DOM Elements ---
const containers = {
login: document.getElementById('loginContainer'),
reset: document.getElementById('resetPasswordContainer'),
username: document.getElementById('usernameContainer'),
signup: document.getElementById('signupContainer')
};
const messageDivs = {
login: document.getElementById('loginMessage'),
reset: document.getElementById('resetMessage'),
username: document.getElementById('usernameMessage'),
signup: document.getElementById('signupMessage')
};
// --- View Management ---
const showView = (viewName) => {
Object.values(messageDivs).forEach(div => div.innerHTML = '');
for (const key in containers) {
containers[key].style.display = (key === viewName) ? 'flex' : 'none';
if (key === viewName) {
containers[key].style.flexDirection = 'column';
}
}
};
// --- Helper Functions ---
const showMessage = (element, text, type = 'error') => {
element.innerHTML = text;
element.className = `message-area w-full max-w-md mt-4 text-center text-sm ${type}-message`;
};
const navigateToDashboard = () => window.location.href = 'logged-in/dashboard.html';
const createUserDocument = async (user, authMethod, username) => {
const isVerified = authMethod !== 'email' || !!user.emailVerified;
try {
await setDoc(getUserDocRef(user.uid), {
email: user.email,
authMethod: authMethod,
createdAt: serverTimestamp(),
username: username,
emailVerified: isVerified
});
return true;
} catch (error) {
console.error("Error creating user document:", error);
return false;
}
};
const handleSuccessfulLogin = async (user) => {
await setPersistence(auth, browserLocalPersistence);
const isProviderLogin = user.providerData.some(p => ['google.com', 'github.com', 'twitter.com', 'microsoft.com'].includes(p.providerId));
if (user.emailVerified || isProviderLogin) {
navigateToDashboard();
} else { showMessage(messageDivs.login, 'Your email is not verified. Please check your inbox. <a href="#" id="resend-link" class="underline cursor-pointer">Resend email</a>', 'error');
document.getElementById('resend-link').addEventListener('click', async (e) => {
e.preventDefault();
try {
await sendEmailVerification(user);
showMessage(messageDivs.login, 'A new verification link has been sent!', 'success');
} catch (err) { showMessage(messageDivs.login, `Error sending email: ${err.message}`); }
});
await signOut(auth);
}
};
const checkProfanity = async (text) => {
try {
const response = await fetch(`https://www.purgomalum.com/service/containsprofanity?text=${encodeURIComponent(text)}`);
const result = await response.text();
return result.toLowerCase() === 'true';
} catch (error) { console.error('Profanity API error:', error); return false; }
};
const isUsernameTaken = async (username) => {
const q = query(collection(db, 'users'), where('username', '==', username));
const querySnapshot = await getDocs(q);
return !querySnapshot.empty;
};
const validateEmail = (email) => {
// Robust regex check for basic email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!email) return 'Email is required.';
if (!emailRegex.test(email)) return 'The email address format is invalid.';
return null;
};
// --- UPDATED PASSWORD VALIDATION: Minimum length changed to 8 ---
const validatePassword = (password) => {
if (password.length < 8) return 'Password must be at least 8 characters.';
if (!/[0-9]/.test(password)) return 'Password must contain at least one number.';
if (!/[A-Z]/.test(password)) return 'Password must contain at least one uppercase letter.';
if (!/[a-z]/.test(password)) return 'Password must contain at least one lowercase letter.';
return null;
};
// --- END UPDATED VALIDATION ---
// --- Event Listener Setup ---
document.addEventListener('DOMContentLoaded', () => {
// Initial view
showView('login');
// --- View Navigation ---
document.getElementById('showSignupLink').addEventListener('click', (e) => { e.preventDefault(); showView('username'); });
document.getElementById('showLoginLink').addEventListener('click', (e) => { e.preventDefault(); showView('login'); });
document.getElementById('forgotPasswordLink').addEventListener('click', () => showView('reset'));
document.getElementById('backToLoginLink').addEventListener('click', () => showView('login'));
document.getElementById('backToUsernameLink').addEventListener('click', () => showView('username'));
// --- Form Handlers ---
// Login Form
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('loginEmail').value.trim();
const password = document.getElementById('loginPassword').value;
if (!email || !password) { showMessage(messageDivs.login, 'Please enter both email and password.'); return; }
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password);
const userDoc = await getDoc(getUserDocRef(userCredential.user.uid));
if (userDoc.exists()) {
await handleSuccessfulLogin(userCredential.user);
} else {
await signOut(auth);
showMessage(messageDivs.login, 'Account record is incomplete. Please sign up again or contact support.');
}
} catch (error) {
let msg = 'Invalid email or password.';
if (error.code === 'auth/too-many-requests') msg = 'Access temporarily disabled due to too many failed login attempts.';
else if (error.code === 'auth/user-disabled') msg = 'Your account has been disabled.';
showMessage(messageDivs.login, msg);
}
});
// Password Reset Form
document.getElementById('resetPasswordForm').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('resetEmail').value.trim();
if (!email) { showMessage(messageDivs.reset, 'Please enter your email.'); return; }
try {
const methods = await fetchSignInMethodsForEmail(auth, email);
if (methods.length === 0) {
showMessage(messageDivs.reset, 'No account found with this email.');
} else if (methods.some(m => m !== 'password')) {
showMessage(messageDivs.reset, 'This account uses a social provider and does not have a password to reset.');
} else {
await sendPasswordResetEmail(auth, email);
showMessage(messageDivs.reset, 'Password reset link sent! Check your inbox.', 'success');
}
} catch (error) {
showMessage(messageDivs.reset, 'An error occurred. Please check the email and try again.');
}
});
// Signup Step 1: Username Form
document.getElementById('usernameForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('signupUsername').value.trim();
if (username.length < 6 || username.length > 24) { showMessage(messageDivs.username, 'Username must be 6-24 characters.'); return; }
if (!/^[a-zA-Z0-9.,\-+_\!\?\$\\]+$/.test(username)) { showMessage(messageDivs.username, 'Username contains invalid characters.'); return; }
showMessage(messageDivs.username, 'Checking username...', 'warning');
if (await checkProfanity(username)) { showMessage(messageDivs.username, 'This username is not allowed. Please choose another.'); return; }
if (await isUsernameTaken(username)) { showMessage(messageDivs.username, 'This username is already taken.'); return; }
selectedUsername = username;
showView('signup');
document.getElementById('signupEmail').focus();
});
// Signup Step 2: Credentials Form
document.getElementById('signupForm').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('signupEmail').value.trim();
const password = document.getElementById('signupPassword').value;
const emailError = validateEmail(email);
if (emailError) { showMessage(messageDivs.signup, emailError); return; }
const passwordError = validatePassword(password);
if (passwordError) { showMessage(messageDivs.signup, passwordError); return; }
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
await sendEmailVerification(userCredential.user);
const docCreated = await createUserDocument(userCredential.user, 'email', selectedUsername);
if (docCreated) {
await signOut(auth);
showMessage(messageDivs.signup, `Success! A verification email has been sent to ${email}. You can now log in.`, 'success');
} else {
await userCredential.user.delete();
showMessage(messageDivs.signup, 'Failed to create user record. Please try again.');
}
} catch (error) {
let msg = 'An unknown error occurred.';
if (error.code === 'auth/operation-not-allowed') {
msg = 'Email/Password sign-in is not enabled in your Firebase project settings. Please check your console.';
} else if (error.code === 'auth/email-already-in-use') {
msg = 'This email is already in use. If you used a social provider, please sign in with that instead.';
} else if (error.code === 'auth/invalid-email') {
msg = 'The email address is not valid.';
} else if (error.code === 'auth/weak-password') {
// This catch block handles residual weak password errors if the server check is stricter than client check
msg = 'Password is too weak. Please ensure it meets all complexity requirements.';
}
showMessage(messageDivs.signup, msg);
console.error("Firebase Auth Error:", error.code, error.message);
}
});
// --- Social Authentication Handler (Unified for Login & Signup) ---
const handleSocialAuth = async (provider) => {
try {
const result = await signInWithPopup(auth, provider);
const user = result.user;
const additionalInfo = getAdditionalUserInfo(result);
const userDoc = await getDoc(getUserDocRef(user.uid));
const providerName = provider.providerId.split('.')[0];
if (userDoc.exists()) {
// User exists -> Log them in
// This will trigger handleSuccessfulLogin, which has the beta check.
await handleSuccessfulLogin(user);
} else {
// New user -> Create account
let rawUsername = additionalInfo?.username || user.displayName || user.email.split('@')[0] || 'User';
let username = rawUsername.replace(/[^a-zA-Z0-9]/g, '').slice(0, 16);
if (username.length < 6) username = `User${user.uid.substring(0, 8)}`;
if (await checkProfanity(username)) username = `User${user.uid.substring(0, 8)}`;
let finalUsername = username;
let counter = 1;
while (await isUsernameTaken(finalUsername)) {
finalUsername = `${username.slice(0, 14)}_${counter++}`;
}
const docCreated = await createUserDocument(user, providerName, finalUsername);
if (docCreated) {
// Since this is a new social user, they are already "verified"
// and have passed the beta check. Log them in.
await setPersistence(auth, browserLocalPersistence);
navigateToDashboard();
} else {
throw new Error('Failed to create user document for social auth.');
}
}
} catch (error) {
let msg = `A problem occurred during social sign-in.`;
if (error.code === 'auth/account-exists-with-different-credential') {
msg = 'An account with this email already exists using a different sign-in method. Please sign in with the provider you originally used.';
} else if (error.code === 'auth/popup-closed-by-user') {
return; // User cancelled, do nothing.
}
// Show error on the currently visible panel
const visibleMessageDiv = messageDivs.login.offsetParent ? messageDivs.login : messageDivs.username;
showMessage(visibleMessageDiv, msg);
}
};
document.getElementById('googleAuthBtn').addEventListener('click', () => handleSocialAuth(new GoogleAuthProvider()));
document.getElementById('githubAuthBtn').addEventListener('click', () => handleSocialAuth(new GithubAuthProvider()));
document.getElementById('twitterAuthBtn').addEventListener('click', () => handleSocialAuth(new TwitterAuthProvider()));
document.getElementById('microsoftAuthBtn').addEventListener('click', () => handleSocialAuth(new OAuthProvider('microsoft.com')));
});
</script>
</body>
</html>