Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save allipiopereira/6f11e427b671856252cb94f8661f997e to your computer and use it in GitHub Desktop.
Save allipiopereira/6f11e427b671856252cb94f8661f997e to your computer and use it in GitHub Desktop.
Como criar Subusários com Firebase - Permitir que um usuário crie outro usuário
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
const db = admin.firestore();
// Callable funciton to create a user
export const functionCreateUser = functions.https.onCall(
async (data, context) => {
var firebaseError = "";
console.log(
"function was called by user with id : " + context.auth?.uid || null
); // the question mark in typescript is usually used to mark parameter as optiona
if (!data.email || !data.password)
return { status: "failure", message: "email or password not provided" };
const email = data.email;
const password = data.password;
//craete user using firebase auth
const firebaseUser = await admin
.auth()
.createUser({ email: email, password: password })
.catch((err) => {
console.log("Firebase user creation error " + err);
firebaseError = err;
});
if (firebaseUser) {
//if user is created, save it to Users collection for custom user
await db
.collection("users")
.doc(firebaseUser.uid)
.set(
{
uid: firebaseUser.uid,
email: data.email,
display_name: data.displayName,
cnpj_cpf: data.cnpjCPF,
phone_number: data.phoneNumber,
photo_url: data.photoURL,
user_type: data.userType,
first_access: true,
created_time: admin.firestore.FieldValue.serverTimestamp(),
},
{ merge: true }
)
.then(() => {
console.log("User Created");
return {
status: "success",
uid: firebaseUser.uid,
};
})
.catch((err) => {
console.log("Error Creating user : " + err);
return {
status: "failure",
message: "User Creation Error",
};
});
} else
return {
status: "failure",
message: "User Creation Error : " + firebaseError,
};
return {
status: "success",
uid: firebaseUser.uid,
};
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment