-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
276 lines (232 loc) · 9.71 KB
/
Copy pathauth.js
File metadata and controls
276 lines (232 loc) · 9.71 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
/* ==========================================
AUTH.JS - HANDLES LOGIN & FIREBASE
========================================== */
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-analytics.js";
import { getFirestore, doc, setDoc, getDoc, updateDoc } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js";
import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, sendPasswordResetEmail, signOut, GoogleAuthProvider, signInWithPopup, updateProfile } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js";
// --- FIREBASE CONFIGURATION ---
const firebaseConfig = {
apiKey: "AIzaSyCGqzSqonv0THJ33BEZbO5PJhaHd8I-IQg",
authDomain: "a-chik-learn.firebaseapp.com",
projectId: "a-chik-learn",
storageBucket: "a-chik-learn.firebasestorage.app",
messagingSenderId: "960876567489",
appId: "1:960876567489:web:13f34adb81759a88ed6d40",
measurementId: "G-97YK0CPMXL"
};
// Initialize Services
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);
const auth = getAuth(app);
// Export for use in main file
export { app, db, auth };
/* ==========================================
UI HELPER FUNCTIONS
========================================== */
// Switch between Login/Signup/Forgot forms
window.showAuthForm = (id) => {
document.getElementById('login-form').classList.add('hidden');
document.getElementById('signup-form').classList.add('hidden');
document.getElementById('forgot-form').classList.add('hidden');
document.querySelectorAll('.error-msg').forEach(e => e.style.display = 'none');
document.getElementById(id + '-form').classList.remove('hidden');
};
function showError(el, msg) {
el.innerText = msg;
el.style.display = 'block';
}
function showLoader(show) {
const l = document.getElementById('app-loader');
if(l) l.style.display = show ? 'flex' : 'none';
}
function getFriendlyError(code) {
switch(code) {
case 'auth/invalid-credential': return "Incorrect Email or Password.";
case 'auth/invalid-email': return "Invalid email address format.";
case 'auth/user-disabled': return "This user account has been disabled.";
case 'auth/user-not-found': return "No account found with this email.";
case 'auth/wrong-password': return "Incorrect password.";
case 'auth/email-already-in-use': return "Email is already in use.";
case 'auth/weak-password': return "Password should be stronger.";
case 'auth/popup-closed-by-user': return "Sign in cancelled.";
default: return "Error: " + code;
}
}
/* ==========================================
AUTHENTICATION LOGIC
========================================== */
// 1. LOGIN
window.handleLogin = async () => {
const email = document.getElementById('login-email').value;
const pass = document.getElementById('login-pass').value;
const errBox = document.getElementById('login-error');
if(!email || !pass) { showError(errBox, "Please fill in all fields"); return; }
showLoader(true);
try {
await signInWithEmailAndPassword(auth, email, pass);
// State change listener in index.html will handle the redirect
} catch (error) {
showLoader(false);
showError(errBox, getFriendlyError(error.code));
}
};
// 2. SIGN UP
window.handleSignup = async () => {
const name = document.getElementById('signup-name').value;
const email = document.getElementById('signup-email').value;
const pass = document.getElementById('signup-pass').value;
const errBox = document.getElementById('signup-error');
if(!name || !email || !pass) { showError(errBox, "All fields are required"); return; }
if(pass.length < 6) { showError(errBox, "Password must be at least 6 characters"); return; }
showLoader(true);
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, pass);
const user = userCredential.user;
// Generate ID
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let newId = '';
for (let i = 0; i < 6; i++) newId += chars.charAt(Math.floor(Math.random() * chars.length));
await updateProfile(user, { displayName: name });
// Save to Firestore
await setDoc(doc(db, "users", user.uid), {
displayName: name,
email: email,
uniqueId: newId,
createdAt: new Date(),
highScore: 0
});
// Listener handles redirect
} catch (error) {
showLoader(false);
showError(errBox, getFriendlyError(error.code));
}
};
// 3. GOOGLE AUTH
window.handleGoogleAuth = async () => {
const provider = new GoogleAuthProvider();
showLoader(true);
try {
await signInWithPopup(auth, provider);
} catch (error) {
showLoader(false);
alert("Google Sign In Failed: " + getFriendlyError(error.code));
}
};
// 4. FORGOT PASSWORD
window.handleForgot = async () => {
const email = document.getElementById('forgot-email').value;
const errBox = document.getElementById('forgot-error');
const succBox = document.getElementById('forgot-success');
errBox.style.display = 'none';
succBox.style.display = 'none';
if(!email) { showError(errBox, "Please enter your email"); return; }
showLoader(true);
try {
await sendPasswordResetEmail(auth, email);
showLoader(false);
succBox.innerText = "Password reset link sent! Check your inbox.";
succBox.style.display = 'block';
} catch (error) {
showLoader(false);
showError(errBox, getFriendlyError(error.code));
}
};
// 5. LOGOUT
window.handleLogout = () => {
// We use a simple confirm here, or the custom alert from main app if available
const confirmLogout = () => {
signOut(auth).then(() => {
// Close drawers/modals if they exist
if(window.closeSettings) window.closeSettings();
if(window.closeDrawer) window.closeDrawer();
window.location.reload();
});
};
if(window.appAlert) {
window.appAlert("Sign Out", "Are you sure you want to log out?", confirmLogout);
} else {
if(confirm("Are you sure you want to log out?")) confirmLogout();
}
};
/* ==========================================
PROFILE MANAGEMENT
========================================== */
// Profile Upload
window.handleProfileUpload = async (input) => {
if (input.files && input.files[0]) {
const file = input.files[0];
const currentUser = auth.currentUser;
if (!currentUser) return;
const avatarBox = document.getElementById('drawerAvatarIcon');
if(avatarBox) avatarBox.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
try {
const compressedBase64 = await compressImage(file);
await setDoc(doc(db, "users", currentUser.uid), {
photoBase64: compressedBase64,
email: currentUser.email,
lastUpdated: new Date()
}, { merge: true });
if(avatarBox) avatarBox.innerHTML = `<img src="${compressedBase64}" alt="Profile">`;
} catch (error) {
console.error("Upload failed", error);
alert("Failed to upload image.");
if(avatarBox) avatarBox.innerHTML = '<i class="fas fa-user"></i>';
}
}
};
// Save Name Changes
window.saveProfileSettings = async () => {
const newName = document.getElementById('settingsName').value;
const currentUser = auth.currentUser;
if(!currentUser) return;
if(!newName) { alert("Name cannot be empty"); return; }
const btn = document.querySelector('.settings-btn');
if(btn) { btn.innerText = "Saving..."; btn.disabled = true; }
try {
await updateProfile(currentUser, { displayName: newName });
await setDoc(doc(db, "users", currentUser.uid), {
displayName: newName,
email: currentUser.email,
lastUpdated: new Date()
}, { merge: true });
document.getElementById('userNameDisplay').innerText = newName;
if(window.appAlert) window.appAlert("Success", "Profile updated successfully!");
if(window.closeSettings) window.closeSettings();
} catch(e) {
console.error("Save failed", e);
alert("Failed to update profile: " + e.message);
} finally {
if(btn) { btn.innerText = "Save Changes"; btn.disabled = false; }
}
};
// Utility: Image Compression
function compressImage(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
const img = new Image();
img.src = event.target.result;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const MAX_DIM = 500;
let width = img.width;
let height = img.height;
if (width > height) {
if (width > MAX_DIM) { height *= MAX_DIM / width; width = MAX_DIM; }
} else {
if (height > MAX_DIM) { width *= MAX_DIM / height; height = MAX_DIM; }
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
resolve(canvas.toDataURL('image/jpeg', 0.7));
};
img.onerror = (err) => reject(err);
};
reader.onerror = (err) => reject(err);
});
}