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?
Szymon KRSN is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.