Reputation: 4344
I'm wrestling with Firebase realtime database rule structures. I need to validate a user registration code input in order to write to the database. I'm validating the code in the frontend right now and I'm trying to find a way to do the same through Firebase rules without storing the submitted code.
For example, an object to send would be:
{
"courseId": "A1",
"code": "codeToMatch"
}
The intended database structure is:
{
courses: {
"A1": {
"code": "codeToMatch",
"date": "2018-07-01T08:00:00.000Z",
"members": {
"abcd1234": true,
"efgh5678": true
},
}, ...
}
}
The best I've been able to do so far is:
{
courses: {
"A1": {
"code": "codeToMatch",
"date": "2018-07-01T08:00:00.000Z",
"members": {
"abcd1234": {
"code": "codeToMatch",
"true": true
},
...
},
}, ...
}
}
I'd like to push to courses/{courseId}/members/{uid}
, with members
storing all registered users.
Rules
{
"rules": {
".write": "auth != null", // Allow any authorized user to write
"courses": {
".read": "auth != null",
"$courseId": {
"members": {
"$uid": {
".validate": "root.child('courses').child($courseId).child('code').val() == newData.child('code').val()" // only write if it's valid
}
}
}
}
}
}
Is there a way to send an object with some kind of value for validation only?
Upvotes: 0
Views: 317
Reputation: 153
I'm not sure if there is a way to do this without storing the code. You could always just store the code instead of "true" since true doesn't help you in any other way. If you are checking the value in another database, you would just check if the user ID exists under "members".
{
courses: {
"A1": {
"code": "codeToMatch",
"date": "2018-07-01T08:00:00.000Z",
"members": {
"abcd1234": codeToMatch,
"efgh5678": codeToMatch
},
}, ...
}
}
Another option is to use a Cloud Function to check the code and make the appropriate update.
Upvotes: 0