-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathauth.js
More file actions
477 lines (394 loc) · 12.5 KB
/
auth.js
File metadata and controls
477 lines (394 loc) · 12.5 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
function getMainPagePath(fileName) {
const normalizedPath = window.location.pathname.replace(/\\/g, "/");
const isGuidelinesPage = normalizedPath.includes("/mini-project-guidelines/");
return isGuidelinesPage ? `../${fileName}` : fileName;
}
const USER_STORAGE_KEY = "user";
const AUTH_SESSION_KEY = "authSession";
const PASSWORD_RESET_EMAIL_KEY = "passwordResetEmail";
const SESSION_DURATION_MS = 2 * 60 * 60 * 1000;
const HASH_ITERATIONS = 120000;
function normalizeEmail(email) {
return String(email || "").trim().toLowerCase();
}
function sanitizeUsername(username) {
return String(username || "").replace(/[^a-zA-Z0-9 _-]/g, "").trim();
}
function isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
function validatePasswordStrength(password) {
if (password.length < 10) {
return "Password must be at least 10 characters long.";
}
if (!/[A-Z]/.test(password)) {
return "Password must include at least one uppercase letter.";
}
if (!/[a-z]/.test(password)) {
return "Password must include at least one lowercase letter.";
}
if (!/[0-9]/.test(password)) {
return "Password must include at least one number.";
}
if (!/[^a-zA-Z0-9]/.test(password)) {
return "Password must include at least one special character.";
}
return "";
}
function bufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let i = 0; i < bytes.length; i += 1) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function base64ToBytes(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function safeParseJSON(value) {
if (!value) {
return null;
}
try {
return JSON.parse(value);
} catch (_error) {
return null;
}
}
function getStoredUser() {
return safeParseJSON(localStorage.getItem(USER_STORAGE_KEY));
}
function storeUser(userRecord) {
localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(userRecord));
}
function setPasswordResetEmail(email) {
localStorage.setItem(PASSWORD_RESET_EMAIL_KEY, normalizeEmail(email));
}
function getPasswordResetEmail() {
return normalizeEmail(localStorage.getItem(PASSWORD_RESET_EMAIL_KEY));
}
function clearPasswordResetEmail() {
localStorage.removeItem(PASSWORD_RESET_EMAIL_KEY);
}
async function derivePasswordHash(password, saltBytes, iterations) {
const encoder = new TextEncoder();
const passwordKey = await crypto.subtle.importKey(
"raw",
encoder.encode(password),
"PBKDF2",
false,
["deriveBits"]
);
const bits = await crypto.subtle.deriveBits(
{
name: "PBKDF2",
hash: "SHA-256",
salt: saltBytes,
iterations,
},
passwordKey,
256
);
return bufferToBase64(bits);
}
async function hashPassword(password, existingSalt, existingIterations) {
if (!window.crypto || !window.crypto.subtle) {
throw new Error("Secure crypto APIs are unavailable in this browser.");
}
const iterations = existingIterations || HASH_ITERATIONS;
let saltBytes;
if (existingSalt) {
saltBytes = base64ToBytes(existingSalt);
} else {
saltBytes = crypto.getRandomValues(new Uint8Array(16));
}
const hash = await derivePasswordHash(password, saltBytes, iterations);
return {
hash,
salt: bufferToBase64(saltBytes),
iterations,
};
}
function createSession(userRecord) {
const session = {
username: userRecord.username,
email: userRecord.email,
expiresAt: Date.now() + SESSION_DURATION_MS,
};
sessionStorage.setItem(AUTH_SESSION_KEY, JSON.stringify(session));
}
function clearSession() {
sessionStorage.removeItem(AUTH_SESSION_KEY);
}
function getSession() {
const session = safeParseJSON(sessionStorage.getItem(AUTH_SESSION_KEY));
if (!session || !session.expiresAt) {
return null;
}
if (Date.now() > Number(session.expiresAt)) {
clearSession();
return null;
}
return session;
}
function hasActiveSession() {
return Boolean(getSession());
}
async function verifyHashedPassword(password, userRecord) {
if (!userRecord || !userRecord.passwordHash || !userRecord.salt) {
return false;
}
const result = await hashPassword(
password,
userRecord.salt,
Number(userRecord.iterations) || HASH_ITERATIONS
);
return result.hash === userRecord.passwordHash;
}
async function migrateLegacyUserIfNeeded(userRecord, passwordAttempt) {
if (!userRecord || !userRecord.password || userRecord.passwordHash) {
return userRecord;
}
if (userRecord.password !== passwordAttempt) {
return null;
}
const hashed = await hashPassword(passwordAttempt);
const migrated = {
version: 2,
username: userRecord.username,
email: normalizeEmail(userRecord.email),
passwordHash: hashed.hash,
salt: hashed.salt,
iterations: hashed.iterations,
createdAt: userRecord.createdAt || new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
storeUser(migrated);
return migrated;
}
/* Password toggle */
function togglePassword(id, icon) {
const input = document.getElementById(id);
if (!input || !icon) {
return;
}
if (input.type === "password") {
input.type = "text";
icon.textContent = "\u{1F648}";
} else {
input.type = "password";
icon.textContent = "\u{1F441}";
}
}
/* Sign up */
const signupForm = document.getElementById("signupForm");
if (signupForm) {
signupForm.addEventListener("submit", async (event) => {
event.preventDefault();
const usernameInput = document.getElementById("username").value;
const emailInput = document.getElementById("email").value;
const password = document.getElementById("password").value;
const confirmPassword = document.getElementById("confirmPassword").value;
const error = document.getElementById("signupError");
error.textContent = "";
const username = sanitizeUsername(usernameInput);
const email = normalizeEmail(emailInput);
if (!/^[a-zA-Z0-9 _-]{3,30}$/.test(username)) {
error.textContent =
"Username must be 3-30 characters and use only letters, numbers, spaces, underscore, or hyphen.";
return;
}
if (!isValidEmail(email)) {
error.textContent = "Please enter a valid email address.";
return;
}
const passwordMessage = validatePasswordStrength(password);
if (passwordMessage) {
error.textContent = passwordMessage;
return;
}
if (password !== confirmPassword) {
error.textContent = "Passwords do not match!";
return;
}
try {
const hashed = await hashPassword(password);
const user = {
version: 2,
username,
email,
passwordHash: hashed.hash,
salt: hashed.salt,
iterations: hashed.iterations,
createdAt: new Date().toISOString(),
};
storeUser(user);
} catch (_error) {
error.textContent =
"Unable to create account securely in this browser. Please try another browser.";
return;
}
// if username already exists
const userExists = users.some(user => user.email === email);
if (userExists) {
error.textContent = "User already exists!";
return;
}
// new user
const newUser = { username, email, password };
users.push(newUser);
localStorage.setItem("users", JSON.stringify(users));
localStorage.setItem("loggedIn", "true");
localStorage.setItem("loggedInUser", username);
window.location.href = getMainPagePath("index.html");
});
}
/* Sign in */
const signinForm = document.getElementById("signinForm");
if (signinForm) {
signinForm.addEventListener("submit", async (event) => {
event.preventDefault();
const email = normalizeEmail(document.getElementById("loginEmail").value);
const password = document.getElementById("loginPassword").value;
const error = document.getElementById("loginError");
error.textContent = "";
if (!isValidEmail(email)) {
error.textContent = "Please enter a valid email address.";
return;
}
const storedUser = getStoredUser();
if (!storedUser) {
error.textContent = "Invalid email or password";
return;
}
try {
const migratedUser = await migrateLegacyUserIfNeeded(storedUser, password);
const userToVerify = migratedUser || storedUser;
const isEmailMatch = normalizeEmail(userToVerify.email) === email;
const isPasswordMatch = await verifyHashedPassword(password, userToVerify);
if (isEmailMatch && isPasswordMatch) {
createSession(userToVerify);
window.location.href = getMainPagePath("index.html");
return;
}
error.textContent = "Invalid email or password";
} catch (_error) {
error.textContent = "Login failed. Please try again.";
}
});
}
/* Forgot password */
const forgotPasswordForm = document.getElementById("forgotPasswordForm");
if (forgotPasswordForm) {
forgotPasswordForm.addEventListener("submit", (event) => {
event.preventDefault();
const email = normalizeEmail(document.getElementById("resetEmail").value);
const error = document.getElementById("forgotError");
const success = document.getElementById("forgotSuccess");
const resetLinkArea = document.getElementById("resetLinkArea");
const storedUser = getStoredUser();
error.textContent = "";
success.textContent = "";
resetLinkArea.hidden = true;
if (!isValidEmail(email)) {
error.textContent = "Please enter a valid email address.";
return;
}
if (!storedUser || normalizeEmail(storedUser.email) !== email) {
error.textContent = "Email not found!";
clearPasswordResetEmail();
return;
}
setPasswordResetEmail(email);
success.textContent = "Reset link generated (demo). Click the link below to continue.";
resetLinkArea.hidden = false;
});
}
/* Reset password */
const resetPasswordForm = document.getElementById("resetPasswordForm");
if (resetPasswordForm) {
resetPasswordForm.addEventListener("submit", async (event) => {
event.preventDefault();
const newPassword = document.getElementById("newPassword").value;
const confirmNewPassword = document.getElementById("confirmNewPassword").value;
const error = document.getElementById("resetError");
const success = document.getElementById("resetSuccess");
error.textContent = "";
success.textContent = "";
const resetEmail = getPasswordResetEmail();
if (!resetEmail) {
error.textContent = "Reset session expired. Start from Forgot Password again.";
return;
}
const passwordMessage = validatePasswordStrength(newPassword);
if (passwordMessage) {
error.textContent = passwordMessage;
return;
}
if (newPassword !== confirmNewPassword) {
error.textContent = "Passwords do not match!";
return;
}
const storedUser = getStoredUser();
if (!storedUser || normalizeEmail(storedUser.email) !== resetEmail) {
error.textContent = "No matching user found for password reset.";
clearPasswordResetEmail();
return;
}
try {
const hashed = await hashPassword(newPassword);
const updatedUser = {
...storedUser,
version: 2,
email: resetEmail,
passwordHash: hashed.hash,
salt: hashed.salt,
iterations: hashed.iterations,
updatedAt: new Date().toISOString(),
};
delete updatedUser.password;
storeUser(updatedUser);
clearPasswordResetEmail();
clearSession();
success.textContent = "Password updated successfully. Redirecting to Sign In...";
setTimeout(() => {
window.location.href = getMainPagePath("signin.html");
}, 1200);
} catch (_error) {
error.textContent = "Unable to reset password right now. Please try again.";
}
});
}
/* Session check */
function checkAuth() {
if (!hasActiveSession()) {
window.location.href = getMainPagePath("signin.html");
}
}
/* Show username in navbar */
function showLoggedInUser() {
const session = getSession();
const userElement = document.getElementById("navUsername");
if (userElement && session && session.username) {
userElement.textContent = session.username;
}
}
function redirectIfAuthenticated() {
if (hasActiveSession()) {
window.location.href = getMainPagePath("index.html");
}
}
/* Logout */
function logout() {
clearSession();
window.location.href = getMainPagePath("signin.html");
}
// Remove outdated keys from older auth versions.
localStorage.removeItem("loggedIn");
localStorage.removeItem("loggedInUser");