-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
664 lines (574 loc) · 20.7 KB
/
auth.js
File metadata and controls
664 lines (574 loc) · 20.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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
// Authentication functionality
$(document).ready(function() {
// Initialize translations
updateInterfaceLanguage();
// Check if user is already logged in
checkAuthStatus();
// Handle sign in form submission
$('#signInForm').on('submit', function(e) {
e.preventDefault();
const email = $('#email').val();
const password = $('#password').val();
// Simple validation
if (!email || !password) {
showError('Please fill in all fields');
return;
}
// In a real application, you would send this to a server
// For demo purposes, we'll use localStorage
const users = JSON.parse(localStorage.getItem('users') || '[]');
const user = users.find(u => u.email === email && u.password === password);
if (user) {
// Store auth status in localStorage
localStorage.setItem('currentUser', JSON.stringify({
id: user.id,
username: user.username,
email: user.email,
preferredLanguage: user.preferredLanguage || 'en'
}));
// Redirect to home page
window.location.href = 'index.html';
} else {
showError('Invalid email or password');
}
});
// Handle registration form submission
$('#registerForm').on('submit', function(e) {
e.preventDefault();
const username = $('#username').val();
const email = $('#email').val();
const password = $('#password').val();
const confirmPassword = $('#confirmPassword').val();
// Simple validation
if (!username || !email || !password || !confirmPassword) {
showError('Please fill in all fields');
return;
}
if (password !== confirmPassword) {
showError('Passwords do not match');
return;
}
// In a real application, you would send this to a server
// For demo purposes, we'll use localStorage
const users = JSON.parse(localStorage.getItem('users') || '[]');
// Check if email already exists
if (users.some(u => u.email === email)) {
showError('Email already in use');
return;
}
// Create new user
const newUser = {
id: Date.now().toString(),
username,
email,
password,
preferredLanguage: 'en',
createdAt: new Date().toISOString()
};
users.push(newUser);
localStorage.setItem('users', JSON.stringify(users));
// Store auth status in localStorage
localStorage.setItem('currentUser', JSON.stringify({
id: newUser.id,
username: newUser.username,
email: newUser.email,
preferredLanguage: newUser.preferredLanguage
}));
// Redirect to home page
window.location.href = 'index.html';
});
// Handle language selection
$('#languageSelect').on('change', function() {
const selectedLanguage = $(this).val();
setLanguage(selectedLanguage);
// Update user's preferred language if logged in
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser) {
currentUser.preferredLanguage = selectedLanguage;
localStorage.setItem('currentUser', JSON.stringify(currentUser));
// Update in users array
const users = JSON.parse(localStorage.getItem('users') || '[]');
const userIndex = users.findIndex(u => u.id === currentUser.id);
if (userIndex !== -1) {
users[userIndex].preferredLanguage = selectedLanguage;
localStorage.setItem('users', JSON.stringify(users));
}
}
});
});
// Check if user is logged in
function checkAuthStatus() {
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser) {
// User is logged in
updateNavForLoggedInUser(currentUser);
}
}
// Update navigation for logged in user
function updateNavForLoggedInUser(user) {
// This function will be called on all pages to update the navigation
const signInLink = $('#signInLink');
if (signInLink.length) {
signInLink.html(`<span data-i18n="profile">${user.username}</span>`);
signInLink.attr('href', '#');
signInLink.after('<li><a href="#" id="logoutLink" data-i18n="logout">Logout</a></li>');
// Add logout functionality
$('#logoutLink').on('click', function(e) {
e.preventDefault();
localStorage.removeItem('currentUser');
window.location.reload();
});
}
}
// Show error message
function showError(message) {
// Check if error element exists, if not create it
let errorElement = $('.error-message');
if (errorElement.length === 0) {
errorElement = $('<div class="error-message"></div>');
$('.auth-container form').prepend(errorElement);
}
errorElement.text(message).show();
// Hide after 5 seconds
setTimeout(() => {
errorElement.hide();
}, 5000);
}
// Show success message
function showSuccess(message) {
// Check if success element exists, if not create it
let successElement = $('.success-message');
if (successElement.length === 0) {
successElement = $('<div class="success-message"></div>');
$('.auth-container form').prepend(successElement);
}
successElement.text(message).show();
// Hide after 5 seconds
setTimeout(() => {
successElement.hide();
}, 5000);
}
// Update interface language
function updateInterfaceLanguage() {
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
const currentLanguage = localStorage.getItem('preferredLanguage') || 'en';
if (currentUser && currentUser.preferredLanguage) {
// User is logged in, use their preferred language
setLanguage(currentUser.preferredLanguage);
} else {
// User is not logged in or no preferred language, use current/default language
setLanguage(currentLanguage);
}
}
// Set interface language
function setLanguage(language) {
// Update language in localStorage
localStorage.setItem('preferredLanguage', language);
// Update language selector if it exists
const languageSelect = $('#languageSelect');
if (languageSelect.length) {
languageSelect.val(language);
}
// Update interface elements
updateInterfaceElements(language);
}
// Update interface elements based on language
function updateInterfaceElements(language) {
// Update language in localStorage
localStorage.setItem('preferredLanguage', language);
}
/**
* Social Authentication Module
* Handles authentication with various social providers
*/
// Configuration for OAuth providers
const oauthConfig = {
facebook: {
clientId: process.env.FACEBOOK_CLIENT_ID,
redirectUri: `${window.location.origin}/oauth-callback.html`,
scope: 'email',
authUrl: 'https://www.facebook.com/v12.0/dialog/oauth'
},
google: {
clientId: process.env.GOOGLE_CLIENT_ID,
redirectUri: `${window.location.origin}/oauth-callback.html`,
scope: 'email profile',
authUrl: 'https://accounts.google.com/o/oauth2/v2/auth'
},
discord: {
clientId: process.env.DISCORD_CLIENT_ID,
redirectUri: `${window.location.origin}/oauth-callback.html`,
scope: 'identify email guilds',
authUrl: 'https://discord.com/api/oauth2/authorize'
}
};
// Initialize social authentication
document.addEventListener('DOMContentLoaded', function() {
// Initialize social login buttons
initSocialButtons();
// Check if we're on the OAuth callback page
if (window.location.pathname.includes('oauth-callback')) {
handleAuthCallback();
}
});
/**
* Initialize social login buttons with event listeners
*/
function initSocialButtons() {
// Get all social login buttons
const socialButtons = {
google: document.querySelector('.google-btn'),
discord: document.querySelector('.discord-btn'),
apple: document.querySelector('.apple-btn'),
twitter: document.querySelector('.twitter-btn')
};
// Add event listeners to each button
Object.entries(socialButtons).forEach(([provider, button]) => {
if (button) {
button.addEventListener('click', function(e) {
e.preventDefault();
initiateOAuthFlow(provider);
});
}
});
}
/**
* Generate a random state parameter for OAuth security
*/
function generateState() {
const array = new Uint8Array(16);
window.crypto.getRandomValues(array);
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}
/**
* Initiate the OAuth flow for the specified provider
* @param {string} provider - The OAuth provider (google, discord, etc.)
*/
function initiateOAuthFlow(provider) {
try {
// Check if provider config exists
if (!oauthConfig[provider]) {
throw new Error(`Provider ${provider} is not configured`);
}
// Generate and store state parameter to prevent CSRF attacks
const state = generateState();
localStorage.setItem('oauth_state', state);
localStorage.setItem('oauth_provider', provider);
// Build the authorization URL
const config = oauthConfig[provider];
const authUrl = new URL(config.authUrl);
// Add query parameters
authUrl.searchParams.append('client_id', config.clientId);
authUrl.searchParams.append('redirect_uri', config.redirectUri);
authUrl.searchParams.append('response_type', 'code');
authUrl.searchParams.append('scope', config.scope);
authUrl.searchParams.append('state', state);
// Add provider-specific parameters
if (provider === 'google') {
authUrl.searchParams.append('prompt', 'select_account');
} else if (provider === 'twitter') {
authUrl.searchParams.append('code_challenge_method', 'S256');
// In a real implementation, you'd generate a code challenge
const codeChallenge = generateCodeChallenge();
authUrl.searchParams.append('code_challenge', codeChallenge);
localStorage.setItem('code_verifier', codeChallenge); // Simplified for example
}
// Redirect to the authorization URL
console.log(`Initiating ${provider} OAuth flow`);
window.location.href = authUrl.toString();
} catch (error) {
console.error(`OAuth initialization error for ${provider}:`, error);
showAuthError(`Failed to initialize ${provider} login: ${error.message}`);
}
}
/**
* Generate a code challenge for PKCE (Simplified)
* In a real implementation, this would use crypto APIs properly
*/
function generateCodeChallenge() {
const verifier = generateState() + generateState();
// In a real implementation, you'd hash this with SHA-256
return verifier;
}
/**
* Handle the OAuth callback after provider redirects back
*/
function handleAuthCallback() {
try {
// Get URL parameters
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
const error = urlParams.get('error');
// Check for errors from OAuth provider
if (error) {
throw new Error(`Provider returned error: ${error}`);
}
// Verify state parameter to prevent CSRF attacks
const storedState = localStorage.getItem('oauth_state');
if (!state || state !== storedState) {
throw new Error('Invalid state parameter');
}
// Get the provider from localStorage
const provider = localStorage.getItem('oauth_provider');
if (!provider) {
throw new Error('No provider information found');
}
// Clear OAuth state data
localStorage.removeItem('oauth_state');
localStorage.removeItem('oauth_provider');
// Exchange the authorization code for tokens
exchangeCodeForTokens(code, provider);
} catch (error) {
console.error('OAuth callback error:', error);
showAuthError(`Authentication failed: ${error.message}`);
// Redirect back to login page after a delay
setTimeout(() => {
window.location.href = 'signin.html';
}, 3000);
}
}
/**
* Exchange authorization code for access and ID tokens
* @param {string} code - The authorization code from OAuth provider
* @param {string} provider - The OAuth provider name
*/
function exchangeCodeForTokens(code, provider) {
// Show loading indicator
showLoadingIndicator();
// In a real implementation, this would be a server-side call
// For security, token exchange should happen on your backend
const tokenEndpoint = '/api/auth/token';
fetch(tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
code,
provider,
redirectUri: oauthConfig[provider].redirectUri,
// Include code_verifier for PKCE if needed
codeVerifier: localStorage.getItem('code_verifier')
})
})
.then(response => {
if (!response.ok) {
return response.json().then(data => {
throw new Error(data.message || 'Token exchange failed');
});
}
return response.json();
})
.then(data => {
// Store authentication data
storeAuthData(data);
// Get user profile data
return fetchUserProfile(data.accessToken, provider);
})
.then(userData => {
// Store user profile data
storeUserData(userData);
// Show success message
showAuthSuccess(`Successfully signed in with ${provider}`);
// Redirect to dashboard or home page
setTimeout(() => {
window.location.href = 'dashboard.html';
}, 1000);
})
.catch(error => {
console.error('Token exchange error:', error);
showAuthError(`Authentication failed: ${error.message}`);
// Redirect back to login page after a delay
setTimeout(() => {
window.location.href = 'signin.html';
}, 3000);
})
.finally(() => {
// Hide loading indicator
hideLoadingIndicator();
// Clean up any remaining OAuth data
localStorage.removeItem('code_verifier');
});
}
/**
* Fetch user profile data from the provider's API
* @param {string} accessToken - The OAuth access token
* @param {string} provider - The OAuth provider name
* @returns {Promise<Object>} - User profile data
*/
function fetchUserProfile(accessToken, provider) {
// Define API endpoints for each provider
const profileEndpoints = {
google: 'https://www.googleapis.com/oauth2/v3/userinfo',
discord: 'https://discord.com/api/users/@me',
facebook: 'https://graph.facebook.com/v13.0/me',
};
// Get the appropriate endpoint
const endpoint = profileEndpoints[provider];
// Make the API request
return fetch(endpoint, {
headers: {
'Authorization': `Bearer ${accessToken}`
}
})
.then(response => {
if (!response.ok) {
return response.json().then(data => {
throw new Error(data.message || 'Failed to fetch user profile');
});
}
return response.json();
})
.then(data => {
// Normalize user data based on provider
return normalizeUserData(data, provider);
});
}
/**
* Normalize user data from different providers into a standard format
* @param {Object} data - Raw user data from provider
* @param {string} provider - The OAuth provider name
* @returns {Object} - Normalized user data
*/
function normalizeUserData(data, provider) {
// Create a standardized user object
const user = {
id: '',
name: '',
email: '',
picture: '',
provider: provider
};
// Map provider-specific fields to our standard format
switch (provider) {
case 'google':
user.id = data.sub;
user.name = data.name;
user.email = data.email;
user.picture = data.picture;
break;
case 'discord':
user.id = data.id;
user.name = data.username;
user.email = data.email;
user.picture = data.avatar
? `https://cdn.discordapp.com/avatars/${data.id}/${data.avatar}.png`
: null;
break;
case "facebook":
user.id = data.id;
user.name = data.name;
user.email = data.email;
user.picture = data.picture.data.url;
break;
}
return user;
}
/**
* Store authentication data securely
* @param {Object} data - Authentication data including tokens
*/
function storeAuthData(data) {
// In a production app, consider using more secure storage methods
localStorage.setItem('auth_token', data.accessToken);
localStorage.setItem('refresh_token', data.refreshToken);
localStorage.setItem('token_expiry', Date.now() + (data.expiresIn * 1000));
}
/**
* Store user profile data
* @param {Object} userData - User profile data
*/
function storeUserData(userData) {
localStorage.setItem('user_data', JSON.stringify(userData));
}
/**
* Show authentication error message
* @param {string} message - Error message to display
*/
function showAuthError(message) {
// Create error element if it doesn't exist
let errorElement = document.getElementById('auth-error');
if (!errorElement) {
errorElement = document.createElement('div');
errorElement.id = 'auth-error';
errorElement.className = 'auth-message error';
document.body.appendChild(errorElement);
}
errorElement.textContent = message;
errorElement.style.display = 'block';
}
/**
* Show authentication success message
* @param {string} message - Success message to display
*/
function showAuthSuccess(message) {
// Create success element if it doesn't exist
let successElement = document.getElementById('auth-success');
if (!successElement) {
successElement = document.createElement('div');
successElement.id = 'auth-success';
successElement.className = 'auth-message success';
document.body.appendChild(successElement);
}
successElement.textContent = message;
successElement.style.display = 'block';
}
/**
* Show loading indicator during authentication
*/
function showLoadingIndicator() {
// Create loading element if it doesn't exist
let loadingElement = document.getElementById('auth-loading');
if (!loadingElement) {
loadingElement = document.createElement('div');
loadingElement.id = 'auth-loading';
loadingElement.className = 'auth-loading';
loadingElement.innerHTML = '<div class="spinner"></div><p>Authenticating...</p>';
document.body.appendChild(loadingElement);
}
loadingElement.style.display = 'flex';
}
/**
* Hide loading indicator
*/
function hideLoadingIndicator() {
const loadingElement = document.getElementById('auth-loading');
if (loadingElement) {
loadingElement.style.display = 'none';
}
}
/**
* Check if user is authenticated
* @returns {boolean} - Whether user is authenticated
*/
function isAuthenticated() {
const token = localStorage.getItem('auth_token');
const expiry = localStorage.getItem('token_expiry');
if (!token || !expiry) {
return false;
}
// Check if token is expired
return Date.now() < parseInt(expiry, 10);
}
/**
* Sign out the current user
*/
function signOut() {
// Clear all authentication data
localStorage.removeItem('auth_token');
localStorage.removeItem('refresh_token');
localStorage.removeItem('token_expiry');
localStorage.removeItem('user_data');
// Redirect to sign in page
window.location.href = 'signin.html';
}
// Export functions for use in other scripts
window.socialAuth = {
signOut,
isAuthenticated,
getCurrentUser: () => {
const userData = localStorage.getItem('user_data');
return userData ? JSON.parse(userData) : null;
}
};