Znote (recipes)
  Get Znote  

Firebase admin integration

Perform admin actions with Firebase admin



Perform admin actions with Firebase admin like read all users or update data.

Firebase Admin installation

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

Init Firebase

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');
    credential: admin.credential.cert(serviceAccount)
  const auth = admin.auth();
  const db = admin.firestore();
  return {auth, db};

const {auth, db} = await initFirebase();

Show all users

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")) {
    if (listUsersResult.pageToken) {
        await getUserEmails(auth, listUsersResult.pageToken);

await getUserEmails(auth);

Read Firestore

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);
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());

Write Firestore

//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}`);

Related recipes