Posts

Showing posts with the label Firebase

Firebase Storage Make only Selected Basket (Folder) Public

Image
 One of the big issue I face with google cloud storage is when I go to build a site which has public as well as private sections. Defult rule  as follows make the whole basket open to read which is not necessary.  match /{allPaths=**} {       allow read;       allow write: if request.auth != null;     } If you make a basket (generated)  base rule and try to access the file without token like below , it will gives permission issue . https://firebasestorage.googleapis.com/v0/b/<project id>.appspot.com/o/generated%test_400*400.png?alt=media&token= {   "error": {     "code": 403,     "message": "Permission denied. Could not perform this operation"   } } The issue have to resolve in google cloud storate admin by giving access to perticular basket. Ref : https://cloud.google.com/storage/docs/access-control/making-data-public#objects Go to following URL : https://console.cloud.google.com/storage/browser?pr

Firebase Cloud Functions Triggers with Two varibles

Image
 Although firebase functions document not mentioned about how many varible values can be exhist in firebase onWrite() tirgger , I have used it upto 2 levles without any issue.  For an exaplen in the blow code , I have consider the change in list under the userId ,, The value will be wrriten under the varible of user.  exports.testFunctionName = functions.database.ref('/user-list/{user}/{pushId}').onWrite(( change,context) => {             const original =  change.after.val();             var pushId=context.params.pushId;                 var userId=context.params.user; ...

How to user firebase Orderby Wisely

Image
There are number of ways  firebase order by can be used.Ferfer the following example.  It can be user as a where clause  to select values based on child attribute.You dont need to select items within the for loop.  todoRef.orderByChild("title").equalTo("test 1").once('value').then(function(snapshot) {     snapshot.forEach(function(childSnapshot) {         var todoID=childSnapshot.key; }) }).. We can use it as fallow,,

Firebase Cloud Functions TypeError: Cannot read property 'val' of undefined

Image
I have started using fire-base functions some time back and it was in beta release. When I try to update the functions within the production with the different node packages of firebase functions, following error occurred. TypeError: Cannot read property 'val' of undefined at exports.<>.functions.database.ref.onWrite.event (/user_code/index.js:467:38) at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27) I have used number of  fire base functions  and all of them triggering based onWrite leads to the above error. After small search I found the following discussion , https://stackoverflow.com/questions/49746905/firebase-typeerror-cannot-read-property-val-of-undefined?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa I have moved  from     "firebase-functions": "^0.9.1", to  "firebase-functions": "^1.0.2", where there is a major cha

Schedule Task on Google Cloud (Firebase)

Image
Major difficulty I faced as a backend-developer using stripe is the automated tasks running in the back-end based on time.For an example a batch process run in night or a small intended delay within a user process. The use of javascript based delay functions cannot accept in enterprise level applications, due to high unreliability within them. For example, all the delay functions might removed within sever restart. During the search of solid solution, I found the google cloud cron jobs,  which overcome the issue without going out of google platform. Thanks for the reference: https://firebase.googleblog.com/2017/03/how-to-schedule-cron-jobs-with-cloud.html Start with prerequisites: Ensure these are available locally. git Python 2.7 Python pip Google Cloud SDK Clone the repository to a desired folder git clone https : //github.com/firebase/functions-cron Move to functions - cron folder from the command line enable gclould tool to use your project.   gcloud

Firebase database.ServerValue.TIMESTAMP get current time

Firebase Server Time STAMP can only retive the value when it comminted to firebase database var currentTimeStamp=firebase.database.ServerValue.TIMESTAMP; value for this will be set when datbase operation like set ,push or update occures . In order to get the value you need to write code like below.   ref.child(test).child(time-stamp').set(firebaseAdmin.database.ServerValue.TIMESTAMP).then(function() {                           ref.child(test).once('value').then(function(Snapshot) {                                                          var currentTimeStamp= Snapshot.val()['time-stamp']; }); });

Firsby for Unit test Firebase REST API

Firebase required to iniciate in order to run test cases. Firsby is a api testing fromwork ,which can work with jasmine.  npm install jasmine-node -g Install frisby.js http://frisbyjs.com/ Create spec file witih spec folder Import depeldancy var request = require("request"); var server = require("./../src/test.js");   // server file var frisby = require('frisby'); Header value for every request frisby.globalSetup({ request: { headers: {'AccessToken':process.env.test_token}. // taken from the .env } }); Dependent Request frisby.create(' Login')   .post(process.env.npm_config_host+'/api/login',{.  //take the host when running test command         "profile-type": "test",         "mess-token":"" }) .after(function(err, res, body) {   frisby.create('Dome')     .post(process.env.npm_config_host+'/api/user',{           "profile-type": &qu

Uplaod to Firebase Storage from Node Express REST

Image
I need to upload user profile picture from mobile device trogh rest API to Firebase storage .Finally I go the follwing articale wich really guide me .  https://mzmuse.com/blog/how-to-upload-to-firebase-storage-in-node In order to upload the file from Express REST I used connect-busboy and fs node modules . Route file   router.post('/api/user-pic/profile-type/:type', ProfilePicController.setProfile); Controller File    exports.setProfile = function(req, res, next) {                     var fstream;                     req.pipe(req.busboy);                     req.busboy.on('file', function (fieldname, file, filename) {                                           console.log("Uploading: " + filename);                         fstream = fs.createWriteStream(__dirname + '/files/' + filename);                               file.pipe(fstream);                         const filePath = __dirname + '/files/' + filename;  

Firebase Promises

Image
 Firebase Nodejs requests are Asyncronus .Which means, in the follwing code block I need to check order users exhist before set user. But the user order insert fucntion written second will fire before validation finished .Developer need to careful on this when firebase adopted.     for(var user in users) {                                              f irebase.database().ref("users"); users.once("value", function(snapshot) {                                      var temp= snapshot.exists();                                                             if (temp) {                                           var temp= on_exhist_checked(snapshot);                                              }                          });                      } function on_exhist_checked(snapshot) {                             var  temp= f irebase.database(). child(snapshot.key).child('orders').set({                                   key: true                

Firebase REST API auth - access token

I have to use Firebase Database and server a REST API .I need to allow the REST API call only for authenticated users from the same freebase. According to Documentation on REST API Save data > Auth Section I able to successfully access the Database using database secret . https://firebase.google.com/docs/database/rest/save-data But I could not successfully retrieve the data using access token of authenticated user . https://<<removed-my-project-id>>.firebaseio.com/users.json?access_token=ya29.GlxuBLxJ6R2uNYJ7SXnMhe7Inqw94ShGeZ7MTBmyxYUI2cLDCXJcPAfbo1_uKLjUhfPX3uQw_ElBjIVwu73caeKJfBAh87GGRWZx2JiSwuIZybAmtVXyFyqaeYbAJQ Reffering confusing document again I pass the URL as fallows using the idtoken.(currentUser.getIdToken taken from cleint side) https:// <<my-project-id>> .firebaseio.com/users.json?auth=eyJhbGciOiJSUzI1NiIsImtpZCI6IjBkNWNlYjA1ODA2ODk3OTM3ZTAxNGFjMDNkYWZkODQyMzM4ZjBlNmQifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vZmV0Y2htZS1