Search code examples
javascriptfirebase-authenticationgoogle-cloud-functionsfirebase-admin

How do I access Firebase Tenants from a Vue app or Firebase Cloud Functions?


The Firebase multi tenant authentication docs include examples on how to work with Tenants in Node.js but I'm still learning and I don't understand how this can be done in Cloud Functions.

function listAllTenants(nextPageToken) {
  return admin.auth().tenantManager().listTenants(100, nextPageToken)
    .then((result) => {
      result.tenants.forEach((tenant) => {
        console.log(tenant.toJSON());
      });
      if (result.pageToken) {
        return listAllTenants(result.pageToken);
      }
    });
}

listAllTenants();

How do I take this above and turn it into a Cloud Function?

The best I could do is this...

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const tenantManager = admin.auth().tenantManager();
const express = require("express");
const cors = require("cors");

const app = express();

app.use(
  cors({
    origin: ["http://localhost:3000"], // Make sure to remove the trailing slash in the URL
  })
);

app.get("/getTenants", async (req, res) => {
  try {
    const tenantList = await tenantManager.listTenants();
    const tenantsArr = tenantList.tenants.map((tenant) => tenant.toJSON());
    res.status(200).send(tenantsArr);
  } catch (error) {
    console.error("Error fetching tenants:", error);
    res.status(500).send("Error fetching tenants");
  }
});

exports.getTenants = functions.https.onRequest(app);

Plus my Vue store (Vuex) file where I call the function...

import { getFunctions, httpsCallable } from "firebase/functions";
async getTenants({ commit }) {
    commit("SET_TENANTS", []); // Clearing tenants before fetching new data
    try {
      const tenantsArr = [];
      const functions = getFunctions();
      const getTenantsCallable = httpsCallable(functions, "getTenants");
      const result = await getTenantsCallable(); // Call the callable function

      tenantsArr.push(result.data);
      console.log("Tenants:", result.data);
      commit("SET_TENANTS", tenantsArr);
    } catch (error) {
      // Handle errors
      console.error("Error fetching tenants:", error);
    }
  },

But this returns a not found 404 console error: POST https://us-central1-mysite-12432-staging.cloudfunctions.net/getTenants 404 (Not Found)


Solution

  • You've written and deployed an HTTP type function, but you're trying to invoke it like a callable function. They are not the same thing - I suggest reviewing those doc links to better understand.

    If you want to invoke your HTTP function, just make a normal HTTP request to it using the endpoint you were given after deployment. Don't use the Firebase functions SDK for that.