Functions on Auth events
Functions that trigger on Auth events
Blocking functions
a cloud function runs before the user is created
The Authentication service waits for the function to complete successfully before adding the user. If the function throws, the error is thrown to the client and the user is not created, aka the registration fails.
const options: BlockingOptions = {
region: "europe-west1",
}
export const onRegisterBlocking = beforeUserCreated(options, async (event) => {
const user = event.data // AuthUserRecord === UserRecord
// user.uid
// user.email
if (user?.email?.includes("@hotmail.com")) {
throw new HttpsError("invalid-argument", "don't use hotmail")
}
// create the user in the database first, then return
await createDefaultDataForUser(user)
})
Non blocking functions
As of writing, there is no v2 equivalents for onCreate
.
functions.auth
functions.auth.user()
Firebase Auth has its own list of users. By default, the database doesn't have the list of users. It's best to store the users in the database too.
return a promise
it's important to return a promise so that the cloud function can return immediately without waiting the actually promise to resolve or error.
new user through Auth => create user in database
import { auth } from "firebase-functions/v1"
export const onRegisterNonBlocking = auth.user().onCreate(async (user) => {
return db
.collection("users")
.doc(user.uid)
.set(
{
uid: user.uid,
email: user.email,
},
{ merge: true }
)
.then(() => {
console.log("user created in Firestore: " + user.email)
return true
})
.catch((error) => {
console.error("Error creating user: ", error)
return true
})
})
user deleted in auth => delete user in database
exports.deleteUserOnFirestore = functions.auth.user().onDelete((user) => {
return db
.collection("users")
.doc(user.uid)
.delete()
.then(() => {
console.log("user deleted from Firestore: " + user.email)
return true
})
.catch((error) => {
console.error("Error deleting user: ", error)
return true
})
})