嘿,我有类似的问题,尝试通过管理员创建用户,因为没有登录就无法注册用户,我创建了一个解决方法,并在下面添加步骤
- 不用注册,而是在 firebase realtime db 中创建一个以电子邮件为密钥的节点(firebase 不允许电子邮件作为密钥,因此我创建了一个从电子邮件生成密钥的函数,反之亦然,我将附上以下函数)
- 在保存用户时保存初始密码字段(如果您愿意,甚至可以使用 bcrypt 或其他东西对其进行哈希处理,尽管它只会使用一次)
- 现在,一旦用户尝试登录,请检查数据库中是否存在具有该电子邮件的任何节点(从电子邮件生成密钥),如果存在,则匹配提供的密码。
- 如果密码匹配,请删除节点并使用提供的凭据执行 authSignUpWithEmailandPassword。
- 用户注册成功
//Sign In
firebaseDB.child("users").once("value", (snapshot) => {
const users = snapshot.val();
const userKey = emailToKey(data.email);
if (Object.keys(users).find((key) => key === userKey)) {
setError("user already exist");
setTimeout(() => {
setError(false);
}, 2000);
setLoading(false);
} else {
firebaseDB
.child(`users`)
.child(userKey)
.set({ email: data.email, initPassword: data.password })
.then(() => setLoading(false))
.catch(() => {
setLoading(false);
setError("Error in creating user please try again");
setTimeout(() => {
setError(false);
}, 2000);
});
}
});
//Sign Up
signUp = (data, setLoading, setError) => {
auth
.createUserWithEmailAndPassword(data.email, data.password)
.then((res) => {
const userDetails = {
email: res.user.email,
id: res.user.uid,
};
const key = emailToKey(data.email);
app
.database()
.ref(`users/${key}`)
.remove()
.then(() => {
firebaseDB.child("users").child(res.user.uid).set(userDetails);
setLoading(false);
})
.catch(() => {
setLoading(false);
setError("error while registering try again");
setTimeout(() => setError(false), 4000);
});
})
.catch((err) => {
setLoading(false);
setError(err.message);
setTimeout(() => setError(false), 4000);
});
};
//Function to create a valid firebase key from email and vice versa
const emailToKey = (email) => {
//firebase do not allow ".", "#", "$", "[", or "]"
let key = email;
key = key.replace(".", ",0,");
key = key.replace("#", ",1,");
key = key.replace("$", ",2,");
key = key.replace("[", ",3,");
key = key.replace("]", ",4,");
return key;
};
const keyToEmail = (key) => {
let email = key;
email = email.replace(",0,", ".");
email = email.replace(",1,", "#");
email = email.replace(",2,", "$");
email = email.replace(",3,", "[");
email = email.replace(",4,", "]");
return email;
};