Emmet B
Emmet B

Reputation: 5541

Firestore security rules in to prevent sensitive field

I am modeling a database with Firestore, for a small company.

I have a collection of departments. Each department is a document. In the company, there will never be more than 50 employees. I would like to keep each employee as a map.

so a department document will be like this;

{ 
  emp1: { name: 'tom', age:23, email: '[email protected]'},
  emp2: { name: 'mike', age:35, email: '[email protected]'}
}

I would like to keep the age field private, it should be accessed only by superusers. From what I learnt, it is not possible to put access level at the granularity of a field. When a client receives the document, he will have access to all fields.

How can I go about that, I should keep a sub-collection of ages, would that work? Coming from SQL, and already done this smoothly in SQL, I cannot get my head around to have a collection just for a single integer.

Or is there any other alternative? I do not want to have a collection of employees.

Upvotes: 1

Views: 445

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317808

You have data associated with one entity (a user) that should have varying permissions for different fields of that data, it will be easiest if you split those fields into documents in different subcollections organized under that entity. The security rules will be much easier to implement in that case. The case of simple public/private data:

users/{uid}/public
  - data
    - name
    - email
users/{uid}/private
  - data
    - age

Then your rules target each subcollection separately:

match /users/{uid}/public {
  allow read: true;
}

match /users/{uid}/private {
  allow read: if  **...whatever conditions you choose, if any...**
}

Upvotes: 3

Related Questions