Firebase应用无法访问功能(例如firebase.auth())

时间:2018-06-08 19:08:22

标签: firebase firebase-authentication

我遇到了这个问题,我花了好几个小时研究,但似乎无法弄明白。我正在尝试将Firebase与Node.js一起使用,但无法访问不同的Firebase功能(例如firebase.auth()和firebase.firestore())。但是,当我通过管理SDK初始化时,那些最终会起作用。下面是我的简单代码以及错误:

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

const app = express();
firebase.initializeApp(functions.config().firebase);

const auth = firebase.auth();
const db = firebase.firestore();

结果错误:TypeError:firebase.auth不是函数

注意我还有几行初始化快车和车把,但怀疑那些会产生任何影响。

我也尝试过包含“require(”firebase / auth“)”,但这并没有奏效。下面也是我的package.json,特别是我安装的模块:

"dependencies": {
    "consolidate": "^0.15.1",
    "express": "^4.16.3",
    "firebase": "^5.0.4",
    "firebase-admin": "~5.12.1",
    "firebase-functions": "^1.0.4",
    "firebase-tools": "^3.18.6",
    "firebaseauth": "^1.0.0",
    "handlebars": "^4.0.11"
  },

请帮忙吗?我是一个新手Web开发人员所以任何建议将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

Cloud Functions触发器的格式如下:

exports.myFunctionName = functions.firestore
    .document('users/marie').onWrite((change, context) => {
      // ... Your code here
    });

您无法从云功能中访问客户端SDK。相反,如果您要在云功能中访问功能,则可以使用Admin SDKs

var admin = require('firebase-admin');
var app = admin.initializeApp();

答案 1 :(得分:0)

简短回答:使用管理SDK,它就是它的用途 - 云功能与你后端的其余部分进行交互。

更长的回答: 为了帮助您,以下是Firebase云功能的工作consume()文件的示例,该文件访问数据库(非firestore )和Firebase的auth部分...评论提供上下文。它是一个API端点,它接受用户的令牌,验证用户是否在我的系统中是“管理员”,然后在使用新的UID进行响应之前创建一个新的用户帐户。

index.js

const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.createUser = functions.https.onRequest( (req, res) => { // Look at the accessToken provided in the request, and have Firebase verify whether it's valid or not admin.auth().verifyIdToken(req.body.accessToken).then(decodedIdToken => { // Token was valid, pull the UID out of the token for the user making this request let requestorUid = decodedIdToken.uid; // Make a query to the database to see what that user's role is admin.database().ref(`userBasicInfo/${requestorUid}/role`).once('value').then( dataSnapshot => { if (dataSnapshot.val() === 'admin') { // If their role is "admin" then let's create a user! let userEmail = `${req.body.newuserid}@company.org`; admin.auth().createUser({ email: userEmail, password: req.body.password }).then(userRecord => { // See the UserRecord reference doc for the contents of userRecord. res.send({uid: userRecord.uid}); }).catch( error => { console.log("Error creating user:"); console.log(error) res.send(false); }); } else { console.log('Checked the database for the UID provided in the access token, role was not "admin".'); res.send(false); } }).catch( err => { console.log('Error finding user in database:'); console.log(err); res.send(false); }) }).catch( error => { console.error('Error while verifying Firebase ID token:'); console.log(error); res.send(false); }); }); 将是:

package.json