0
votes

I am a beginner to Firebase cloud Functions. My main motivation of using cloud functions is for authentication.

index.js (in functions folder)

    var admin = require("firebase-admin");
    const functions = require('firebase-functions');
    const createuser = require('./funs/create_user');
    var serviceAccount = require('./funs/serviceAccount.json');

    admin.initializeApp({
       credential: admin.credential.cert(serviceAccount),
       databaseURL: "//Given by Firebase"
    });


    exports.createuser = functions.https.onRequest(createuser);

create_user.js

    const admin = require("firebase-admin");
    module.exports = function (req,res) {

       if(!req.body.phone)
       {
           return res.status(422).send({error: "Bad Input"});
       }

       const phone = String(req.body.phone).replace(/[^\d]/g,"");

       admin.auth().createUser({ uid: phone })
       .then((user) => res.send(user))
       .catch((err)=>res.status(422).send({error:err}));

       //return 1;

     } 

When I call the function using Postman, I pass data to the cloud function as:

     {
         "phone": "1212121212"         
      }

I get response as "Bad Input" as specified inside of if statement.

On removal of the if condition i get this as my response

  {
    "error": {
    "code": "auth/invalid-uid",
    "message": "The uid must be a non-empty string with at most 128 
    characters."
  }
 }

Postman

2
How do you call this HTTPS function and how do you pass the data (i.e. phone number) to the body of the HTTP Request. What happens if you try to log req.body? - Renaud Tarnec
I call the function and pass the data using Postman web app. I have edited and attached the image link. Thank you - Ron Astle Lobo

2 Answers

2
votes

Your Cloud Function code is valid, I have successfully tested it in a Firebase project, using the Axios library as follows, in an HTML page.

axios.post('https://us-central1-xxxxxxxx.cloudfunctions.net/testPhoneNbr', {
    phone: '0471214365'
})
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

The user is correctly created.

The problem is probably coming from the way you call the HTTPS Cloud Function.

0
votes

Please change type="text" to type="JSON" in postman when hit the POST request