Firebase云功能-可以使用https.onCall(....)Context.Auth吗?

时间:2018-08-14 12:11:27

标签: function firebase oauth cloud

我需要建议,因为我从未尝试过这种组合:

  1. firebase应用程序+实时数据库 该应用程序将成为我的后端,并提供一些云功能。
  2. 将调用这些云功能的android应用。

我想使用google auth2身份验证,并且仅当atuh仅有效时才“保护”仅由android应用程序调用的云函数。

最佳问候 伊万

例如,这是我针对“ addTickets”场景的云功能:

=== index.js:===

exports.addTickets = functions.https.onCall((data, context) => {
 // data comes from client app
 const buyingRecord = data;
 console.log(‘buyingRecord: ‘ + JSON.stringify(buyingRecord));

return tickets.updateTicketsAmmount(buyingRecord)
 .then((result)=>{
 tickets.addTicketsBuyingRecord(buyingRecord);
 result.userid = buyingRecord.userid;
 result.ticketsCount = buyingRecord.ticketsCount;
 return result;
 });
});

====== tickets.js =======

exports.updateTicketsAmmount = function(buyingRecord) {
 var userRef = db.ref(‘users/’ + buyingRecord.userid);
 var amountRef = db.ref(‘users/’ + buyingRecord.userid + ‘/ticketsAmount’);
 return amountRef.transaction((current)=>{
 return (current || 0) + buyingRecord.ticketsCount;
 })
 .then(()=>{
 console.log(“amount updated for userid [“ + buyingRecord.userid + “]”);
 return userRef.once(‘value’);
 })
 .then((snapshot)=>{
 var data = snapshot.val();
 console.log(“data for userid [“ + snapshot.key + “]:” + JSON.stringify(data));
 return data;
 });
}

exports.addTicketsBuyingRecord = function(buyingRecord) {
 var historyRef = db.ref(‘ticketsBuyingHistory’);
 var newRecordRef = historyRef.push();
 return newRecordRef.set(buyingRecord)
 .then(()=>{
 console.log(‘history record added.’); 
 return newRecordRef.once(‘value’);
 })
 .then((snapshot)=>{
 var data = snapshot.val();
 console.log(‘data:’ + JSON.stringify(data));
 return data;
 });
}

1 个答案:

答案 0 :(得分:2)

如果只希望经过身份验证的用户调用您的可调用函数,则只需检查context.auth.uid是否存在。如果用户未通过身份验证,则将没有uid。

相关问题