Firebase database security rules allow authenticated user to read and write from their own contents
Asked Answered
E

2

8

Here's my database structure:

 Clients:
     employee1emailaddress
     employee2emailaddress
 Employees:
     employee1emailaddress
     employee2emailaddress
 allClients:
     client1phonenumber
     client2phonenumber

I want to make a security rule to limit the authenticated user to read and write from nodes associated to their email address

For example: the employee who has the email address of employee1emailaddress can only read from and write to the nodes that has their email addresses as the key

How to make that possible ? and thanks in advance..

Eliga answered 2/8, 2018 at 15:57 Comment(3)
What have you tried, and why doesn't it work as you expect?Copyhold
I searched for a way to do this, all the security rules i found are depending on $uid, but as you can see I'm using email address as the key, not the IDEliga
After a few days, I found a way. Please review: #57635684Godbeare
C
9

I would recommend not associating data with a user's email address. You should use their UID instead:

{
  "rules": {
     "$uid": {
        ".read": "auth !== null && auth.uid === $uid",
        ".write": "auth !== null && auth.uid === $uid"
    }
  }
}

This will only allow users to read and write from a directory in your database where the key is their UID.

Censer answered 2/8, 2018 at 16:17 Comment(5)
This would work for all the nodes (Clients & Employees & allClients) Right ? And is there a way to apply this rule for user's email instead ?Eliga
I do believe that there is a way to do this, but using UIDs is better because you won't have to move data if a user changes their email address. While this will work for multiple nodes, any user will be able to edit their own directory on any node. I would recommend tagging the user and only letting them use the proper node, or not dividing the database into three nodes, and instead storing all users together.Censer
@Censer with latest firebase 2023, it errs Error saving rules – Line 3: Unknown variable '$uid'.; Line 4: Unknown variable '$uid'.Sacramentarian
if nested inside $uid:, even ".read": true, denies readingSacramentarian
gist.github.com/codediodeio/6dbce1305b9556c2136492522e2100f6Sacramentarian
L
0
"rules": { ".read": "auth!=null" , ".write":"auth!=null", }
Logotype answered 26/4, 2024 at 12:11 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.