prof002313 / src /config /firebase.js
Huzaifa1435's picture
Full backend with fixed Firebase service account key
411b3a5
Raw History Blame Contribute Delete
8.73 kB
const admin = require('firebase-admin');
const path = require('path');
const fs = require('fs');
let db;
let firebaseReady = false;
let firebaseInitError = null;
const DB_TIMEOUT_MS = Number(process.env.DB_TIMEOUT_MS || 8000);
function withTimeout(promise, label, timeoutMs = DB_TIMEOUT_MS) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(
() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),
timeoutMs,
);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
function normalizePrivateKey(value) {
if (!value) return value;
return value.includes('\\n') ? value.replace(/\\n/g, '\n') : value;
}
function parseJson(value, label) {
try {
return JSON.parse(value);
} catch (error) {
throw new Error(`${label} is not valid JSON: ${error.message}`);
}
}
function loadServiceAccount() {
const jsonEnv = process.env.FIREBASE_SERVICE_ACCOUNT_JSON;
if (jsonEnv && jsonEnv.trim()) {
console.log('Firebase credentials source: FIREBASE_SERVICE_ACCOUNT_JSON');
return parseJson(jsonEnv, 'FIREBASE_SERVICE_ACCOUNT_JSON');
}
const b64Env =
process.env.FIREBASE_SERVICE_ACCOUNT_JSON_B64 ||
process.env.FIREBASE_SERVICE_ACCOUNT_BASE64;
if (b64Env && b64Env.trim()) {
const decoded = Buffer.from(b64Env, 'base64').toString('utf8');
console.log('Firebase credentials source: FIREBASE_SERVICE_ACCOUNT_JSON_B64');
return parseJson(decoded, 'FIREBASE_SERVICE_ACCOUNT_JSON_B64');
}
const projectId = process.env.FIREBASE_PROJECT_ID;
const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;
const privateKey = normalizePrivateKey(process.env.FIREBASE_PRIVATE_KEY);
if (projectId && clientEmail && privateKey) {
console.log('Firebase credentials source: FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY');
return {
project_id: projectId,
client_email: clientEmail,
private_key: privateKey,
};
}
let serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;
if (!serviceAccountPath) {
// Prefer backend root key first. Some projects keep an old/revoked key in src/config.
const possiblePaths = [
path.resolve(process.cwd(), './serviceAccountKey.json'),
path.resolve(__dirname, './serviceAccountKey.json'),
path.resolve(__dirname, '../config/serviceAccountKey.json'),
path.resolve(process.cwd(), './src/config/serviceAccountKey.json'),
];
for (const possiblePath of possiblePaths) {
if (fs.existsSync(possiblePath)) {
serviceAccountPath = possiblePath;
break;
}
}
}
if (serviceAccountPath && fs.existsSync(serviceAccountPath)) {
console.log(`Firebase credentials source file: ${serviceAccountPath}`);
return require(serviceAccountPath);
}
throw new Error(
[
'Firebase service account missing.',
'Set one of these in Hugging Face Secrets:',
'- FIREBASE_SERVICE_ACCOUNT_JSON',
'- FIREBASE_SERVICE_ACCOUNT_JSON_B64',
'- FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY',
].join(' '),
);
}
function createNoopSnapshot(value = null) {
return {
exists: () => Boolean(value),
val: () => value,
forEach: () => false,
};
}
function createNoopQuery() {
const query = {
once: async () => createNoopSnapshot(null),
get: async () => ({ empty: true, docs: [] }),
set: async () => undefined,
update: async () => undefined,
remove: async () => undefined,
on: () => undefined,
off: () => undefined,
orderByChild: () => query,
equalTo: () => query,
limitToLast: () => query,
limit: () => query,
where: () => query,
doc: () => query,
collection: () => query,
push: () => ({
key: `noop-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
set: async () => undefined,
update: async () => undefined,
}),
};
return query;
}
function createNoopDb() {
const root = createNoopQuery();
return {
ref: () => root,
collection: () => root,
doc: () => root,
};
}
function createNoopAuth() {
const unavailable = (method) => {
const error = new Error(`Firebase Admin is not configured. Cannot call ${method}.`);
error.code = 'auth/internal-error';
throw error;
};
return {
getUserByEmail: async () => unavailable('getUserByEmail'),
getUser: async () => unavailable('getUser'),
createUser: async () => unavailable('createUser'),
createCustomToken: async () => unavailable('createCustomToken'),
verifyIdToken: async () => unavailable('verifyIdToken'),
};
}
function createNoopMessaging() {
return {
send: async () => {
const error = new Error('Firebase messaging is not configured.');
error.code = 'messaging/unavailable';
throw error;
},
sendEachForMulticast: async () => {
const error = new Error('Firebase messaging is not configured.');
error.code = 'messaging/unavailable';
throw error;
},
};
}
function initializeFirebase() {
if (admin.apps.length) {
firebaseReady = true;
return true;
}
const serviceAccount = loadServiceAccount();
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL:
process.env.FIREBASE_DATABASE_URL ||
'https://serviceconnect-dea35-default-rtdb.firebaseio.com/',
});
firebaseReady = true;
return true;
}
try {
initializeFirebase();
console.log('Firebase Admin initialized successfully');
} catch (error) {
firebaseInitError = error;
firebaseReady = false;
console.error('Firebase initialization failed:', error.message);
}
if (firebaseReady) {
db = admin.database();
} else {
db = createNoopDb();
}
const auth = firebaseReady ? admin.auth() : createNoopAuth();
const messaging = firebaseReady ? admin.messaging() : createNoopMessaging();
async function dbGet(pathName) {
try {
const snap = await withTimeout(db.ref(pathName).once('value'), `dbGet ${pathName}`);
return snap.exists() ? snap.val() : null;
} catch (error) {
console.error(`dbGet error at ${pathName}:`, error.message);
return null;
}
}
async function dbSet(pathName, data) {
try {
await withTimeout(
db.ref(pathName).set({ ...data, _updatedAt: Date.now() }),
`dbSet ${pathName}`,
);
return true;
} catch (error) {
console.error(`dbSet error at ${pathName}:`, error.message);
return false;
}
}
async function dbUpdate(pathName, data) {
try {
await withTimeout(
db.ref(pathName).update({ ...data, _updatedAt: Date.now() }),
`dbUpdate ${pathName}`,
);
return true;
} catch (error) {
console.error(`dbUpdate error at ${pathName}:`, error.message);
return false;
}
}
async function dbPush(pathName, data) {
try {
const ref = db.ref(pathName).push();
await withTimeout(
ref.set({ ...data, id: ref.key, _createdAt: Date.now() }),
`dbPush ${pathName}`,
);
return ref.key;
} catch (error) {
console.error(`dbPush error at ${pathName}:`, error.message);
return null;
}
}
async function dbDelete(pathName) {
try {
await withTimeout(db.ref(pathName).remove(), `dbDelete ${pathName}`);
return true;
} catch (error) {
console.error(`dbDelete error at ${pathName}:`, error.message);
return false;
}
}
async function dbQuery(pathName, orderBy, equalTo, limitToLast = null) {
try {
let ref = db.ref(pathName).orderByChild(orderBy).equalTo(equalTo);
if (limitToLast) ref = ref.limitToLast(limitToLast);
const snap = await withTimeout(ref.once('value'), `dbQuery ${pathName}`);
if (!snap.exists()) return [];
const results = [];
snap.forEach((child) => results.push({ _key: child.key, ...child.val() }));
return results;
} catch (error) {
console.error(`dbQuery error at ${pathName}:`, error.message);
return [];
}
}
async function dbGetAll(pathName) {
try {
const snap = await withTimeout(db.ref(pathName).once('value'), `dbGetAll ${pathName}`);
if (!snap.exists()) return [];
const results = [];
snap.forEach((child) => results.push({ _key: child.key, ...child.val() }));
return results;
} catch (error) {
console.error(`dbGetAll error at ${pathName}:`, error.message);
return [];
}
}
function dbListen(pathName, callback) {
const ref = db.ref(pathName);
ref.on('value', (snapshot) => {
callback(snapshot.exists() ? snapshot.val() : null);
});
return () => ref.off();
}
module.exports = {
admin,
db,
auth,
messaging,
firebaseReady,
firebaseInitError,
dbGet,
dbSet,
dbUpdate,
dbPush,
dbDelete,
dbQuery,
dbGetAll,
dbListen,
};