0
votes

How to set security rules for database without user authentication in which user can change there own data only. When app starts for the first time new data item gets added without any authentication with unique ID.

My JSON data looks like this:

{
  "Rand3435" : {
    "Score" : 10,
    "DID" : "Rand3435",
    "CanDance" : "No"
  },
  "Rand7765" : {
    "Score" : 25,
    "DID" : "Rand7765",
    "CanDance" : "Yes"
  },
  "Rand6769" : {
    "Score" : 0,
    "DID" : "Rand6769",
    "CanDance" : "No"
  },
  "Rand1326" : {
    "Score" : 10,
    "DID" : "Rand1326",
    "CanDance" : "No"
  },
  "Rand9879" : {
    "Score" : 10,
    "DID" : "Rand9879",
    "CanDance" : "Yes"
  },
  "Rand5455" : {
    "Score" : 10,
    "DID" : "Rand5455",
    "CanDance" : "No"
  },
  "Rand2322" : {
    "Score" : 19,
    "DID" : "Rand2322",
    "CanDance" : "No"
  }
}

What will be the rules in JSON format to put in the rules section?

Please help, I am new to Firebase. Thanks

2

2 Answers

0
votes
  1. Store unique ID in shared preferences when app starts for first time.
  2. Whenever user want to made any changes to database, check whether unique ID is present in database or not.
  3. If unique ID is present, then user can modify data, otherwise not.
0
votes

If you want to secure access to a user's data, but don't want to require the user to provide credentials, you're looking for Firebase's anonymous authentication. With anonymous authentication you sign the user in with just this simple call:

FirebaseAuth.getInstance().signInAnonymously();

From there on, the user has a UID that identifies them, and you can use this UID in the data to associate data with that user, and then in security rules to ensure only authorized access is allowed as shown in the documentation on user based security.


If you insist on generating your own IDs, you can ensure only someone who knows the ID can write a document with that ID with:

{
  "rules": {
    ".read": false,
    "$DID": {
      // anyone who knows a DID can read its contents
      ".read": true, 

      // anyone who knows a DID can write its contents, as long as they specify the DID in the contents too
      ".write": "newData.child('DID').val() === $DID"
    }
  }
}

So this way the user must specify the same ID in both the DID property and in the path, to be allowed to write. Since there is no read permission on the root, there is no way for someone to get a list of all data (and hence of all DIDs).