Role-Based User Access Control With Firebase

Viewed 2980

I try to create Role-Based User Access Control With Firebase to allow access to a route if the user is authenticated && admin... and I´m trying it with this tutorial: https://angularfirebase.com/lessons/role-based-permissions-and-authorization-with-firebase-auth/ but i use angular 7 , I get a syntax error on " Observable.of(null) " and ".subscribe(user => { this.user.next(user)"

my My AuthService :

import { Injectable } from '@angular/core';
import { User } from 'src/app/register/user';
import { AngularFireAuth } from '@angular/fire/auth';
import { map } from "rxjs/operators";
import { auth } from 'firebase';
import { Router } from "@angular/router";
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
//import * as firebase from 'firebase/app';
import { AngularFireDatabase } from '@angular/fire/database';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
import { observable } from 'rxjs/internal/symbol/observable';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  user: BehaviorSubject<User> = new BehaviorSubject(null)

  constructor(public db: AngularFireDatabase, private fire: AngularFireAuth) {

    this.fire.authState.pipe(switchMap(auth => {
      if (auth) {
        /// signed in
        return this.db.object('users/${auth.uid}')
      } else {
        /// not signed in
        return Observable.of(null)
      }
    }).subscribe(user => {
      this.user.next(user)
    }))


  }

My User Model:

export interface Roles {
    reqUser: boolean;
    volunteer?: boolean;
    admin?:  boolean;
  }

  export class User {
    uid: string;
    email:    string;
    username: string;
    password : string;
    roles:    Roles;
    fullname : string;

    constructor(auth) {
      this.email    = auth.email
      this.uid = auth.uid
      this.roles    = { reqUser: true }
    }
  }
1 Answers

try this return of(null) instead of return Observable.of(null), it will solve the error of syntax error on Observable.of(null) which you are currently getting

and for your second error in subscribe function just simply try this code

subscribe(user => this.user = user)

instead of

subscribe(user => {
  this.user.next(user)
}

hope this will solve your error and if not reply me with your errors and code

Related