Perform admin actions with Firebase admin
Perform admin actions with Firebase admin like read all users or update data.
Obtain your service account private key and store it in a json file https://firebase.google.com/docs/admin/setup
npm install firebase-admin --save
Run this block of code below before all the others
// global 1
async function initFirebase() {
const admin = require('firebase-admin');
const serviceAccount = require('./appid-firebase-adminsdk.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const auth = admin.auth();
const db = admin.firestore();
return {auth, db};
}
const {auth, db} = await initFirebase();
Paginate the results present in auth
More details here: https://firebase.google.com/docs/auth/web/start?hl=en
//exec: /usr/local/bin/node
async function getUserEmails(auth, nextPageToken) {
const listUsersResult = await auth.listUsers(1000, nextPageToken);
listUsersResult.users.map(user => {
//if (new Date(user.metadata.creationTime) > new Date("2022-12-20T00:00:00")) {
console.log(user.email);
//}
});
if (listUsersResult.pageToken) {
await getUserEmails(auth, listUsersResult.pageToken);
}
}
await getUserEmails(auth);
Use a hierarchy such as /UserID/DocumentID
More details here: https://firebase.google.com/docs/firestore/query-data/get-data?hl=en
Firebase admin only works for NodeJs app (not browser)
//exec: /usr/local/bin/node
const user = await auth.getUserByEmail(email);
console.log(user);
const docsRef = db.collection(user.uid);
const snapshot = await docsRef.get();
// show nbr of objects for user
console.log("Usage: " + snapshot.size);
// show all documents for user
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
//exec: /usr/local/bin/node
const user = await auth.getUserByEmail(email);
let collectionRef = db.collection("profile/");
let documentRef = collectionRef.doc(user.uid);
// Delete a document
//documentRef.delete().then(() => {
// console.log('Document successfully deleted.');
//});
// Update a document
documentRef.set({ name: "John Doe"}).then(() => {
return documentRef.get();
}).then(documentSnapshot => {
let field = documentSnapshot.get('name');
console.log(`Retrieved field value: ${field}`);
});