Search code examples
node.jsfirebase-authenticationgoogle-cloud-functionsfirebase-admin

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." })
  }
}

{/* Rest of the code */}

index.js

const functions = require("firebase-functions")
const express = require("express")
const cors = require("cors")
const helmet = require("helmet")
require("dotenv").config()

const {
  handleGoogleSignIn,
  handleFormSubmit,
  handleGetUserData,
  handleUpdateProfile,
  handleUpdateProfilePicture,
  handleUpdatePassword,
  handleForgotPassword,
} = require("./firebase")

const app = express()

const allowedOrigins = [
// Here are my all allowed origins urls
]

app.use(
  cors({
    origin: function (origin, callback) {
      if (!origin) return callback(null, true)
      if (allowedOrigins.indexOf(origin) === -1) {
        const msg =
          "The CORS policy for this site does not allow access from the specified Origin."
        return callback(new Error(msg), false)
      }
      return callback(null, true)
    },
  })
)

app.use(helmet())
app.use(
  helmet.crossOriginOpenerPolicy({
    policy: "same-origin-allow-popups",
  })
)

app.use(express.json())

app.post("/googleSignIn", handleGoogleSignIn)
app.post("/formSubmit", handleFormSubmit)
app.get("/getUserData", handleGetUserData)
app.post("/updateProfile", handleUpdateProfile)
app.post("/updateProfilePicture", handleUpdateProfilePicture)
app.post("/updatePassword", handleUpdatePassword)
app.post("/forgotPassword", handleForgotPassword)

exports.api = functions.region("europe-west1").https.onRequest(app)
exports.scheduledFunction = scheduledFunction

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?


Solution

  • You're getting the following error:

    PERMISSION_DENIED: Missing or insufficient permissions

    Because the rules reject the operations that you're performing. This is happening because you're using the Firebase web client SDK inside Cloud Functions. The client SDK for the web should only be used inside web clients and not inside Cloud Functions.

    If you want to write an HTTP-type Cloud Function, then you should only use the Firebase Admin SDK as explained in the official documentation: