Home > Net >  A user doesn't have any persmission when its account has just been created in Firebase (web ver
A user doesn't have any persmission when its account has just been created in Firebase (web ver

Time:12-05

I'm trying to use Firebase in the web project (with NextJS), but here is my problem: the user doesn't have an account, so naturally the account is created with createUserWithEmailAndPassword(). However, I want to store data in Firestore right after the creation of the account... and there is the problem. Indeed Firebase throws the following error:

FirebaseError: [code=permission-denied]: Missing or insufficient permissions.

Here is an extract of my code:

import { useState } from "react";
import {
  createUserWithEmailAndPassword,
  getAuth,
} from "firebase/auth";
import {
  collection,
  getFirestore,
  addDoc,
} from "firebase/firestore";

export const ConnectionPage = () => {
  // the values of the inputs in the HTML content
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  // the function executed when the user clicks the register button
  const submit = async (e) => {
    e.preventDefault();
    // create a new user with email and password
    // and add the document in the "users" collection
    try {
      const userCredentials = await createUserWithEmailAndPassword(
        getAuth(),
        email,
        password
      );
      const user = userCredentials.user;
      const userInfo = {
        uid: user.uid,
        // ...and all kind of data
      };
      // my problem starts here
      // the following line will throw an error
      // "[code=permission-denied]: Missing or insufficient permissions."
      // whereas, according to the rules in Firestore, it should work
      // because I just ask the user to be authenticated (`allow read: if request.auth != null`)
      // and according to the documentation, `createUserWithEmailAndPassword` logs in the user.
      const collectionRef = collection(getFirestore(), "users");
      // I have never reached the following lines
      const docRef = await addDoc(collectionRef, userInfo);
      console.log(`New document with id '${docRef.id}' created successfully.`);
    } catch (e) {
      console.error("An error has occured during register, look:");
      console.error(e.toString());
    }
  };

  // returns a form
  // with an email input
  // and a password input
  // and a button to register
};

Here are my rules in Firestore:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read;
      allow write: if request.auth != null;
    }
  }
}

Please help me, the only solution I can find on a similar problem is to sign out the user after the creation of the account, and sign in right after that.

CodePudding user response:

When you just have:

allow read;

This is an entire statement, and means that nobody can read the data.

If you want to apply the same condition for both read and write, use:

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

CodePudding user response:

Try using an auth state observer instead of just await on the creation of the account. In my experience, the current user object is not immediately set after account creation, and you have to wait until the auth state observer triggers with a non-null user object in order to be able to perform authenticated queries. Without a non-null currentUser, Firestore queries that require auth will fail.

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

If this feels like a bug to you, then I suggest filing it on GitHub.

  • Related