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

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


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.


Let's start with a sample JSON snippet:

  "book": {
    "-JRHTHaIs-jNPLXOQivY": { //this is the generated unique id
      "title": "Structuring Data",
      "url": "",
      "creator": "twiter:4916627"

    "-JRHTHaKuITFIhnj02kE": {
      "title": "Securing Your Data",
      "url": "",
      "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.


Unlink listener for parent does it applied to children in 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; But I discover that some listeners are still attached. My question is: when you put listeners to off for a parent node does it...

How to see if given object matches one of the objects returned from 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...

Read data from Firebase and hide a class

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...

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

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...

Cross-platform text, image, video Chat for Android, iOS and Web using Firebase/Parse/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...

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

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['$rootScope', '$location', 'AuthenticatorService', function ($rootScope, $location, AuthenticatorService)...

Listen for changes on data in 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: combine filtering with ordering in swift

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 -...

Firebase data ordering

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...

firebase-import timing out?

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...

Iterate nodes to get child key value

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 write denormalized data in 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...

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

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

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

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: 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: {...

Understanding Firebase orderByChild

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...

firebase security permission not working

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": {...

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

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...

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

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 REST API POST request fails with error: “Invalid data; couldn't parse JSON object, array, or value…”

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 to Convert Firebase data to Java Object…?

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...

Saving an html object to firebase

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...

Firebase rules - limit access to owning user

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,...

AngularFire pushing to array doesn't work

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...

How do I Implement a Node.Js server-side event listener for 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...

Angularfire facebook user_friends

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?

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...

Save to 3 firebase locations with a slow internet connection

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: when onDisconnect event fire?

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>"); // stores the timestamp of my last disconnect (the last time I was seen online) final...

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

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...

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

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...

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

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...

Message gurantees on rapidly updated entities in 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...

Firebase data structuring - accessing jobIDs for each user

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"...

Firebase data structure with cyclic dependency

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:...

compile error on FirebaseHandle

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...

How to use Firebase Twitter Authentication with React Native?

How to use Firebase Twitter Authentication with React Native? I tried both of the code below in reference to 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...

Using Chrome Console with 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...

Search inside objects javascript

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:...

FirebaseAuth Memory Leak in Activity

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...

Javascript: Split array of arrays into multiple arrays

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...

No transports available

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 Since upgrading...

AngularJS - Firebase - Promise Error

I am trying to follow a basic tutorial on and am tunning into issues. 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...