Firebase authentication sign up token

26 Views Asked by At

I am new to firebase cloud functions and I'm using cloud functions with express.js. I need to retrieve an access token after registering a new user. i am using the below method for that.

const { admin, db } = require("../util/admin");

exports.registerUser = (req, res) => {
  const newUser = {
    email: req.body.email,
    password: req.body.password,
  };
  // ToDO valiate data
  db.collection("users")
    .doc(newUser.email)
    .get()
    .then((doc) => {
      if (doc.exists) {
        return res.status(400).json({ email: "email already exists" });
      } else {
        return admin
          .auth()
          .createUser({ email: newUser.email, password: newUser.password });
      }
    })
    .then(async (userRecord) => {
      // Get the access token
         const token = await userCredential.user.getIdToken();
         return token;
    })
    .then((token) => {
      return res.status(201).json({ token });
    })
    .catch((err) => {
      console.error(err);
      return res.status(500).json({ error: err.code });
    });
};

After sending the post request with email and password, the user is registered but the I receive a status 500 response. In the firebase authentication tab the registered user is visible but I'm unable to receive the access token. How to reteireve the token? Below there is the dependency versions I'm using.

  "dependencies": {
    "express": "^4.18.3",
    "firebase": "^10.10.0",
    "firebase-admin": "^11.8.0",
    "firebase-functions": "^4.3.1"
  },

This is the error response I receive in postman.enter image description here

0

There are 0 best solutions below