79351400

Date: 2025-01-13 07:13:16
Score: 1
Natty:
Report link

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:

  1. Make sure you've initialized Firebase with auth:
// 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
  ]
})
  1. You need to ensure you're authenticated before making Firestore requests. Your current code looks good for that part since you're using currentUser$.

  2. 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:

  1. Handle user authentication flows
  2. Manage user state
  3. Control access patterns
  4. Handle error cases

Would you like me to explain more about how Firebase security rules work or show you how to test them locally?

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (0.5):
Posted by: Hedieh Rafiee