4

I tried to signup and login to firebase . I use Firebase (fire-store), postman, express(REST API).

my code (index.js)

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp(config); 
// i'm not  provide the config data here, but initialized in my actual code.

const express = require("express");
const app = express();

let db = admin.firestore();

// Signup route 
app.post('/signup', (req,res) => {
  const newUser = {
    email: req.body.email,
    password: req.body.password,
    confirmPassward: req.body.confirmPassword,
    handle: req.body.handle
  };

  let token, userId;
  db.doc(`/users/${newUser.handle}`)
    .get()
      .then(doc => {
        if(doc.exists) {
          return res.status(400).json({ hanldle: 'this hanlde is already taken'});
        }else {
          return firebase()
        .auth()
        .createUserWithEmailAndPassword(newUser.email, newUser.password);
        }
      })

    .then((data) => {
       userId = data.user.uid;
      return data.usergetIdToken()
    })
.then( ( idToken ) => {
      token = idToken ;
      const userCredentials = {
        handle: newUser.handle,
        email: newUser.email,
        createdAt: new Date().toISOString(),
        userId 
      };
      return db.doc(`/users/${newUser.handle}`).set(userCredentials);
    })
    .then(() => {
      return res.status(201).json({ token });
    })
    .catch(err => {
      if(err.code === 'auth/email=already-in-use') {
        return res.status(400).json({ email: 'email is alread is used '})
      } else { 
        return res.status(500).json({ err : err.code });
      }
    });
});

exports.api = functions.https.onRequest(app); 

firebase.json file

{
  "emulators": {
    "functions": {
      "port": 5001
    },
    "ui": {
      "enabled": true
    },
    "hosting": {
      "port": 5000
    }
  },
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

I'm starting the firebase emulator using firebase emulators:start i didn't get any error when starting the firebase emulator and it works properly Though, there is one warning, like

!  functions: The Cloud Firestore emulator is not running, so calls to Firestore will affect production.

If i send any get or post request using post, i get error log from the emulator

!  External network resource requested!
   - URL: "http://169.254.169.254/computeMetadata/v1/instance"
 - Be careful, this may be a production service.
!  External network resource requested!
   - URL: "http://metadata.google.internal./computeMetadata/v1/instance"
 - Be careful, this may be a production service.
>  Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.

I don't know how to get rid of it. Any assistance you could give me in this matter would be greatly appreciated.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Yuvan M
  • 53
  • 1
  • 4

2 Answers2

5

I just had the same issue, and it seems to come down to admin.initializeApp(); needing different info than what you've likely supplied.

I found this answer here that helped.

I'm guessing you got the config JSON from Console > Project Settings > General > Your Apps > Firebase SDK snippet. That's what I was using and kept getting this error too.

Then I did as that answer suggests. Go to Console > Project Settings > Service Accounts. There you'll find a blue button that reads "Generate new private key". Download that key, saving it to your project (and renaming it if youd like). Then as that page suggests, use the following code to initialize.

var admin = require("firebase-admin");

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://projectname.firebaseio.com"
});

It might be worth noting that the databaseURL bit can be found in what you currently have for config.

m4cbeth
  • 144
  • 1
  • 1
  • 11
0

First, There are limitations with regular firebase accounts.

Once you are into blaze plan etc, make sure to "Project Settings" > Service Account Tab > Firebase Admin SDK

Generate New Service Key.

Then use below code to Map correct service account json

var admin = require("firebase-admin");

 var serviceAccount = require("Mention path to service Account key.json")

 admin.initializeApp({
   credential: admin.credential.cert(serviceAccount)
})

Thank you m4cbeth.

Vinayak V Naik
  • 1,291
  • 1
  • 9
  • 7