I cannot get this firestore rule to work.
I want to write/read to user-read-only/USER-ID-HERE/business/settings
service cloud.firestore {
match /databases/{database}/documents {
match /user-read-only/{userId} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
match /{document=**} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
}
}
}
}
I continue to get the message
FirebaseError: Missing or insufficient permissions.
I have tried many different approaches with the simulator and they are all successful, but I can’t repro from my app.
Does anything look incorrect above?
Can the above be simplified? I would like the user to be able to control everything beyond {userId}
How do I know if request.auth.uid and userId are populating properly?
This works
service cloud.firestore {
match /databases/{database}/documents {
match /{userId}/{document=**} {
allow read, write;
}
}
}
This does not work
service cloud.firestore {
match /databases/{database}/documents {
match /{userId}/{document=**} {
allow read, write: if request.auth.uid == userId;
}
}
}
Update following your comment "The intent is to expand the rule so that anything beyond {userId} can be managed by the user":
service cloud.firestore {
match /databases/{database}/documents {
match /user-read-only/{userId}/{document=**} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
}
}
}
Just note that the create rule (copied from your question) allows any authenticated user to write under any {userId} folder.
(On the opposite if you just want to declare a rule for business/settings sub-collection and doc) the following should do the trick:
service cloud.firestore {
match /databases/{database}/documents {
match /user-read-only/{userId}/business/settings {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
}
}
}
In order to be sure that userId is populated properly, you could add it as a field to the document when created and check in the rules for create that it is correct, as follows:
allow create: if request.auth.uid != null && request.auth.uid == request.resource.data.userId;
On the other hand, Firebase Auth will automatically ensure that request.auth.uid is correctly populated.
Finally, you may watch this very good video from the Firebase team about Security Rules : https://www.youtube.com/watch?v=eW5MdE3ZcAw
Here is the HTML page used for testing. Just change the value of userId with the different user's ID.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: 'xxxxx',
authDomain: 'xxxxx',
databaseURL: 'xxxxx',
projectId: 'xxxxx'
};
firebase.initializeApp(config);
firebase
.auth()
.signInWithEmailAndPassword('xxxxxx#gmail.com', 'yyyyyyy')
.then(userCredential => {
const userId = userCredential.user.uid;
// Replace with another userId to test
//e.g. const userId = 'l5Wk7UQGRCkdu1OILxHG6MksUUn2';
firebase
.firestore()
.doc('user-read-only/' + userId + '/business/settings4')
.set({ tempo: 'aaaaaaa' })
.then(() => {
return firebase
.firestore()
.doc(
'user-read-only/' + userId + '/testC/1/collec/2'
)
.get();
})
.then(function(doc) {
if (doc.exists) {
console.log('Document data:', doc.data());
} else {
// doc.data() will be undefined in this case
console.log('No such document!');
}
})
.catch(function(error) {
console.log('Error getting document:', error);
});
});
</script>
</head>
<body>
</body>
</html>
Did you deploy security rules?
See: https://firebase.google.com/docs/firestore/security/get-started#deploying_rules
Before you can start using Cloud Firestore from your mobile app, you will need to deploy security rules. You can deploy rules in the Firebase console or using the Firebase CLI.
Did you have loggedin using Firebase Authentication?
See: https://firebase.google.com/docs/firestore/security/rules-conditions
If your app uses Firebase Authentication, the request.auth variable contains the authentication information for the client requesting data. For more information about request.auth, see the reference documentation.
How do you call Firestore method?
See:
https://firebase.google.com/docs/firestore/data-model
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#currentuser
https://firebase.google.com/docs/reference/js/firebase.User
Like this?
var userId = firebase.auth().currentUser.uid
var docRef = db.doc(`user-read-only/${userId}/business/settings`);
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
I think you should change structure data.
A structure data should be like db.collection('coll').doc('doc').collection('subcoll').doc('subdoc').
(Collections->doc->SubCollections->SubDoc->SubSubCollections->SubSubDoc)
So {userId} should be docId. Not collections.
The security rules should be the this.
match /databases/{database}/documents {
match /users/{userId} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
match /settings/{setting} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
}
}
}
The settings collection ref is db.collection('users').doc(userId).collection('settings').
If does not work then you should try basic rule sets.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
Related
I want to create new rules for my client - one client can create one document in collection.
match /Users/{userId} {
allow update, delete: if request.resource.data.uid == uid;
allow create: if
request.data.uid != request.resource.data.uid;
if request uid == request.resource.data.uid; he cannot.
If you want each user to only be able to create a single document, that is easiest if you use the user's UID as the document ID. In JavaScript that'd be something like this:
import { doc, setDoc } from "firebase/firestore";
import { getAuth } from "firebase/auth";
const user = getAuth().currentUser;
await setDoc(doc(db, "Users", user.uid), {
displayName: user.displayName,
});
You can then enforce this content-owner only access in security rules with:
service cloud.firestore {
match /databases/{database}/documents {
// Allow only authenticated content owners access
match /Users/{userId}/{documents=**} {
allow write: if request.auth != null && request.auth.uid == userId
}
}
}
The main difference with your approach is that we don't check the data of the document, but instead check the document ID (which we set to the UID in our code) to the UID on the request.
My project has 2 main collections: "contact" and "albums".
Here is my data structure
I am trying to assign full read access to everyone in the "albums" collection and to restrict write access to unauthenticated users.
At the same time, i want to assign write access to unauthenticated users and read, update, delete to authenticated users in the "contact" collection.
The current ruleset fails in the rules simulator both for authenticated requests and unauthenticated requests. Rules are as follows:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /contact/{document=**} {
allow create;
allow read, update, delete: if request.auth != null;
}
}
match /albums/{document=**}{
allow read;
allow write: if request.auth != null;
}
}
And the firebase query returns "Uncaught Error in onSnapshot: FirebaseError: Missing or insufficient permissions."
Query below:
useEffect(() => {
const unmount = firestore
.collection("albums")
.orderBy("date", "asc")
.onSnapshot((snapshot) => {
const tempAlbums = [];
snapshot.forEach((doc) => {
tempAlbums.push({ ...doc.data(), id: doc.id });
});
setAlbums(tempAlbums);
});
return unmount;
}, []);
Any ideas on how to correct the rules?
There is a typo in your rules. It should be like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /contact/{document=**} {
allow create;
allow read, update, delete: if request.auth != null;
} //The /albums path must be included inside /documents
match /albums/{document=**}{
allow read;
allow write: if request.auth != null;
}
}
}
Hello I am working with Firestore and flutter. I need to check the username availability when someone creates a new account.
I want to make that when the user is not connected in the app, the field 'username' of the collection "User Data" can be access with get().
However, the code in rules return several errors of 'expected {' but even if I add the '{', it stills does not accept it.
The code in rule that doesn't work and firebase won't allow me to install this rule:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
match /User Data/{User Data} {
allow read: true;
}
}
What I've tried so far :
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
match /User Data/{User Data} {
allow read: request.resource.data == resource.data.username;
}
}
The code in flutter :
Future<bool> checkUsernameAvailability(String val) async {
final result = await Firestore.instance.collection("User Data").where('username', isEqualTo: val).getDocuments();
return result.documents.isEmpty;
}
onPressed: () async {
final valid = await checkUsernameAvailability(_usernameController.text);
if (!valid) {
error = AppLocalizations.of(context)
.translate('this_username_is_not_available');
} else if (_formKey.currentState.validate()) {
setState(() => loading = true);
dynamic result =
await _auth.registerWithEmailAndPassword(
_emailController.text,
_passwordController.text,
_nameController.text,
_usernameController.text);
if (result == null) {
setState(() {
loading = false;
error = AppLocalizations.of(context)
.translate('please_enter_email');
});
}
}
}
All help is welcomed thanks!
You can seperately write security rules for all collections. When you use match /{document=**} expression to allow read and write for authenticated users, it overrides other rules.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /User Data/{User Data} {
allow read: request.resource.data == resource.data.username
allow write: if request.auth.uid != null;
}
}
In my application, once the user is logged in via Firebase auth, I want to fetch additional data from my firestore database.
I do not want users to be able to look at other user's documents, therefore I created a rule for this:
match /users/{userId} {
function isAuthenticated() {
return request.auth != null;
}
function userIsSelf() {
return request.auth.uid == userId;
}
allow read: if
isAuthenticated()
&& userIsSelf();
}
In my head, what I wrote should in theory allow the current logged in user to see data only about himself, and this worked fine in the "rules playground".
However, when I try this code in in the app, I get an error: FirebaseError: Missing or insufficient permissions.
I think this has something to do with the way firestore fetches the data?
The way I query this is by fetching the collection users with a where that only returns users that has uid same as logged in user:
const querySnapshot = await firebase.firestore().collection("users").where("uid", "==", uid).get().catch(err => {
console.error('could not fetch user', err)
})
if (!querySnapshot || querySnapshot.empty) {
dispatch('logout')
throw new Error('Cannot find logged in user\'s data in database')
}
const userData = querySnapshot.docs[0].data()
commit('setUser', userData)
I created my firestore rules to look like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isAuthenticated() {
return request.auth != null;
}
function isAdmin(uid) {
return get(/databases/$(database)/documents/users/$(uid)).data.role == 'admin'
}
// Allow admin to do everything
match /{document=**} {
allow read, write: if isAdmin(request.auth.uid)
}
// Only allow users to read/write to themselfs
match /users/{userId} {
function userIsSelf() {
return request.auth.uid == userId;
}
function roleIsUserOrSameAsDocument() {
return request.resource.data.role == 'user' || request.resource.data.role == resource.data.role;
}
allow read: if
isAuthenticated()
&& userIsSelf();
allow write: if
isAuthenticated()
&& userIsSelf()
&& roleIsUserOrSameAsDocument();
}
}
}
Your query doesn't match your rules. Your query is attempting to get all documents where the uid field matches the provided uid:
firebase.firestore()
.collection("users")
.where("uid", "==", uid)
But your rules are saying that users may only access the individual document with the ID that matches their UID. The rule is going to reject this query every time, because it's not looking at the document ID at all, just a field.
Your rules allow this query instead:
firebase.firestore()
.collection("users")
.doc(uid)
If you actually do want to allow the user to access any document where their UID matches the uid field in the document, you will need to adjust them like this:
match /users/{userId} {
function isAuthenticated() {
return request.auth != null;
}
function checkDocUid() {
return request.resource.data.uid == request.auth.uid;
}
allow read: if isAuthenticated() && checkDocUid();
}
Note that request.auth.uid is the currenetly auth'd user's uid and request.resource.data.uid is the value of the uid field in the document.
Always remember that your query must match the rules exactly, and that security rules are not filters.
Firestore security rules do not work.
Help me.
Document data of users/userid could not be read.
----------Security Rule------------
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId=**} {
// Missing or insufficient permissions.
allow read, write: if request.auth.uid == userId
// this is work.
//allow read, write: if request.auth != null
}
}
}
--------------main.js--------------------
import Vue from 'vue'
import Quasar from 'quasar'
import firebase from 'firebase'
import 'firebase/firestore'
Vue.config.productionTip = false
Vue.use(Quasar)
let app;
firebase.initializeApp({
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
})
firebase.auth().onAuthStateChanged(user=> {
if (user) {
let ref = firebase.firestore().collection('users').doc(user.uid)
ref.get().then(snapshot=>{
// Error !! : Missing or insufficient permissions.
}
}
if(!app){
Quasar.start(() => {
app = new Vue({
el: '#q-app',
render: h => h(require('./App').default)
})
})
}
})
firebase ^4.8.0
vue ^2.5.0
Apparently, require.auth.uid does not seem to work properly.
Where is there a mistake in me?
I was able to solve it self
match /users/{user} {
allow read, write: if request.auth.uid == user
match / {docs = **} {
allow read, write: if request.auth.uid == user
}
}
I followed the example I found here (under the User tab) and it's working great:
// Grants a user access to a node matching their user ID
service firebase.storage {
match /databases/{database}/documents {
match /users/{userId}/{documents=**} {
allow read, write: if isOwner(userId);
}
}
function isOwner(userId) {
return request.auth.uid == userId;
}
}
match /users/{userId}/{documents=**} {
// return request.auth.uid == userId
function isAuth(){
return request.auth != null
}
allow read,write:if (isAuth() && request.auth.uid == userId)
}
this solution work for this error.