firebase 云函数 - https.onCall(....) 可以使用 Context.Auth 吗?

Iva*_*hev 4 cloud function oauth firebase

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

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

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

最好的问候伊万

例如,这是我的“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;
 });
});
Run Code Online (Sandbox Code Playgroud)

======门票.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;
 });
}
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 7

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