Janis Jansen
Janis Jansen

Reputation: 1025

Firebase cloud firestore + auth: write only for signed in users

I am building a vuejs application and I am trying to add firebase auth to the app. I used cloud firestore for a news system.

Now on the "add news" page I call

firebase.auth().signInWithEmailAndPassword("[email protected]", "mypassword").catch(function (error) {
  console.log(error.code);
  console.log(error.message);

  if (errorCode === 'auth/wrong-password') {
    alert('Wrong password.');
  } else {
    alert(errorMessage);
  }
});

to log the user in, or give him feedback if something went wrong.

Later I am writing data to cloud firestore like this

irestore.collection("news").doc().set({
  date: today,
  title: "Hello",
  text: "A think I am a news!"
});

In the firestore rules I set

allow read, write: if request.auth != null;

to the news collection - so it should only grant write access to logged in users, right?

Now the thing: If i log in with a wrong password, firebase gives back, that the password was incorrect (so we are not logged in are we?) but the data is written to firestore anyways. What did I do wrong?

enter image description here

Upvotes: 1

Views: 1874

Answers (1)

Sam Stern
Sam Stern

Reputation: 25134

Your rule request.auth != null will check if the user is signed in via any method. You can check on the client side for sign in two ways:

Sync:

// Synchronously check for current user
var user = firebase.auth().currentUser;

if (user) {
  // User is signed in.
} else {
  // No user is signed in.
}

Async:

// Listen for current user status
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

If you get a user then you can expect request.auth to not be null.

Upvotes: 4

Related Questions