如何使用firebase admin sdk列出所有用户

时间:2016-12-07 07:40:56

标签: firebase firebase-authentication firebase-admin

有没有办法列出使用firebase admin sdk的所有用户?文档仅显示通过uid或电子邮件获取一个用户。

5 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:4)

最新的firebase-admin sdk(截至目前版本5.4.2)有listUsers API可以执行此操作。示例是here

要添加到示例中的一件事,必须省略nextPageToken或有效的用户ID。 (IMO,它在示例或API文档中都不明显。)

答案 2 :(得分:3)

它不是一个好的解决方案,但您可以使用Firebase CLI导出用户数据并与您的应用程序集成。

  

AUTH:出口

     

firebase auth:export account_file --format = file_format

https://firebase.google.com/docs/cli/auth

答案 3 :(得分:3)

您可以使用admin sdk中提供的auth().listUsers()方法。详细的示例代码可以在这里找到。 Firebase Admin SDK Documentation

答案 4 :(得分:1)

在2020年3月,经过大量文件和各种帖子的争斗之后,我发现了以下作品:

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

这与在前端使用诸如react-firebase或npm firebase模块之类的东西时传递的常规Firebase配置不同。

要在服务器端获得CRUD权限,您似乎需要以下条件:

{
  "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"
}

如果您还没有生成一个,我会去找我的:

Firebase控制台=>项目设置=>服务帐户=>生成新的私钥