I have a simple signup form where a user can set their details, including a username that needs to be unique.
I have written a rule to validate if the username already exists (which works) but even if the signup fails, the user account has been created.
Example signup script (stripped back):
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)
}
The call to create a user document fails because the username is not unique (which is expected), but at this point in the flow, the user has already been created in Firebase!
If they then choose another username, they can't continue because Firestore already sees a user with that same email.
Is there a better way to create this flow?
Ideally, I do not want to create a user at all if the creation of the user document fails in some way.
Thanks!
Possible solution:
I was thinking I could just immediately delete the user after they're created if the try/catch block fails:
await data.user.delete() // ...but this seems hacky?