Sammy
Sammy

Reputation: 21

Firebase credentials error when trying to get collection

I am using node with express for my project. Everything is working until I try to get a collections with my middleware.

This is the middleware:

const FBAuth = (req, res, next) => {
  let idToken;
  if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
    idToken = req.headers.authorization.split(' ')[1];
  } else {
    return res.status(403).json({ error: 'No Token' });
  }
  admin.auth().verifyIdToken(idToken)
    .then(decodedToken => {
      req.user = decodedToken;
      console.log(decodedToken);

I console log the idToken and seems to be fine. I console log the decodedToken and I get this:

iss: 'https://securetoken.google.com/projectName',
>    aud: 'projectName',
>    auth_time: 1583062225,
>    user_id: 'an ID',
>    sub: 'same as user_id',
>    iat: number...,
>    exp: number...,
>    email: '[email protected]',
>    email_verified: false,
>    firebase: { identities: { email: [Array] }, sign_in_provider: 'password' },
>    uid: 'same as user_id'

But then if I try to get a collection for example "users" (Same as the collection name as in firebase):

admin.auth().verifyIdToken(idToken)
    .then(decodedToken => {
      req.user = decodedToken;
      console.log(decodedToken);
      return db.collection("users")
       .where('email', '==', req.user.email)
       .limit(1)
       .get()
    })
     .then(data => {
       res.json(data)
     })

No matter what collection I try to get or how I always get this error:

UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information...

So I read about the credentials, I add them like this:

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

const config = {
...more configs
atabaseURL: "https://...",
credential: admin.credential.cert(serviceAccount),
projectId: "projecId",
...more config
}

firebase.initializeApp(config)

And in the serviceAccountKey.json I have the key that I got from firebase generated in the account service tab.

Still getting same error as above after adding the credentials.

Upvotes: 1

Views: 357

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

The code you're showing calls this:

firebase.initializeApp(config)

But we don't know what firebase is. I'm pretty sure it's not the Firebase Admin SDK. I suspect you should be initializing the Admin SDK using the admin variable that you're using to query the database in your exprss app:

admin.initializeApp(config)

Upvotes: 1

Related Questions