Create custom validation on Firebase Database Rules

风流意气都作罢 提交于 2020-01-02 10:15:13

问题


I want to create a chat application using firebase real time db, I already have my own server and my own authentication for my users and recipient.

So basically what I want to do is:

I want my server to able to generate room, and its room secret key, so only to people I share the secret key who can access the room, do read and write

maybe the flow is like this 1. The server create a POST using REST API to this url

curl -X PUT \
https://example-chat-92682.firebaseio.com/order-test.json \ -d 
'{ 
   "UB8Hdazo834-4760": {
     "secret": "secret123"
   }
 }'

So it will generate following structure

- order-test
    - UB8Hdazo834-4760
         secret: "secret123",

2. then I will send the chat room https://example-chat-92682.firebaseio.com/order-test/UB8Hdazo834-4760.json to users

I will send them in json like this

"room": "https://example-chat-92682.firebaseio.com/order-test/UB8Hdazo834-4760.json",
"secret": "secret123"

3. Users receive the payload and use it to join the chat using their ios or android, so the final structure will be like this

- order-test
    - UB8Hdazo834-4760
         secret: "secret123",
         - chat
             - Kifeisufsu23r
                 name: "Bob",
                 message: "How you doin?"
             - Ki4324ffs3fIF
                 name: "Alex",
                 message: "I am fine"

The question is, how do I make Firebase Database Rule to create read and write validation? I have seen the doc, I can't use the Firebase Authentication since I have my own auth and have no control over the auth (different micro service)

the secret will be auto-generated, so there is no way I can hardcode the database rule

If you guys have any feedback on my data structure, I am more than welcome


回答1:


If you have a server, you can mint a custom token for Firebase Authentication to ensure your users are also identified within Firebase. They would then surface as auth and auth.uid in the Firebase Database security rules.

But in your current model, I'd recommend putting the secret into the key of the room:

  • order-test
    • UB8Hdazo834-4760_secret123
      • chat
        • Kifeisufsu23r name: "Bob", message: "How you doin?"
        • Ki4324ffs3fIF name: "Alex", message: "I am fine"

Now you can easily secure access so that only users that know both the room ID and the secret can access it:

{
  "rules": {
    ".write": false,
    "order-test": {
      "$roomIdAndSecret": {
        ".write": true
      }
    }
  }
}


来源:https://stackoverflow.com/questions/43692202/create-custom-validation-on-firebase-database-rules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!