1

I'm fairly new to Firebase and Node.js. I have created this function in my Cloud Functions to login users with a custom token:

const functions = require('firebase-functions'); const admin = require('firebase-admin'); var serviceAccount = require("./service-account.json"); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: functions.config().firebase.databaseURL }); const cors = require('cors')({origin: true}); exports.login = functions.https.onRequest((req, res) => { cors(req, res, () => { //doing some validation.. //get password from db and match it with input password var userRef = admin.firestore().collection('users') userRef.where('username', '==', username).get() .then(snapshot => { if(snapshot.size > 1){ res.status(200).send("Invalid account!"); return; } snapshot.forEach(doc => { var userPass = doc.data().password; //if password matches, generate token, save it in db and send it if(userPass && password == userPass){ var uid = doc.data().uid; var admin = Boolean(doc.data().admin); var server = Boolean(doc.data().server); var additionalClaims = { admin: admin, server: server }; admin.auth().createCustomToken(uid, additionalClaims) .then(function(customToken) { res.status(200).send("token:" + customToken); }) .catch(function(error) { res.status(200).send("Token creation failed!"); }); //save token in db.. }else{ res.status(200).send("Invalid credentials!"); } }); }) .catch(err => { res.status(200).send("User authentication failed!"); }); }); }); 

I used the token generation method in the documentation, but whenever I try to login a user it throws the error:

TypeError: admin.auth is not a function at snapshot.forEach.doc (/user_code/index.js:128:27) at QuerySnapshot.forEach (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/reference.js:1012:16) at userRef.where.get.then.snapshot (/user_code/index.js:110:13) at process._tickDomainCallback (internal/process/next_tick.js:135:7) 

What could it be that I'm doing wrong?

1 Answer 1

4

This declaration of admin:

var admin = Boolean(doc.data().admin); 

is hiding this one:

const admin = require('firebase-admin'); 

Use a different name, such as:

var docAdmin = Boolean(doc.data().admin); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.