const admin = require('firebase-admin'); const { getAuth } = require('firebase-admin/auth'); // Initialize Firebase Admin if not already initialized try { const apps = admin.getApps ? admin.getApps() : (admin.apps || []); if (apps.length === 0) { admin.initializeApp({ projectId: process.env.FIREBASE_PROJECT_ID || process.env.GCLOUD_PROJECT || 'motoapp-d22e0' }); } } catch (e) { console.warn('Firebase admin initialization failed:', e.message); } /** * Express middleware to verify Firebase ID tokens. */ async function requireAuth(req, res, next) { const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { return res.status(401).json({ error: 'authenticationRequired', message: 'Missing or malformed Authorization header' }); } const idToken = authHeader.split('Bearer ')[1]; try { const auth = typeof admin.auth === 'function' ? admin.auth() : getAuth(); const decodedToken = await auth.verifyIdToken(idToken); req.user = decodedToken; next(); } catch (error) { console.error('Error verifying Firebase ID token:', error.message); let errorCode = 'invalidToken'; if (error.code === 'auth/id-token-expired') errorCode = 'expiredToken'; return res.status(401).json({ error: errorCode, message: 'Invalid or expired Firebase ID token' }); } } module.exports = { requireAuth, admin };