gpt4 book ai didi

javascript - 火存储 : How to stop user account being created if a rule has failed?

转载 作者:行者123 更新时间:2023-11-28 17:16:11 27 4
gpt4 key购买 nike

我有一个简单的注册表单,用户可以在其中设置其详细信息,包括需要唯一的用户名。

我编写了一条规则来验证用户名是否已存在(有效),但即使注册失败,用户帐户也已创建。

注册脚本示例(精简):

try {
// This creates a user on submit of the form.
const data = await fb.auth.createUserWithEmailAndPassword(this.email, this.password)

// Use the uid we get back to create a user document in the users collection.
await db.collection('users').doc(data.user.uid).set({
username: this.username, // This fails in the rule if it exists.
firstName: this.firstName,
lastName: this.lastName
})
} catch (error) {
console.log(error)
}

创建用户文档的调用失败,因为用户名不是唯一的(这是预期的),但此时在流程中,用户已在 Firebase 中创建!

如果他们随后选择其他用户名,则无法继续,因为 Firestore 已发现具有相同电子邮件地址的用户。

是否有更好的方法来创建此流程?

理想情况下,如果用户文档的创建因某种原因失败,我根本不想创建用户。

谢谢!

可能的解决方案:

我想如果 try/catch block 失败,我可以在创建用户后立即删除用户:

await data.user.delete() // ...but this seems hacky?

最佳答案

我建议在这里使用云功能,可能使用 http onCall一个会让它变得美好而简单。我还没有测试过下面的内容,但应该可以帮助您实现目标。

客户端代码

const createUser = firebase.functions().httpsCallable('createUser');
createUser({
email: this.email,
password: this.password,
username: this.username,
firstName: this.firstName,
lastName: this.lastName
}).then(function(result) {
console.log(result); // Result from the function
if (result.data.result === 'success') {
await firebase.auth().signInWithEmailAndPassword(this.email, this.password);
} else {
console.log('Username already exists')
}
});

云功能

exports.createUser = functions.https.onCall(async (data, context) => {
const email = data.email;
const password = data.password;
const username = data.username;
const firstName = data.firstName;
const lastName = data.lastName;

const usersQuery = await admin.firestore().collection('users').where('username', '==', username).get();

if (usersQuery.size > 0) {
return {
result: 'username-exists'
}
} else {
const user = await admin.auth().createUser({
displayName: username,
email: email,
password: password
});
await admin.firestore().collection('users').doc(user.uid).set({
username: username,
firstName: firstName,
lastName: lastName
});
return {
result: 'success'
}
}
});

关于javascript - 火存储 : How to stop user account being created if a rule has failed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53445405/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com