Reputation: 149
Say my Firebase Database rules look like this:
"rules": {
".read": "auth != null",
".write": "auth != null"
}
In my app I need to check if a username is already taken, and thus I need to do so before authenticating the user. I am aware that I could do something like this:
"rules": {
".write": "auth != null",
"Users": {
".read": true
}
}
However, if I have understood how the rules work correctly, this will make only the "Users" path readable and by default every other path will be set to ".read": false
. My question is therefore how I would make every path readable by an authenticated user, and make an unauthenticated user only able to read data from the path "Users" and nothing else.
Upvotes: 0
Views: 915
Reputation: 7546
Certainly you can make it so one path in the database is readable for unauthenticated users, but I wouldn't recommend it. It's not ideal to allow anyone to read the usernames of all of your users.
One other option is you can create a user first and then have them choose a username once authenticated, but then you'd have to figure out how you wanted to handle users who are authenticated but then exit the app before choosing a username.
A better option is to use Cloud Functions for Firebase with an HTTP trigger, and pass the desired username as part of the request. The request would include a query of the desired username and the response would return whether the username is available or not. It could look something like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.uniqueUsername = functions.https.onRequest((req, res) => {
const username = req.query.username
admin.database().ref('users').orderByChild('username').equalTo(username)once('value').then(snap => {
// if the child exists, then the username is taken
if (snap.exists()) {
res.send('username not available');
} else {
res.send('username available');
}
})
}
If you're new to Cloud Functions for Firebase, then check out these resources:
Getting Started with Cloud Functions for Firebase - YouTube
Cloud Functions for Firebase Documentation
Timing Cloud Functions for Firebase using an HTTP Trigger and Cron - YouTube
Upvotes: 1