Lynn Smith
Lynn Smith

Reputation: 1

Firebase angularfire2 - How to return data from the current user only?

I'm trying to figure out how to limit a collection to returning just the user's data, not everyone's data.

In the example I'm working from the FirebaseService only shows CRUD examples where the data that's returned is everything.

import { Injectable } from "@angular/core";
import { Platform } from 'ionic-angular';
import 'rxjs/add/operator/toPromise';
import { AngularFirestore } from 'angularfire2/firestore';
import * as firebase from 'firebase/app';
import 'firebase/storage';

@Injectable()
export class FirebaseService {

  constructor(
    public afs: AngularFirestore,
    public platform: Platform
  ){}

  getEvents(){
      return new Promise<any>((resolve, reject) => {
        this.afs.collection('/events').snapshotChanges() // add +auth.uid ... or something?
        .subscribe(snapshots => {
          resolve(snapshots)
        })
      })
    }

...

In order to only get the user's events back, I think I need to add:

import { AngularFireAuth } from 'angularfire2/auth';

... and, do something from there. But, I'm at a loss. Any help would be greatly appreciated. Thanks in advance!

Upvotes: 0

Views: 346

Answers (1)

rijin
rijin

Reputation: 1759

You can limit this by adding rules. For example, you are using /users/ node to store user information. You can restrict only for the logged in user matching with userId can access /users/

match /databases/{database}/documents {

    function isSignedIn() {
      return request.auth != null;
    }

    function isOwner(userId) {
      return request.auth.uid == userId
    }

    match /users/{userId} {
      allow get: if isSignedIn()
        && isOwner(userId);
     ....
    }

}

To get User Id

constructor(
    private afAuth: AngularFireAuth  )

// then
ngOnInit() {

this.afAuth.authState;
    this.afAuth.authState.subscribe(
      user => {
        this.userInfo = user; <-- You can store user Id information to user variable
      },
      err => {
        console.log(err);
      }
}

you can use this.userInfo.uid to make further calls.

Upvotes: 1

Related Questions