Firebase Firestore 不允许经过身份验证的用户

问题描述 投票:0回答:1

我正在为此苦苦挣扎 我有一个项目,我正在努力从经过身份验证的用户的数据库中获取数据。我感觉我失去了一些东西。

在 firebase.js 中我有

const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app);

// Initialize Authentication
const auth = getAuth(app);
setPersistence(auth, browserLocalPersistence)
  .then(() => {
    console.log("User Persistence is Local");

  })
  .catch((error) => {
    console.error('Error setting persistence:', error);
  });
  onAuthStateChanged(auth, (user) => {
    if (user) {
      // User is signed in
      console.log("User is signed in:", user);
    } else {
      // User is signed out
      console.log("User is signed out");
    }
  });

当我尝试加载某些内容时,我可以注册并登录 src/app/home/page.jsx

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { auth,firestore } from '../../../../firebase';
import { collection, getDocs } from 'firebase/firestore';
import Swal from 'sweetalert2';
import createNewProject from '../../api/makeNewProject'
const Page = () => {

  const fetchData = async () => {
    console.log("current user:",auth.currentUser)
    const dataRef = collection(firestore, 'data');
    console.log("data ref",dataRef)
  return (
<div/>)};

日志值

current user: null
dataref: null
current user: null
dataref: null
User is signed in: {userID}
User Persistence is Local

直观上,当我启动开发服务器或导入时,这应该初始化 firebase -> 设置持久性 -> 检查/设置用户身份验证 -> 尝试从 firestore 提取数据

调试规则是

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Allow any authenticated user to read and write to the projects collection
    match /data/{dataId} {
      allow read, write: if request.auth.uid != null;
    }

    // Allow any authenticated user to read and write to the users collection
    match /users/{userId} {
      allow read, write: if request.auth.uid != null;
    }
  }
}
reactjs firebase google-cloud-firestore next.js firebase-authentication
1个回答
0
投票

根据上面的评论,我创建了一个函数

  const waitForAuth = new Promise((resolve, reject) => {
    onAuthStateChanged(auth, (user) => {
      if (user) {
        console.log("User is signed in");
        resolve(user);
      } else {
        console.log("User is signed out");
        reject(new Error('User is not signed in'));
      }
    });
  });

然后在整个项目中都这样称呼

const fetchProjects = async () => {
    await waitForAuth;
    const dataRef = collection(firestore, 'data');
© www.soinside.com 2019 - 2024. All rights reserved.