Firebase is a common point of confusion! The issue isn't with your code specifically, but rather with how Firebase authentication and security rules work together.
First, you are already using the Firebase SDK correctly through @angular/fire
. The issue isn't about adding manual headers - Firebase handles authentication tokens automatically when you initialize it properly. Here's how to fix this:
// app.module.ts
import { provideFirebaseApp, initializeApp } from '@angular/fire/app';
import { provideAuth, getAuth } from '@angular/fire/auth';
import { provideFirestore, getFirestore } from '@angular/fire/firestore';
@NgModule({
imports: [
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideAuth(() => getAuth()),
provideFirestore(() => getFirestore()),
// ... other imports
]
})
You need to ensure you're authenticated before making Firestore requests. Your current code looks good for that part since you're using currentUser$
.
The most likely issue is your Firestore security rules. Check your rules in the Firebase Console (Database → Rules). They probably look something like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false; // This is the default, blocking all access
}
}
}
You need to update them to allow authenticated users to access their own timeshares. Here's a basic example:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /timeshares/{timeshare} {
allow read: if request.auth != null && resource.data.ownerId == request.auth.token.email;
}
}
}
This rule says: "Allow reading a timeshare document only if the user is authenticated AND the document's ownerId matches the authenticated user's email."
You haven't wasted your time at all! Understanding authentication and building your auth service is valuable knowledge. The Firebase SDK handles the token management automatically, but you still need to:
Would you like me to explain more about how Firebase security rules work or show you how to test them locally?