我想制作一个系统,管理员可以通过电子邮件创建用户身份验证。我已经按照文档说明进行开发,但当前会话已关闭。我只想创建 auth 来获取 uid,然后在数据库中创建一个用户,其中包含我要存储的数据。
这就是我所拥有的:
var email = emailInput.value;
var password = "Abcd1234";
firebase.auth().createUserWithEmailAndPassword(email, password).then((userCredential) => {
var user = userCredential.user;
//user.uid contains the id I want to create the instance on ref usuarios
database.ref("usuarios/"+ user.uid).set({...});
});
编辑:
答案 0 :(得分:2)
您无法使用客户端 SDK 创建新用户。我的意思是用户根据需要创建新用户。您需要使用 Firebase Admin SDK(必须在安全的服务器环境中 - 如 Firebase Cloud Functions)。
您可以像这样编写云函数:
exports.createNewUser = functions.https.onCall((data, context) => {
if (isAdmin(context.auth.uid)) {
return admin.auth().createUser({
email: data.email,
password: data.password,
displayName: data.name
}).then((userRecord) => {
// See the UserRecord reference doc for the contents of userRecord.
console.log('Successfully created new user:', userRecord.uid);
return { uid: userRecord.uid }
}).catch((error) => {
console.log('Error creating new user:', error);
return { error: "Something went wrong" }
});
}
return {error: "unauthorized" }
})
现在有多种方法可以验证调用此函数的用户是否为管理员。第一个将使用 Firebase Custom Claims,它有点像您分配给用户的角色。另一种选择是存储在数据库中使用的 UID 并检查 db 的管理节点中是否存在 UID。只需确保只有您可以编辑数据库的那部分。
从客户端调用函数:
const createNewUser = firebase.functions().httpsCallable('createNewUser');
createNewUser({ name: "test", email: "test@test.test", password: "122345678" })
.then((result) => {
// Read result of the Cloud Function.
var response = result.data;
});