0

Im setting up Access Control for an angular app and have modeled my User object like this: -User --firstName --phoneNumber --posts[] <--- String array of post id's

getPosts(): Observable<any[]> {
    return this.postsCollection.snapshotChanges().pipe(
      map((actions) => {
        return actions.map((a) => {
          const data = a.payload.doc.data();
          const data2 = { id: a.payload.doc.id, ...data};
          this.hasPostAccess(data2);
          return { id: a.payload.doc.id, ...data};
        });
      })
    );
  }

  private hasPostAccess(data: any) {
    const inspect = obj => {
      for (const prop in obj) {
        if (obj.hasOwnProperty(prop)) {
          // console.log(`${prop}: ${obj[prop]}`);
          if (prop === 'id') {
            console.log(obj[prop]);
            const PostId = obj[prop];
            const currentUser = JSON.stringify(localStorage.getItem('user'));
            if (currentUser.search(PostId) === -1) {
              console.log('Denied: ' + PostId);
            } else {
              console.log('Allowed: ' + PostId);
            }
            console.log('Current USER: ' + JSON.stringify(currentUser));
            // if (currentUser(PostId) > -1) {
            //   console.log('Allowed: ' + PostId);
            // } else {
            //   console.log('Denied: ' + PostId);
            // }
          }
        }
      }
    };
    inspect(data);
  }

I want to show all posts that belong to the user. So when I subscribe to the getPosts Observable, this must filter the posts and return only the posts id's that are stored in the User's post array.

4
  • Where is the problem? Are you expecting us to do your work for you? How to ask Commented May 21, 2019 at 12:52
  • No Mike, just wanted to know how this can be done with an Observable without using the prop inspection. I am new to rxjs. :) Commented May 21, 2019 at 13:16
  • 1
    rxjs-dev.firebaseapp.com/api/operators/filter Commented May 21, 2019 at 13:30
  • Thanks @penleychan Commented May 21, 2019 at 14:34

1 Answer 1

0
getPosts(): Observable<any[]> {
    const currentUser: User = JSON.parse(localStorage.getItem('user'));
    const userPosts  = currentUser.posts;
    return this.postsCollection.snapshotChanges().pipe(
      map((actions) => {
        return actions.map((a) => {
          const data = { id: a.payload.doc.id, ...data};
          const filteredPosts = _.filter(data, (p) => 
          _.includes(currentUser, p.postId));
          return filteredPosts;
        });
      })
    );
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.