Home > Enterprise >  firebase admin sdk to create new user
firebase admin sdk to create new user

Time:10-16

**In my crud project the admin adds the user in the docs as well as in auth by normal sdk would replace the current user so i tried admin sdk but writing the cloud functions and calling is getting complex as im new to firebase. i got this got from fellow stackoverflow's thread modified it for my convenience but doesn't seems to be working. **

I deployed the function locally using "firebase serve"

cloud function

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();


exports.createUser = functions.firestore
.document('Teamchers/{userId}')
.onCreate(async (snap, context) => {
    const userId = context.params.userId;
    const newUser = await admin.auth().createUser({
        disabled: false,
        username: snap.get('UserName'),
        email: snap.get('email'),
        password: snap.get('password'),
        subjectname: snap.get('subjectname')
    });
  
    return admin.firestore().collection('Teamchers').doc(userId).delete();
});

calling it

const createUser = firebase.functions().httpsCallable('createUser');

  const handleadd = async (e) =>{
    e.preventDefault();
    try{
      createUser({userData: data}).then(result => {
        console.log(data);
    });
      addDoc(collection(db, "Courses" , "Teachers", data.subjectname ), {
        ...data,
        timestamp: serverTimestamp(),
        
      });
      alert("Faculty added succesfully")
    } catch (e){
      console.log(e.message)
    }
  }

CodePudding user response:

In addition to the potential typo mentioned by coderpolo and Frank, there are several other errors in your codes:

1. JS SDK versions mixing-up

It seems that you are mixing up JS SDK V9 syntax with JS SDK V8 syntax.

Defining the Callable Cloud Function in your front-end as follows is V8 syntax:

const createUser = firebase.functions().httpsCallable('createUser'); 

While doing addDoc(collection(...)) is V9 syntax.

You have to choose one version of the JS SDK and unify your code (see V9 example below, #3).

2. Wrong Cloud Function definition

Defining your function with:

exports.createUser = functions.firestore
.document('Teamchers/{userId}')
.onCreate(async (snap, context) => {..})

is not the way you should define a Callable Cloud function.

With onCreate() you are defining a background triggered Cloud Function that is to be triggered when a new doc is created in Firestore and not a Callable CF.

You need to adapt it as follows:

exports.createUser = functions.https.onCall((data, context) => {

    try {
        // ....
        // Return data that can be JSON encoded
    } catch (e) {
        console.log(e.message)
        // !!!! See the doc: https://firebase.google.com/docs/functions/callable#handle_errors
    }
});

3. Use await since your handleadd() function is async

This is not stricto sensu an error but you should avoid using then() and async/await together.

I would refactor it as follows (V9 syntax):

import { getFunctions, httpsCallable } from "firebase/functions";

const functions = getFunctions();
const createUser = httpsCallable(functions, 'createUser');

const handleadd = async (e) => {
    e.preventDefault();
    try {
        await createUser({ userData: data })
        await addDoc(collection(db, "Courses", "Teachers", data.subjectname), {
            ...data,
            timestamp: serverTimestamp(),

        });
        alert("Faculty added succesfully")
    } catch (e) {
        console.log(e.message)
    }
}
  • Related