Spaces:
Paused
Paused
Create lib/firebase-admin.ts
Browse files- lib/firebase-admin.ts +43 -0
lib/firebase-admin.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import 'server-only';
|
| 2 |
+
import admin from 'firebase-admin';
|
| 3 |
+
|
| 4 |
+
interface FirebaseAdminConfig {
|
| 5 |
+
projectId: string;
|
| 6 |
+
clientEmail: string;
|
| 7 |
+
privateKey: string;
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
function formatPrivateKey(key: string) {
|
| 11 |
+
return key.replace(/\\n/g, '\n');
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
export function createFirebaseAdminApp(config: FirebaseAdminConfig) {
|
| 15 |
+
if (admin.apps.length > 0) {
|
| 16 |
+
return admin.app();
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
return admin.initializeApp({
|
| 20 |
+
credential: admin.credential.cert({
|
| 21 |
+
projectId: config.projectId,
|
| 22 |
+
clientEmail: config.clientEmail,
|
| 23 |
+
privateKey: formatPrivateKey(config.privateKey),
|
| 24 |
+
}),
|
| 25 |
+
});
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
export function getAdminAuth() {
|
| 29 |
+
// Only initialize if we have credentials, otherwise return null (or throw)
|
| 30 |
+
// This prevents build crashes if env vars are missing
|
| 31 |
+
if (!process.env.FIREBASE_PROJECT_ID || !process.env.FIREBASE_CLIENT_EMAIL || !process.env.FIREBASE_PRIVATE_KEY) {
|
| 32 |
+
console.warn("Firebase Admin credentials missing. Server-side auth will fail.");
|
| 33 |
+
return null;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
const app = createFirebaseAdminApp({
|
| 37 |
+
projectId: process.env.FIREBASE_PROJECT_ID,
|
| 38 |
+
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
|
| 39 |
+
privateKey: process.env.FIREBASE_PRIVATE_KEY,
|
| 40 |
+
});
|
| 41 |
+
|
| 42 |
+
return app.auth();
|
| 43 |
+
}
|