Is it possible to set a firebase storage rule to watch the value of a piece of state?
I am not using firebase auth for my app I just want to use a bucket for file storage. I have a state variable within my app:
const [state, setState] = useState({
currentUser: null,
isAuthed: false
});
If the user is authenticated the isAuthed
value will flip to true. Therefore would it be possible to write a rule set that looks as so:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if state.isAuthed === true;
}
}
}
CodePudding user response:
Your post raises two questions:
How to pass data to storage rules?
How to check for authentication status without using firebase authentication?
✉️ Passing data to storage rules
File path
You could save your file to the path /userfiles/authenticated/...
to signal that the file was uploaded by an authenticated user. In the storage rule, you have access to the path through the match clause:
match /userfiles/authenticated/{allPaths=**} {
allow read, write: if true;
}
Custom metadata
When uploading a file you can set custom metadata this way:
const metadata = { customMetadata: { isAuthed: true } };
const uploadTask = uploadBytes(storageRef, file, metadata);
Then you can read the metadata in the storage rules:
match /{allPaths=**} {
allow read, write: if request.resource.metadata.isAuth == true;
}
Custom claims or custom tokens
Custom claims or custom tokens allow assigning data to a user in a secure way, this data is then passed to the storage rule. Custom claims necessitate using firebase authentication, but custom tokens allow you to assign a token from your server without using firebase authentication. To read the data:
match /{allPaths=**} {
allow read, write: if request.auth.token.isAuth == true;
}