7 PERMISSION_DENIED: Missing or insufficient permissions

I’m encountering the 7 PERMISSION_DENIED: Missing or insufficient permissions error when trying to access Firestore in my Firebase Cloud Function. Here is the relevant part of my code:

admin.js:

const admin = require("firebase-admin")
const serviceAccount = require("./serviceAccountKey.json")

// admin.initializeApp({
//   credential: admin.credential.cert(serviceAccount),
// })
admin.initializeApp(serviceAccount)

module.exports = admin

firebase.js:

const functions = require("firebase-functions")
const admin = require("./admin")
const { initializeApp } = require("firebase/app")
const {
  getAuth,
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  sendPasswordResetEmail,
} = require("firebase/auth")
const { getFirestore, doc, setDoc, getDoc } = require("firebase/firestore")

const firebaseConfig = {
  apiKey: functions.config().customfirebase.api_key,
  authDomain: functions.config().customfirebase.auth_domain,
  projectId: functions.config().customfirebase.project_id,
  storageBucket: functions.config().customfirebase.storage_bucket,
  messagingSenderId: functions.config().customfirebase.messaging_sender_id,
  appId: functions.config().customfirebase.app_id,
  measurementId: functions.config().customfirebase.measurement_id,
}

const firebaseApp = initializeApp(firebaseConfig)
const auth = getAuth(firebaseApp)
const db = getFirestore(firebaseApp)

const handleGoogleSignIn = async (req, res) => {
  const { idToken } = req.body

  try {
    const decodedToken = await admin.auth().verifyIdToken(idToken)
    const uid = decodedToken.uid
    const email = decodedToken.email

    const userDocRef = doc(db, "users", uid)
    const docSnapshot = await getDoc(userDocRef)

    if (!docSnapshot.exists()) {
      await setDoc(userDocRef, {
        email: email,
        createdAt: new Date(),
        userData: {},
      })
    }

    const updatedDocSnapshot = await getDoc(userDocRef)

    if (!updatedDocSnapshot.exists()) {
      throw new Error("User document not found")
    }

    const customToken = await admin.auth().createCustomToken(uid)

    const userData = {
      uid: uid,
      email: email,
      ...updatedDocSnapshot.data(),
    }

    res.status(200).json({
      message: "Google sign-in successful",
      user: userData,
      idToken: customToken,
      success: true,
    })
  } catch (error) {
    console.error("Google sign-in error:", error.message)
    res.status(500).send({ error: "Google sign-in failed. Please try again." })
  }
}

IAM page, permissions for my Cloud Functions account:
Cloud Datastore Owner
Cloud Datastore User
Cloud Functions Invoker
Cloud Storage for Firebase Admin
Editor
Firebase Admin
Firebase Rules Firestore Service Agent
Firestore Service Agent
Service Account Token Creator
Service Account User
Storage Admin

Cloud Functions page, permissions for my Cloud Functions account:
Cloud Functions Invoker
Editor
Firebase Admin
(Here I can’t make any changes because of ‘Role cannot be edited as it is inherited from another resource’. How can I add more roles here?)

Firebase Console -> Firestore Database -> Rules:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    
    // Allow read access to all users for the products collection
    match /products/{productId} {
      allow read: if true; // Publicly readable
      allow write: if request.auth != null && request.auth.token.admin == true; // Only admins can write
    }

    // Allow read/write access to authenticated users for their own orders
    match /orders/{orderId} {
      allow read, write: if request.auth != null && request.auth.uid == resource.data.userId;
    }

    // Allow authenticated users to read/write their own user profile
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
    
    // Allow admins to read/write all documents
    match /{document=**} {
      allow read, write: if request.auth != null && request.auth.token.admin == true;
    }
  }
}

Firebase Console -> Project settings -> Service accounts -> Database secrets:
Here I have this information: ‘Database secrets are currently deprecated and use a legacy Firebase token generator. Update your source code with the Firebase Admin SDK.’
Is that the problem linked to my permissions?

New contributor

Szymon KRSN is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật