Angular AuthGuard - verify authentication and database input sequentially

To allow access to the admin route, I have to check two things:

  • If the user is authenticated
  • If this user is an administrator. I get admin status from firebase database.

Adminminard

import {ActivatedRouteSnapshot, CanActivate, Router, 
RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {AngularFireAuth} from 'angularfire2/auth';
import {Injectable} from '@angular/core';
import {DbActionsService} from '../services/db-actions.service';
import {AuthService} from '../services/auth.service';
import 'rxjs/add/operator/map';

@Injectable()
export class AdminGuard implements CanActivate {

  constructor(private afAuth: AngularFireAuth, private router: Router, private dbAction: DbActionsService, private authService : AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    if (this.afAuth.auth.currentUser) {
      return this.dbAction.getUserProfileData(this.afAuth.auth.currentUser.email).map((user) => {
        if (user[0].admin) {
          return true;
        } else {
          this.router.navigate(['/']);
          return false;
        }
      }).take(1)
    } else {
      this.router.navigate(['/']);
    }
  }
}

Service function

getUserProfileData(userEmail: string) {
    this.dataRef = this.afDatabase.list('data/users', ref => ref.orderByChild('profile/email').equalTo(userEmail));
    this.data = this.dataRef.snapshotChanges().map(changes => {
      return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
    });
    return this.data;
  }

This works great, however, my main problem is when I refresh (or load initially) the page where AdminGuard always redirects me to the home page, since AdminGuard does not wait for an authentication response.

What i tried

New AuthService

import { Injectable } from '@angular/core';
import {AngularFireAuth} from 'angularfire2/auth';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class AuthService {
  private user: any;

  constructor(private afAuth: AngularFireAuth) { }

  setUser(user) {
    this.user = user;
  }
  getAuthenticated(): Observable<any> {
    return this.afAuth.authState;
  }

}

New AdminGuard

import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {AngularFireAuth} from 'angularfire2/auth';
import {Injectable} from '@angular/core';
import {DbActionsService} from '../services/db-actions.service';
import {AuthService} from '../services/auth.service';
import 'rxjs/add/operator/map';

@Injectable()
export class AdminGuard implements CanActivate {

  constructor(private afAuth: AngularFireAuth, private router: Router, private dbAction: DbActionsService, private authService : AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

    return this.authService.getAuthenticated().map(user => {
      this.authService.setUser(user);
      return user ? true : false;
    });

  }
}

This works with Auth Check on boot, but how do I also use the database to check if the user is an administrator? I have no idea...

+4
1

, , :

  • authState .
  • switchMap, , .
  • admin boolean .
  • tap .
import { tap, map, switchMap, take } from 'rxjs/operators;

// ...omitted

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

  return this.afAuth.authState.pipe(
    take(1),
    switchMap(user => {
      return this.dbAction.getUserProfileData(user.email)
    })
    map(profile => !!(profile.length && profile[0].admin),
    tap(isAdmin => {
      if (isAdmin) {
        console.log('admin user, you shall pass')
      } else {
        console.log('non-admin user, go home')
        this.router.navigate(['/']);
      }
    })
  )

}

Angular/Firebase , - , auth screencast

+3

Source: https://habr.com/ru/post/1692993/


All Articles