Access your own data, shared data, or designated data with Firebase rules

Seeking guidance on implementing firebase rules and queries for Firestore in a Vue.js application.

Requirement: User must be authenticated

  1. User can read/write their own data entries
  2. User can read data with "visibility" field set to "public"
  3. User can read specific entries using document ID, even if "visibility" is not public (e.g. "private")

Assume the collection contains entries created by different users:

  1. User-B can read/write the 2nd entry
  2. User-A, B, C can read 1st and 3rd entries
  3. User-A, C can read 2nd entry with known document ID

Is "user_id" field required to filter self-created documents or does Firebase provide built-in functionality based on authentication?

[
  {
    "user_id": "User-A's firebase id",
    "foo": "foo",
    "bar": true,
    "visibility": "public"
  },
  {
    "user_id": "User-B's firebase id",
    "foo": "foo",
    "bar": true,
    "visibility": "private"
  },
  {
    "user_id": "User-C's firebase id",
    "foo": "foo",
    "bar": true,
    "visibility": "public"
  }
]

Requesting assistance with creating rules and queries using this npm package.

Current query for retrieving self-created entries:

this.db.collection("my_collection").where('user_uid','==',this.$store.state.user.id).get().then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        //do something 
      });
    });

Create entry query:

db.collection("my_collection").add({
    user_uid: this.$store.state.user.id,
    foo: this.foo,
    bar: this.bar,
    visibilty: this.visibility
  })

Existing rule:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

Answer №1

When it comes to Firestore, there is no automatic linking of documents to the users who created them. If you require such metadata, it must be stored in each document individually.

In order to ensure that a user is only able to access their own documents, two key elements are necessary:

  1. A tailored query that specifically targets and retrieves those particular documents – which you already have covered ✔.
  2. Rules need to be put in place to permit the query while blocking broader data access requests.
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null && request.auth.uid == resource.data.user_uid;
    }
  }
}

To delve deeper into this topic, refer to the documentation on securely querying data.


If you wish to accommodate other scenarios, you will need to expand your rules to grant access accordingly. However, keep in mind that separate queries will be necessary for each case since Firestore queries cannot encompass OR conditions across multiple fields – a requirement specific to your use-case.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sails.js navigating through sessions

What is a rolling session in Sails.js? A rolling session is a session that expires after a set amount of time without user activity, except for websockets live updating data. If the user navigates to a different part of the site before the session expires, ...

Tips for improving performance with ng-repeat directive?

I have encountered some performance issues while using socket.io with the ng-repeat directive in Angular. The application slows down significantly when receiving a large amount of data from the backend, making it impossible to interact with the app. What w ...

What sets MongoDB Shell Scripting apart from JavaScript?

I'm currently working on a homework assignment and I prefer not to share my code as it would give away the solution. However, I can provide some generic snippets. I must admit, I am a novice when it comes to javascript and Mongo, and I only learned ab ...

Searching for matching strings in jQuery and eliminating the parent div element

Here's an HTML snippet: <div id="keywords"> <div id="container0"> <span id="term010"> this</span> <span id="term111"> is</span> <span id="term212"> a</span> <span ...

The design template is failing to be implemented on my personal server utilizing node.js

I've encountered an issue while developing the signup page on my local server using Bootstrap 4. The CSS is not getting applied properly when I run it locally, although it displays correctly in the browser. Can someone explain why this is happening? ...

Error message: 'Vue is not defined' when using RequireJS

I'm facing an issue where the Vue object appears to be undefined in the browser after loading Vue with RequireJS. I'm puzzled by this situation and would appreciate any guidance that could help me narrow down the problem. It's worth mention ...

Performing mathematical computations through a mixin without relying on inline javascript code

Looking to enhance my web app with a mixin that shows a list of entries, each with a time stamp indicating how long ago it was posted. mixin listTitles(titles) each title in titles article.leaf article a.headline(href=title.URL)= title.t ...

What is the most efficient way to organize an array by date?

Here is the data I have: const data = [{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44}, {date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53}, {date: "2022-05 ...

Ensure the buttons within v-card-actions are responsive to different screen sizes

I am facing an issue with a v-card that contains three buttons (v-btn) within v-card-actions. Each button has long text on it, which is causing alignment problems on small screens. The buttons are not responsive and are still aligned horizontally from left ...

Webpack is throwing an error stating that it cannot find a module with the relative path specified

Here is the structure of my app (excluding the node_modules directory): ├── actions.js ├── bundle.js ├── components │   ├── App.js │   ├── Footer.js │   ├── Link.js │   ├── Todo.js │   └─ ...

Issue with the dueChange event not functioning properly in Ionic 5 and Vue 3 duet picker

I have integrated the Duet Date Picker into my Ionic 5/ Vue 3 application, but I am facing an issue with the event listener for duetChange not working as expected. Below is a snippet of my code: <duet-date-picker @duetChange="handleInput($event)&q ...

Ways to efficiently transfer multiple files from a server to a client using Express in NodeJS

I am working on a NodeJS server to transfer various files, such as images, css files, and js files, to clients. Currently, I have the following code snippet for sending individual files: app.get('/js/client.js', function (req, res) { res.sendF ...

Create a website specifically designed to showcase the functionality and capabilities of an API

As a junior front-end developer, I am looking to build a simple API. I have already deployed a mock version of this API on Heroku (accessible at this link) using Express. My goal is to create a website with Vue.js where the root path is dedicated to the w ...

Using jQuery code within PHP pages is a convenient and powerful way to

I am currently facing an issue with PHP and jQuery. Here is the structure of my website: header.php - contains all css and js files. index.php - main page. sidemenu.php - includes the side menu in index.php Within sidemenu.php, I have the following JS ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

Having issues with setting up nodejs on kali linux

Whenever I try to execute the configure script ./configure for nodejs installation, it fails to run successfully. Traceback (most recent call last): File "./configure", line 19, in <module> from distutils.spawn import find_executable ModuleN ...

The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the ...

When implementing require('devtron').install(), it triggers the error message "Uncaught TypeError: Cannot read property 'BrowserWindow' of undefined" within an Electron application

I'm attempting to install devtron's developer tools from the Electron application developer console. However, I encountered an error when trying to run the install command: > require('devtron').install() Uncaught TypeError: Cannot r ...

Drop-down menu for every individual cell within the tabular data

I'm working with a large HTML table that looks like this: <table> <tr> <td>value1</td> <td>value2</td> </tr> <tr> <td>value3</td> <td>value4 ...

Is the reference to a variable within an array maintained by JavaScript?

I'm working with react code and using the find() method to select an item from an array. When I retrieve an item from the array, is JavaScript copying the item or returning a reference? EDIT: The items in my array are objects, such as [{id: 12, name ...