Basic Security Rules with Firebase

I have problems with basic security rules with Firebase (I read the documentation on Firebase and StackExchange, but I can not get the security rules to work):

Model (representation of Emberjs model):

App.User = DS.Model.extend({ uid: DS.attr('string'), displayName: DS.attr('string'), books: DS.hasMany('statistic', { inverse: 'user', async: true}), actions: DS.hasMany('action', { inverse: 'user', async: true}), }); App.Action = DS.Model.extend({ date: DS.attr('date'), actionType: DS.attr('string'), comment: DS.attr('string'), user: DS.belongsTo('user', {inverse: 'actions', async: true} ) }); App.Book = DS.Model.extend({ name: DS.attr('string'), description: DS.attr('string'), user: DS.belongsTo('user', { inverse: 'books', async: true} ) }); 

3 nodes (models) are stored directly in the Firebase root application. Book and Action models have a user field (property).

What are the rules for writing to:

  • Only the user identified in the user field of the book models and actions (nodes) can have read and write access to their own data? (The value of the user field in the book and action must be equal to the value of auth.uid in Firebase, so that the user receives read and write privileges.)
  • So that users can access only the user model information (node) that applies to them?

thanks

+5
source share
1 answer

It is important to understand the data structure in Firebase.

Basically, there are two ways to write security rules. You either set security rules right under the books / or write security rules for each model attribute separately. Or a combination of both, but first make sure you understand the principle from top to bottom.

I prefer to write the rules for each attribute separately, it is easier to maintain and test.

But in your case, since other users do not need access to any part of the books or users, it is easy to write rules for the entire model:

 "rules" :{ "books": { "$book_id": { ".read": "data.child('user').val() === auth.uid && auth !== null", ".write": "!data.exists() && newData.child('user').val() === auth.uid || data.child('user').val() === newData.child('uid').val() && auth !== null" }, "users": { "$user_id": { ".read": "data.child('uid') === auth.uid", ".write": "!data.exists() && newData.child('uid').val() === auth.uid || data.child('uid').val() === newData.child('uid').val()" } } } } 

I have not tested these rules, they may contain flaws, please use the simulator tool to make them bulletproof:]

Check out my middle post for more info: https://medium.com/@martinmalinda/emberfire-is-awesome-but-querying-data-and-writing-security-rules-can-be-a-pain-f5370f4decb

+2
source

Source: https://habr.com/ru/post/1210380/


All Articles