Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firebase cloud functions - https.onCall(....) can Context.Auth be used?

I need advice becuase I’ve never tried this combination:

  1. firebase app + realtime database this app will be my backend and provide some cloud functions.
  2. android app which will call these cloud functions.

I want to use google auth2 authentication and “protect” the cloud functions to be called by the android app only and if atuh is valid only.

Best Regards Ivan

For expample this is my cloud functions for ‘addTickets’ scenario:

=== 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;
 });
}
like image 400
Ivan Peshev Avatar asked Aug 14 '18 12:08

Ivan Peshev


1 Answers

If you want only authenticated users to invoke your callable function, then simply check that context.auth.uid exists. If the user is not authenticated, there will be no uid.

like image 194
Doug Stevenson Avatar answered Nov 10 '22 00:11

Doug Stevenson