Firebase功能错误<admin.auth is =“”not =“”a =“”function =“”at =“”.. =“”>

时间:2018-03-30 12:56:22

标签: node.js firebase google-cloud-functions firebase-admin

我对Firebase和Node.js相当陌生。我在我的云功能中创建了此功能,以使用自定义令牌登录用户:

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!");
        }); 
    });
});

我在文档中使用了令牌生成方法,但每当我尝试登录用户时,它都会抛出错误:

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)

我做错了怎么可能?

1 个答案:

答案 0 :(得分:3)

admin的声明:

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

隐藏了这个:

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

使用其他名称,例如:

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