Firestore:如果规则失败,如何停止创建用户帐户?

时间:2018-11-23 10:59:08

标签: javascript firebase firebase-authentication google-cloud-firestore

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

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

示例注册脚本(回溯):

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)
}

创建用户 document 的调用失败,因为用户名不是唯一的(这是预期的),但是在流程的这一点上,已经在Firebase中创建了用户!

如果他们随后选择了另一个用户名,则将无法继续,因为Firestore已经看到使用相同电子邮件的用户。

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

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

谢谢!

可能的解决方案:

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

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

2 个答案:

答案 0 :(得分:2)

我建议在这里使用Cloud Functions,也许使用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'
        }
    }
});

答案 1 :(得分:1)

如果您希望某个值唯一,请考虑将其用作集合中的文档ID,并禁止对该集合进行更新。

例如,由于您希望用户名唯一,因此请创建一个集合usernames,其中每个文档的ID是用户名,内容是正在使用该名称的用户的UID。

另请参阅: