James
James

Reputation: 43

Can't get list of users using Admin SDK Firebase

If I add to the Firebase cloud functions, I cannot get a list of users. I have tried many things, and followed the guide on firebase documentation, but it just keeps running, but never loading.

exports.listAllUsers = functions.https.onRequest((data, context) => {
  // List all users

  return listAllUsers();
});

function listAllUsers() {
  // List batch of users, 1000 at a time.
  var allUsers = [];

  return admin.auth().listUsers()
    .then(function (listUsersResult) {
      listUsersResult.users.forEach(function (userRecord) {
        // For each user
        var userData = userRecord.toJSON();
        allUsers.push(userData);
      });
        return allUsers
    })
    .catch(function (error) {
      console.log("Error listing users:", error);
    });

}

Upvotes: 2

Views: 1439

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599001

You seem to be confusing two types of Cloud functions:

  1. Callable functions, that you call from your app using the Firebase SDK.
  2. Regular HTTP functions, that you call from your app your client platform's regular HTTP client API.

Cloud Functions that are invoked with regular HTTPS requests

When you declare your function as functions.https.onRequest, you need to write your response to the response object. Based on the documentation on calling functions through HTTP requests, you'll need to do:

exports.listAllUsers = functions.https.onRequest((req, res) => {
  // List batch of users, 1000 at a time.
  var allUsers = [];

  return admin.auth().listUsers()
    .then(function (listUsersResult) {
      listUsersResult.users.forEach(function (userRecord) {
        // For each user
        var userData = userRecord.toJSON();
        allUsers.push(userData);
      });
      res.status(200).send(JSON.stringify(allUsers));
    })
    .catch(function (error) {
      console.log("Error listing users:", error);
      res.status(500).send(error);
    });
});

Calling Cloud Functions that are invoked using the Firebase SDK

If you want to call your Cloud Function from within your app using the Firebase SDK, you need to declare your function as:

exports.listAllUsers = functions.https.onCall((data, context) => {
  // List all users

  return listAllUsers();
});

Upvotes: 7

Related Questions