Skip to content

Commit 1bb25f7

Browse files
author
Archith
committed
Fix authentication flow and document Firebase SDK security
- Fixed async/await handling in login button click handler - Added getCurrentSession() method for backward compatibility - Improved error handling and user feedback during login - Added comprehensive security documentation to Firebase SDK - Clarified that Firebase API keys are designed to be public - Security is enforced through database rules, not API key secrecy
1 parent ce51d9c commit 1bb25f7

File tree

4 files changed

+110
-24
lines changed

4 files changed

+110
-24
lines changed

api/auth/login.js

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,33 @@ module.exports = async (req, res) => {
2626
return res.status(405).json({ error: 'Method not allowed' });
2727
}
2828

29-
const { email, password } = req.body;
29+
// Parse body if it's a string (Vercel sometimes doesn't parse JSON automatically)
30+
let body = req.body;
31+
if (typeof body === 'string') {
32+
try {
33+
body = JSON.parse(body);
34+
} catch (e) {
35+
return res.status(400).json({ error: 'Invalid JSON in request body' });
36+
}
37+
}
38+
39+
// Debug logging (remove in production)
40+
console.log('Request body type:', typeof req.body);
41+
console.log('Request body:', req.body);
42+
console.log('Parsed body:', body);
43+
44+
const { email, password } = body || {};
3045

3146
if (!email || !password) {
32-
return res.status(400).json({ error: 'Email and password required' });
47+
return res.status(400).json({
48+
error: 'Email and password required',
49+
debug: process.env.NODE_ENV !== 'production' ? {
50+
bodyType: typeof req.body,
51+
hasBody: !!req.body,
52+
hasEmail: !!email,
53+
hasPassword: !!password
54+
} : undefined
55+
});
3356
}
3457

3558
try {

lib/firebase-sdk.js

Lines changed: 50 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,58 @@
1-
// Initialize Firebase
1+
/**
2+
* Firebase SDK Configuration
3+
*
4+
* SECURITY NOTE:
5+
* - Firebase API keys are designed to be public and included in client-side code
6+
* - Security is enforced through Firebase Security Rules (database.rules.secure.json)
7+
* - These keys only identify your project, they don't grant access
8+
* - Access control is managed by:
9+
* 1. Database Security Rules (configured in Firebase Console)
10+
* 2. Authentication (handled by our backend API)
11+
* 3. CORS settings and domain restrictions
12+
*
13+
* For additional security:
14+
* - Database rules restrict access to authenticated users only
15+
* - Admin functions require JWT tokens from our backend
16+
* - Consider enabling App Check for additional client verification
17+
*/
18+
19+
// Initialize Firebase with public configuration
20+
// These are CLIENT-SIDE keys that are safe to expose
221
var config = {
322
apiKey: "AIzaSyDaTXD54QykZ7IIT8Ji9mZBqxhijRKLd3U",
423
authDomain: "sneakers-688b6.firebaseapp.com",
524
databaseURL: "https://sneakers-688b6.firebaseio.com",
625
storageBucket: "sneakers-688b6.appspot.com",
7-
messagingSenderId: "553327129273"
26+
messagingSenderId: "553327129273",
27+
projectId: "sneakers-688b6"
828
};
929

10-
console.log('🔥 Initializing Firebase with config:', config.databaseURL);
11-
firebase.initializeApp(config);
30+
// Initialize Firebase
31+
try {
32+
firebase.initializeApp(config);
33+
console.log('✅ Firebase initialized');
34+
35+
// Monitor connection status
36+
firebase.database().ref('.info/connected').on('value', function(snapshot) {
37+
if (snapshot.val() === true) {
38+
console.log('✅ Firebase connected');
39+
} else {
40+
console.warn('⚠️ Firebase disconnected - check your internet connection');
41+
}
42+
});
43+
} catch (error) {
44+
console.error('❌ Firebase initialization error:', error);
45+
}
1246

13-
// Test Firebase connection
14-
firebase.database().ref('.info/connected').on('value', function(snapshot) {
15-
if (snapshot.val() === true) {
16-
console.log('✅ Firebase connected successfully!');
17-
} else {
18-
console.log('⚠️ Firebase disconnected');
19-
}
20-
});
47+
// Security reminder for developers
48+
if (window.location.hostname === 'localhost') {
49+
console.info(
50+
'%c⚠️ Security Reminder',
51+
'background: yellow; color: black; padding: 5px;',
52+
'\nFirebase config is public by design. Security is enforced through:\n' +
53+
'1. Database Security Rules (database.rules.secure.json)\n' +
54+
'2. Backend authentication (Vercel API)\n' +
55+
'3. Never store sensitive data in client-side code\n' +
56+
'4. Use environment variables for server-side secrets only'
57+
);
58+
}

scripts/app.js

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -98,19 +98,33 @@
9898
});
9999

100100
// Login
101-
adminLoginBtn.addEventListener('click', function() {
101+
adminLoginBtn.addEventListener('click', async function() {
102102
const email = adminEmail.value.trim();
103103
const password = adminPassword.value;
104104

105-
const result = Auth.loginAdmin(email, password);
106-
107-
if (result.success) {
108-
document.getElementById('adminLoginModal').style.display = 'none';
109-
document.getElementById('adminDashboardModal').style.display = 'flex';
110-
setupAdminDashboard();
111-
} else {
112-
loginError.textContent = result.error;
105+
// Show loading state
106+
adminLoginBtn.disabled = true;
107+
adminLoginBtn.textContent = 'Logging in...';
108+
loginError.style.display = 'none';
109+
110+
try {
111+
const result = await Auth.loginAdmin(email, password);
112+
113+
if (result.success) {
114+
document.getElementById('adminLoginModal').style.display = 'none';
115+
document.getElementById('adminDashboardModal').style.display = 'flex';
116+
setupAdminDashboard();
117+
} else {
118+
loginError.textContent = result.error;
119+
loginError.style.display = 'block';
120+
}
121+
} catch (error) {
122+
loginError.textContent = 'Login failed. Please try again.';
113123
loginError.style.display = 'block';
124+
} finally {
125+
// Reset button state
126+
adminLoginBtn.disabled = false;
127+
adminLoginBtn.textContent = 'Login';
114128
}
115129
});
116130

scripts/auth-api.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,10 @@ const Auth = (function() {
102102

103103
return { success: false, error: data.error || 'Authentication failed' };
104104
} catch (error) {
105+
console.error('API login error:', error);
105106
return {
106107
success: false,
107-
error: error.message || 'Network error. Please check your connection.'
108+
error: 'Server connection failed. Please check if the API is running.'
108109
};
109110
}
110111
}
@@ -220,6 +221,15 @@ const Auth = (function() {
220221
}, 5 * 60 * 1000);
221222
}
222223

224+
// Get current session (compatibility with app.js)
225+
function getCurrentSession() {
226+
return {
227+
isAdmin: session.isAdmin,
228+
userName: session.userName,
229+
email: session.email
230+
};
231+
}
232+
223233
// Public API
224234
return {
225235
loginAdmin,
@@ -228,6 +238,7 @@ const Auth = (function() {
228238
isAdmin,
229239
isAuthenticated,
230240
getCurrentUser,
241+
getCurrentSession, // Added for compatibility
231242
getAuthHeaders,
232243
verifySession
233244
};

0 commit comments

Comments
 (0)