【问题标题】:How can I create an admin that can add users in firebase?如何创建可以在 Firebase 中添加用户的管理员?
【发布时间】:2021-06-29 13:47:12
【问题描述】:

我正在为教师构建一个管理学生数据的应用程序?老师需要能够注册一个帐户,然后才能将多个学生添加到 firebase auth。然后学生必须登录。如何在 firebase 中执行此操作?

【问题讨论】:

  • 嗨,欢迎来到 stackoverflow。确保提供有关您希望应用程序如何工作以及您可能尝试过的任何代码的完整详细信息。你可以阅读更多关于它的信息here。如果我的回答对您有帮助,您可以点击对勾图标接受它,否则请随时提出更多问题。
  • 鉴于有一个公认的答案,这非常好,最重要的是您不能直接通过客户端 SDK 执行此操作。原因是一旦用户进行身份验证然后创建另一个 firebase 用户,它就会取消对第一个用户的身份验证,然后对创建的用户进行身份验证。因此,您将需要利用 Admin SDK 来根据答案真正做到这一点。还有一些解决方法。

标签: node.js reactjs firebase


【解决方案1】:

您可以使用Firebase Custom Claims 分配“教师”声明,以便区分教师和学生。之后你可以Firebase Cloud Functions创建一个新的学生账户。

在云端函数中,可以验证调用该函数的用户是否为教师。

// Creates a new student account
exports.addStudent = functions.https.onCall((data, context) => {
  //Getting data passed from frontend
  const {name, email, password, ...rest} = data;
  
  //Checking if the caller of function is a teacher
  if (!context.auth.token.teacher) return "You are not a teacher!";
  
  //Creating a new user account
  return admin
  .auth()
  .createUser({
    email,
    password: 'secretPassword',
    displayName: name,
  })
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log('Successfully created new user:', userRecord.uid);
    return userRecord.uid;
  })
  .catch((error) => {
    console.log('Error creating new user:', error);
    return "An error occured"
  });
});

现在由您决定如何创建教师帐户。您可以直接在 Firebase 控制台中创建它并编写一次性函数来将教师声明添加到它们。

export.addTeacherClaim = functions.https.onCall((data, context) => {
  const {uid} = data;
  return admin
  .auth()
  .setCustomUserClaims(uid, { teacher: true })
  .then(() => {
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.
    return true;
  });
})

你可以像这样从你的 React 应用调用函数:

const addStudent = firebase.functions().httpsCallable('addStudent');
addMessage({ email: "name@domain.tld", name: "StudentName", password: "Password" })
  .then((result) => {
    // Read result of the Cloud Function.
    const newUserUid = result.data;
  });

【讨论】:

  • 您知道不使用云功能的另一种方法吗?我无法使用云功能,因为我目前没有信用。
  • @twfm_11 您需要某种安全环境、云功能或您自己的服务器。只有 Admin SDK(使用服务帐户)可以更新声明,因此您也不能共享凭据。否则,您将不得不手动更新声明左右。
  • “你知道我可以用另一种方法来做到这一点,而无需使用云功能吗?”是的,您可以通过在 Firestore 文档中声明角色来制定解决方案,如 doc 中所述,但请注意,如果没有使用 Admin SD,用户将无法创建另一个用户。所以非管理员用户应该首先创建他们的帐户(例如使用createUserWithEmailAndPassword()),然后管理员应该在 Firestore 中声明他们的角色。
  • (续)不要忘记保护持有角色的集合/文档:只有管理员应该有写入权限。总之,与基于 Cloud Functions 的方法相比,这种方法实现起来有点复杂,但这是可能的。
猜你喜欢
  • 2018-06-27
  • 2023-04-03
  • 1970-01-01
  • 2011-03-30
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多