Search code examples
securitygoogle-cloud-firestoretokenfirebase-security

Is it possible to pass data to Firestore within a read-operation to check if the read-op. is allowed based on that data in 'security rules'?


I would like to check a givenAnswer of a user against the correctAnswer stored in Firestore securely. First I thought I could just check if a document with the givenAnswer of the user exists but it was pretty easy to get all the document id's and its fields by iterating on a collection like so:

db.doc(`quizzes/quiz1`).collection('question1').get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
          console.log('doc.id: ' , doc.id)
          console.log('doc.data: ' , doc.data())
    })
})

I could imagine to achieve what I need by first writing the givenAnswer to Firestore in a specific userDocument and check afterwards on the read-operation in the security-rules if this value is the same as the correctAnswer but it would cost an additional write-operation...

So I thought there must be a way to pass the givenAnswer within a read-operation and check in security-rules if givenAnswer and correctAnswer matching.

Read about creating a custom token for the user but Im not sure if this is the way to go (I have no idea how these tokens work...) because it would be necessary to change the value of the custom token on every new try to compare the givenAnswer.

Hope somebody has a solution for what I'm trying to do

Thx a lot!


Solution

  • I don't think that there is something like that in read operations for the firestore rules. Using a writing operation you could just use the data you write to check.

    I could imagine two solutions you could use. Both inclute firebase cloud functions:

    1 - when and if your users write the answers to firestore just use a cloud function to check it against the right ones and mark them as right or false. That way no user needs access to the answers.

    2 - use callable cloud functions to call them if you want to check if an asnwer is correct or not. You just send the answer and it gives you back if it is correct or not.

    The client user can't change his custom claims. They are stored in the auth token. You would still ned to invole cloud functions to set or update them.