Seth Kitchen Seth Kitchen - 1 year ago 50
Javascript Question

How do I let a subfolder be written to EXACTLY one time in firebase?

To link together a group creator with group members, I would like the group creator to submit a connection string that group members can then use to join the group.

Once the connection string is created, however, I do not want anyone but the creator to remove or write over the string or data under the string.

In my javascript I can easily write a checking function to see if it exists:

function tryToAddConnectionString(uid, desiredConnectionString)
firebase.database().ref('/connectionStrings/' + desiredConnectionString).once('value').then(function(snapshot){
//There is no data therefore there is no connection string, so create one.
firebase.database().ref('connectionStrings/' + desiredConnectionString).set({
owner: uid });
//Connection String already exists. Throw "already exists" message

But this does not stop a malicious hacker from going into his/her console and typing

firebase.database().ref('connectionStrings/' + desiredConnectionString).set(null);

Which will delete/take over the group.

Is there a rule I can set to fix this? Also, under


I want people to be able to add themselves as members.

To recap: I am looking for a rule which will allow anyone to create a connectionstring, but only the creator can delete the connection string or change the owner subfolder, but anyone can read/write the members folder.

Thanks in advance.

Answer Source

You can easily do that with security rules:

//add a condition to verify that the node doesn't exist or the
//You must add to your node the aid of the creator
".write":"!data.exist() || auth.uid === data.child('creator')"

You can see what else you can configure here Security Rules Firebase