Is there a way to list all the users using the firebase admin sdk? Documentation only shows getting one user either by uid or email.
5 Answers
The latest firebase-admin sdk
(as of now version 5.4.2
) has listUsers
API that would do that. The example is here.
One thing to add to the example, the nextPageToken
has to be omitted or a valid userid. (IMO, it's not obvious in neither the example or the API doc.)
Update As @Webp says in their answer, there is now an API to list all users in the Admin SDK.
Original answer:
There is no public API to retrieve a list of users from the Firebase Admin SDK.
The typical way to deal with this scenario is to keep a list of the pertinent user information in the Firebase Database. See this original question for more: How do I return a list of users if I use the Firebase simple username & password authentication
You can use auth().listUsers()
method provided in the admin sdk. Detailed example code can be found here.
Firebase Admin SDK Documentation
In March 2020, after a lot of fighting with documentation and various posts, i found the following works:
const admin = require("firebase-admin");
const serviceAccount = require('./serviceAccount.json'); // see notes below about this.
const listAllUsers = () => {
const app = admin.initializeApp({
databaseURL: 'https://your-project-name.firebaseio.com',
credential: admin.credential.cert(serviceAccount) <-- see notes below about this
});
app.auth().listUsers(1000) // lists up to 1000 users
.then((listUsersResult) => {
let users = JSON.stringify(listUsersResult);
const date = new Date();
const day = date.getDate();
const month = date.getMonth() + 1;
fs.writeFileSync(__dirname + `/../my-backups/authentication-backup_${day}_${month}_2020.json`, users);
})
.catch(function (error) {
console.log('Oh no! Firebase listUsers Error:', error);
});
}
re serviceAccount.json
This is NOT the same as the usual Firebase config you pass-in when using things like react-firebase or the npm firebase module on front end.
To gain CRUD rights server-side, you seem to need the following:
{
"type": "service_account",
"project_id": "my-project-id",
"private_key_id": "xxxxxxxxxxxxxxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----\nMxxxxxxxxxxxxxxzuUA=\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-em4gz@my-project-name-email-thing.iam.gserviceaccount.com",
"client_id": "0000000000000000000",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-em4gz%40my-proj-name.iam.gserviceaccount.com"
}
If you haven't generated one yet, I got mine by going:
Firebase Console => Project Settings => Service Accounts => Generate New Private Key