firebase,angularfire,firebase-security,firebase-authentication , Understanding Firebase's rules for user-write, global-read


Understanding Firebase's rules for user-write, global-read

Question:

Tag: firebase,angularfire,firebase-security,firebase-authentication

I am building a simple Firebase application with AngularJS. This app authenticates users through Google. Each user has a list of books. Anyone can see books, even if they are not authenticated. Only the creator of a book can edit it. However, individual users need to be able to record that they've read a book even if someone else added it.

I have rules.json like so:

{
  "rules": {
    ".read": false,
    ".write": false,
    "book": {
      "$uid": {
        ".write": "auth !== null && auth.uid === $uid",
      }
      ".read": true,
    }
  }
}

And I am trying to write a book simply with:

$firebaseArray(new Firebase(URL + "/book")).$add({foo: "bar"})

I get a "permission denied" error when trying to do this although I do seem to be able to read books I create manually in Forge.

I also think that the best way to store readers would be to make it a property of the book (a set of $uid for logged-in readers). ".write" seems like it would block this, so how would I do that?

"$uid": {
  ".write": "auth !== null && auth.uid === $uid",
  "readers": {
    ".write": "auth !== null"
  }
},

It seems like a validation rule would be appropriate here as well ... something like newData.val() == auth.uid, but I'm not sure how to validate that readers is supposed to be an array (or specifically a set) of these values.


Answer:

Let's start with a sample JSON snippet:

  "book": {
    "-JRHTHaIs-jNPLXOQivY": { //this is the generated unique id
      "title": "Structuring Data",
      "url": "https://www.firebase.com/docs/web/guide/structuring-data.html",
      "creator": "twiter:4916627"

    },
    "-JRHTHaKuITFIhnj02kE": {
      "title": "Securing Your Data",
      "url": "https://www.firebase.com/docs/security/guide/securing-data.html",
      "creator": "twiter:209103"
    }
  }

So this is a list with two links to articles. Each link was added by a different user, who is identified by creator. The value of creator is a uid, which is a value that Firebase Authentication provides and that is available in your security rules under auth.uid.

I'll split your rule into two parts here:

{
  "rules": {
    ".read": false,
    "book": {
      ".read": true,
    }
  }
}

As far as I see your .read rule is correct, since your ref is to the /book node.

$firebaseArray(new Firebase(URL + "/book"))

Note that the ref below would not work, since you don't have read-access to the top-level node.

$firebaseArray(new Firebase(URL))

Now for the .write rules. First off is that you'll need to grant users write-access on the book level already. Calling $add means that you're adding a node under that level, so write-access is required.

{
  "rules": {
    "book": {
      ".write": "auth != null"
    }
  }
}

I leave the .read rules out here for clarity.

This allows any authenticated user to write to the book node. This means that they can add new books (which you want) and change existing books (which you don't want).

Your last requirement is most tricky. Any user can add a book. But once someone added a book, only that person can modify it. In Firebase's Security Rules, you'd model that like:

{
  "rules": {
    "book": {
      ".write": "auth != null",
      "$bookid": {
        ".write": "!data.exists() || auth.uid == data.child('creator').val()"
      }
    }
  }
}

In this last rule, we allow writing of a specific book if either there is no current data in this location (i.e. it's a new book) or if the data was created by the current user.

In the above example $bookid is just a variable name. The important thing is that the rule under it is applied to every book. If needed we could use $bookid in our rules and it would hold -JRHTHaIs-jNPLXOQivY or -JRHTHaKuITFIhnj02kE respectively. But in this case, that is not needed.


Related:


Search inside objects javascript


javascript,object,firebase
I'm experimenting on login with firebase. I can make an account, and it'll store additional information too. The problem is retrieving this information. I can get it using: usersRef.on("value", function(snapshot) { console.log(snapshot.val()) }, function (errorObject) {...}); When I do this I get two things (because I have two accounts): -JrrzEOqZQU0HVeYVXCm:...

Javascript: Split array of arrays into multiple arrays


javascript,arrays,charts,firebase,flot
serious problem here, I have an array like this: [[0,50],[0,68],[1,26],[2,9],[2,32]] The form I need is to split this array into two separated arrays like this: array1 = [[0,50][1,0][2,9]] array2 = [[0,68][1,26][2,32]] Yeah you are right guys, I need that to build flot chart. If anybody interested in source of data...

Firebase data structure with cyclic dependency


android,database-design,structure,firebase
I'm currently discovering Firebase and trying to evaluate it for further projects. At the moment, i'm testing with a very simple "Todo list" app where lists can be shared with friends. I've read the Doc about flattening data structure to avoid complexity and I came up with the following structure:...

How to see if given object matches one of the objects returned from firebase


javascript,object,firebase
I am trying to test if the given object matches the stored objects that are stored and returned from firebase. If it does then return true or store true in a variable. Here is the example of given object and firebase returned data given object: {name: "John", age: "32"} stored...

Saving an html object to firebase


javascript,canvas,ember.js,firebase,emberfire
I'm working in ember.js my project has an image cropping mechanic. This returns to me by default a canvas object and some data necessary to redraw the cropped image. But when I try to save the canvas object to firebase it saves it as something like [htmlObject Canvas] or something...

I'm using AngularFire, How can I retrieve this “email”, “uid” data?


angularjs,object,firebase,angularfire
JS CODE var myFirebaseRef = new Firebase('https://blinding-inferno-7068.firebaseio.com/'); var createdUserRef = myFirebaseRef.child('users').child('createdUser'); $scope.users = $firebaseArray(createdUserRef); HTML CODE <ul ng-repeat="user in users"> <li>{{user.uid}}</li> <li>{{user.email}}</li> <li>{{user}}</li> </ul> What I wanted was user.uid and user.email, but those thing didn't come out. So I checked the user object, and these things came out....

Using Chrome Console with Firebase


javascript,console,firebase
As a js newbie, this is probably a dumb question. But how can I actually use js within a Chrome console. I am trying to interact with my Firebase via the console but when I try to get the Firebase reference I keep getting undefined. I know I can use...

Cross-platform text, image, video Chat for Android, iOS and Web using Firebase/Parse/PubNub


android,ios,parse.com,firebase,pubnub
I want to develop a cross platform chat application which I can use to send text,url,image,location,video to my friends which can be on android/ios/web. I want chat to be realtime, and want to make sure that even if user is not using application, he get a 'Notification' for new incoming...

compile error on FirebaseHandle


ios,swift,firebase
I got compile error when I tried to keep a reference to the handled returned by observeEventType call as suggested in the firebase iOS doc firebaseHandle = messagesRef.observeEventType(FEventType.ChildAdded, withBlock: { (snapshot) in error is: Cannot assign a value of type 'UInt' to a value of type 'FirebaseHandle!' this is the...

Unable to get my data from $firebaseObject using AngularFire in a controller. View/ng-repeat works fine


angularjs,firebase,angularfire
I have different sections in Firebase with normalized data, and I have routines to get the information, but I cannot loop through the returned records to get data. I want to use the keys in the $firebaseArray() to get data from other $firebaseObject(). GetOneTeam() .... { var DataRef = GetFireBaseObject.DataURL(Node...

Unlink listener for parent does it applied to children in Firebase


javascript,firebase
I am using firebase to synch data in a real time app. After some treatment, I want to unlink all listeners added. So I put myRef.off(); But I discover that some listeners are still attached. My question is: when you put listeners to off for a parent node does it...

Understanding Firebase's rules for user-write, global-read


firebase,angularfire,firebase-security,firebase-authentication
I am building a simple Firebase application with AngularJS. This app authenticates users through Google. Each user has a list of books. Anyone can see books, even if they are not authenticated. Only the creator of a book can edit it. However, individual users need to be able to record...

Firebase: when onDisconnect event fire?


android,firebase,firebase-android
I`m using Firebase-backend for my android applicaion. I'd like to build a users presence system for my chat. For this purpose I've taken the pattern from Firebase Guide final Firebase myConnectionsRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/users/joe/connections"); // stores the timestamp of my last disconnect (the last time I was seen online) final...

Iterate nodes to get child key value


javascript,node.js,firebase
So here is how my test firebase looks I want to be able to go through the entire list and match the name with a string and if it matches, return the CID. This is what I'm trying from the official documentation but it returns undefined. fb.on('value', function(snapshot){ var data...

How to Convert Firebase data to Java Object…?


java,android,firebase
Using Firebase Library to send data to the server in the form Message(String,String) added to the HashMap Example: Firebase fb=new Firebase(URL); Firebase msgRef = fb.child("finished"); HashMap<String, Message> msgList = new HashMap<>(); Message msg = new Message(m, n); msgList.put(HASHKEY, msg); msgRef.push().setValue(msgList); While Receiving Data with firebase method addValueEventListener() getting String in...

Upload single file to firebase hosting via CLI or other without deleting existing ones?


firebase,firebase-hosting
Question: How to upload a single file to firebase without deleting existing files? Details: Intent: upload single file without deleting existing files on server Usage: have separate directories on local machine each uploading to a specific folder on server What I've tried: overriding the public dir with firebase deploy -p...

Save to 3 firebase locations with a slow internet connection


javascript,angularjs,firebase,latency
Sometimes I'm having issues with firebase when the user is on a slow mobile connection. When the user saves an entry to firebase I actually have to write to 3 different locations. Sometimes, the first one works, but if the connection is slow the 2nd and 3rd may fail. This...

Firebase data ordering


android,firebase
I feel as if I'm missing something big when I use firebase in my android app. I have been using push(); to put my data in firebase with a unique id. I have been accessing this data in an activity using the ChildEventListener: ref.addChildEventListener(new ChildEventListener() { // Retrieve new posts...

AngularJS: Uncaught ReferenceError: $rootScope is not defined in run


javascript,angularjs,firebase,angularjs-service,angularfire
I am trying to route all unauthorized traffic to the login page, and am using angularfire to authenticate. Here's all the relevant code. I know most of it is broken, but I'd like to get past this first. The problematic code is: App.js app.run(['$rootScope', '$location', 'AuthenticatorService', function ($rootScope, $location, AuthenticatorService)...

Angularfire facebook user_friends


angularjs,facebook,firebase,angularfire
Using facebook authentication with angularFire, I don't see "user_friends" in the Auth object that is returned. ng-click="auth.$authWithOAuthPopup('facebook',{scope:'user_friends'})" This works fine for grabbing the uid, and I see the facebook object which contains the "accessToken", "cachedUserProfile" etc., but no "user_friends". Someone is have a similar issue here with the "email" object:...

How do I give read/write access to all nodes with Firebase rules?


firebase,rules
Default setting gives full access: { "rules": { ".read": true, ".write": true } } For the sake of testing my understanding of rule-writing from the Firebase guide and documentation, I'm (now retreating to) trying to achieve the same results by writing rules for the 4 parent nodes. If it makes...

Message gurantees on rapidly updated entities in Firebase


firebase
I'd like to understand how Firebase and listening Clients behave in the situation where a large number of updates are made to an entity in a short amount of time, and a client is listening to 'value' changes on that entity. Say I have an entity in firebase with some...

AngularJS - Firebase - Promise Error


javascript,angularjs,firebase
I am trying to follow a basic tutorial on thinkster.io and am tunning into issues. https://thinkster.io/learn-to-build-realtime-webapps/ The tutorial uses an depreciated SimpleLogin, so I have changed the code accordingly however I keep getting an error as follows. TypeError: Cannot read property 'finally' of undefined at Scope.$scope.register (http://localhost:9000/scripts/controllers/auth.js:9:31) I believe the...

FirebaseAuth Memory Leak in Activity


android,memory-leaks,firebase,firebase-android,leakcanary
I added the awesome LeakCanary library in my app and pretty soon I started to receive various reports for a leak generated by the FirebaseAuth Object that I use in the various activities. Now my question is: is it a leak generated by the Firebase library itself or I should...

Firebase REST API POST request fails with error: “Invalid data; couldn't parse JSON object, array, or value…”


jquery,ajax,firebase
I'm trying to use Firebase REST API to save stuff into my data store. I tried with jQuery and vanilla JS XHR. However, both give the same error. 403 Bad Request and this response: Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your...

How do I Implement a Node.Js server-side event listener for Firebase?


javascript,node.js,windows-8,firebase
I'm trying to listen for data changes in my firebase using firebase's package for Node. I'm using the on() method which is supposed to listen for changes non-stop (as opposed to once() method that only listens to the first occurrence of a specific event ) My listener.js file on the...

Read data from Firebase and hide a class


jquery,firebase
I have a Firebase database with users in it with the following data: name: Some Name email: [email protected] tier: standard or premium I'd like to hide the class ".premium-feature" when the the Firebase data for 'tier' reads standard. If the data for 'tier' reads as anything else, I'll need to...

Firebase: combine filtering with ordering in swift


swift,filter,order,firebase
So I have a sports app, which handle matches and championships data. I have two displays using the same data: All future matches All future matches from a certain championship The data is structured like this - championships - libertadores - name: Libertadores da América - matches - 2j6g42kjhg62 -...

Authentication error “Access Denied” in AngularFire when using Internet Explorer 9


firebase,firebase-security
I'm using Firebase for simple email/password authentication. Logging in (using the AngularFire client) works fine on both Firefox and Chrome, but on IE9 I get an "Access Denied" error. At this point I have no security rules established, so by default all requests should go through. I've tried loosening the...

What would be a regular expression that can test if a string is a valid Firebase key?


regex,firebase
I'm writing an application that allows users to input values that will be stored in Firebase as a key. Firebase Key Requirement: max size - 768 bytes cannot contain . $ # [ ] / or ASCII control characters 0-31 or 127 allows single spaces, but not double or more...

Listen for changes on data in Firebase (AngularFire)


javascript,angularjs,firebase,angularfire
Is it possible to listen for Firebase server updates on the DOM in AngularFire? I want to be able to fetch any updates when they are returned from the server to update the values of an array. Basically my problem is that I am using Firebase.ServerValues.TIMESTAMP which is set by...

firebase-import timing out?


json,node.js,firebase
I'm using the firebase-import tool to upload JSON data to my firebase. I consistently get the following error after trying to upload a JSON file that is ~40MB in size. Any ideas why? The output seems to be intentionally cryptic. It always happens when the upload is 42% complete, and...

Understanding Firebase orderByChild


firebase
Here's an example. (Note: The data in firebase is NOT changing. This is to eliminate one variable. In other words, I loaded the data and now it is static.) I'm testing if I'm receiving the correct results from the orderByChild call. I do this in the curl commands below. Please...

No transports available


sockets,firebase,react-native
I recently was trying to upgrade my react-native app to use react-native 0.5.0 and firebase. According to this article the react-native sockets are working and the full firebase sdk should be available. I was previously using firebase-debug and @badfortrains react-native fork with success following the example project https://github.com/badfortrains/wsExample. Since upgrading...

How to use Firebase Twitter Authentication with React Native?


twitter,firebase,react-native
How to use Firebase Twitter Authentication with React Native? I tried both of the code below in reference to https://www.firebase.com/docs/web/guide/login/twitter.html var Firebase = require("firebase"); var App = React.createClass({ render: function() { return ( <View> <Text onPress={this._handlePress}> Twitter login </Text> </View> ); }, _handlePress: function () { var myApp = new...

AngularFire pushing to array doesn't work


javascript,arrays,angularjs,firebase,angularfire
I'm developing a contact book application that can have groups with members in them. A member has a name, title, and email but that is not important. I have following controller that has an array of all groups, and an index of which group I'm currently dealing with. Also, there...

Using $loaded with $firebaseObject to update value VS firebase SDK update. Pros and Cons


angularjs,firebase,angularfire
Let's say I have a service deal with Firebase operation: angular.module('myApp').factory('taskOfferService', ['FURL', '$firebaseArray', '$firebaseObject', '$q', 'taskService', taskOfferService]); function taskOfferService(FURL, $firebaseArray, $firebaseObject, $q, taskService) { var ref = new Firebase(FURL); var Offer = { acceptOffer: function(taskId, offerId, runnerId) { var offerRef = ref.child('taskOffers').child(taskId).child(offerId); var taskUpdate = $q.defer(); offerRef.update({accepted: true}, function(error) {...

Firebase data structuring - accessing jobIDs for each user


javascript,database,database-design,firebase
In my database, I currently have two kinds of objects, users and jobs. I am already storing userIDs in jobs. Do I also need to store jobIDs in each user? A typical user: "-JqzUjcOfddBNd_HtjKb" : { "contact" : { "-JqzWcIyD77ZwatEKALp" : { "email" : "[email protected]" }, "-JqzWrtyni3ZGOKooNF7" : { "email"...

My data is being written to Firebase database but i can't read it why?


json,database,osx,swift,firebase
I'm new to swift and databases. All I'm trying to do is read from my firebase database. I'm using the example code provided here: https://www.firebase.com/docs/ios/guide/retrieving-data.html. I'm calling this from my viewcontroller.swift file in override func viewDidLoad(){} func getRootRef(){ // Read data and react to changes println("entered getRootRef") myRootRef.observeEventType(.Value, withBlock: {...

How to write denormalized data in Firebase


javascript,database,web,firebase
I've read the Firebase docs on Stucturing Data. Data storage is cheap, but the user's time is not. We should optimize for get operations, and write in multiple places. So then I might store a list node and a list-index node, with some duplicated data between the two, at very...

Firebase rules - limit access to owning user


facebook,firebase
My app is using Firebase's Facebook authentication and I have the following users collection: { "fsdjf34hf98wjefj" : { "uid" : "facebook:543634634536" }, "3298djwhy9hwd34234" : { "uid" : "facebook:7658899965432" } } I'm trying to restrict access so that a user can view only his own user: { "rules": { ".write": true,...

firebase security permission not working


firebase,firebase-security,firebase-authentication
I have below data stored in my firebase: firebaseRoot admins simplelogin:1: users simplelogin:1 email: [email protected] picture: csd provider: password uid: simplelogin:1 simplelogin:2 email: [email protected] picture: zsd provider: password uid: simplelogin:1 and following security rules: { "rules": { "admins": { ".read": "root.child('admins').child(auth.uid).val() === true", ".write": "root.child('admins').child(auth.uid).val() === true" }, "users": {...