I'm using NextAuth and Firebase to retrieve a user's data but I'm encountering the following error when I try to run this function:
Uncaught (in promise) FirebaseError: Missing or insufficient permissions.
async function getBalance(uid) {
const userRef = doc(db, "users", uid);
const userDoc = await getDoc(userRef);
if (userDoc.exists()) {
const { tokens } = userDoc.data();
return tokens;
} else {
return null;
}
}
How do I set the rules in Firebase to fix this error? Here are my configuration files:
import { getApps } from "firebase-admin/app";
import admin from "firebase-admin";
const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT_KEY);
if (!getApps().length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
const adminDb = admin.firestore();
const adminAuth = admin.auth();
export { adminDb, adminAuth };
import { getFirestore } from "firebase/firestore";
import { getApps, initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: process.env.FIREBASE_APIKEY,
authDomain: process.env.FIREBASE_AUTHDOMAIN,
databaseURL: process.env.FIREBASE_DATABASEURL,
projectId: process.env.FIREBASE_PROJECTID,
storageBucket: process.env.FIREBASE_STORAGEBUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGINGSENDERID,
appId: process.env.FIREBASE_APPID,
measurementId: process.env.FIREBASE_MEASUREMENTID,
};
const app = getApps().length ? getApp() : initializeApp(firebaseConfig);
const db = getFirestore(app);
export { db };
This is how my database is structured:
/users/[email protected]/chats/UN3XookDLjiJvqsW7GPG/messages/2gKLNAKDGiNWy2TvcFWq
In this case, [email protected]
is the uid
.
This is my current Firebase rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
match /{document=**} {
allow read, write: if request.auth.uid == userId;
}
}
}
}
I was able to run the function with these testing rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.time < timestamp.date(2023, 4, 19);
}
}
}
What do I need to change in my Firebase rules to allow access to user data?
The request.auth
in your Firestore security rules is populated by Firebase automatically, but only when a user signs in with Firebase Authentication.
Since you're not signing in to Firebase Authentication, the request.auth
won't be populated and your rules check will reject all access.
To solve this, you'll want to take the information of the user signed into Next Auth and use that to also sign in to Firebase. This flow is described in the documentation on custom sign-in and minting custom tokens, so I recommend following those to address the problem.