I'm having trouble with rules configuration in Realtime Database. In Realtime Database, I have:
"users": {
"0ayi220wJ0WOHfPftAwaxAAJh3P2": {
"email": "oop3@gmail.com",
"emailVerified": false,
"publicKey": "",
"privateKey": "",
}
}
"0ayi220wJ0WOHfPftAwaxAAJh3P2" is uid.
I'm trying to develop a Chat App in React Native, this is the code to list all the users in database:
onValue(firebaseDatabaseRef(firebaseDatabase, 'users'), async (snapshot) => {
if (snapshot.exists()) {
let stringUser = await AsyncStorage.getItem('user')
let myUserId = JSON.parse(stringUser)['uid']
let snapShotObject = snapshot.val()
// console.log(snapShotObject)
setUsers(Object.keys(snapShotObject).filter((eachKey) => eachKey != myUserId)
.map((eachKey: any) => {
let eachObject = snapShotObject[eachKey]
return {
name: eachObject['email'],
email: eachObject['email'],
userId: eachKey,
}
}))
}
else {
console.log('No data availble')
}
So the app would get email and emailVerified from each uid except my uid (which I get from auth)
When I config rules like bellow, The app can get all data from each uid
{
"rules": {
"users": {
".read": true,
}
}
}
But when I config the rules with wildcard "$uid", my app can't get data from database anymore (Permission denied)
{
"rules": {
"users": {
"$uid": {
".read": true
}
}
}
}
What can I do to use wildcard? I need to use it to authorize who can get privateKey.
Your code tries to read this data from the database:
onValue(firebaseDatabaseRef(firebaseDatabase, 'users')
Since your security rules don't grant anyone read access on /users
, the operation is denied.
You seem to have missed the documentation on the fact that security rules don't filter the data. They don't actually look at the data, but rather "just" make sure that the code only tries to access data that it is permitted to.
You'll need to find a way to read or query only the data that the user has access to. For example, to read the user's own UID only, you can read:
let uid = getAuth().currentUser.uid;
onValue(firebaseDatabaseRef(firebaseDatabase, 'users/'+uid), ...
In other cases, you'll need to use a query and then secure that.
And in yet another set of cases, you can't use a query to meet the security constraints and will instead have to change the data model to allow the use-case.