javascriptangulartypescriptionic-frameworkauth-guard

Check multiple condition before login in Using auth guard


I am trying to check multiple condition to let user login. I was able implement authguard when user is logged In successfully. Not only user need validate but also need to meet the criteria to login. Here is How I have implemented auth guard to check if user is Sign In or not.

export class AuthGuard implements CanActivate {
  access: boolean;
  constructor(
    private auth: AuthService,
    private router: Router,
  ) {}
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    return this.auth.user$.pipe(
      take(1),
      map((user) => (user ? true : false)),
      tap((isLoggedIn) => {
        if (!isLoggedIn) {
          this.router.navigate(['/login']);
          return false;
        }
        return true;
      })
    );
  }
}

While registration user has a field called employee which is boolean. So I want to implement auth guard to login so that when user login it should meet the condition that the user credentials are valid and the user is employee I tried Following by using following way but empolyee was undefined

this.auth.user$.subscribe((res) => {
  this.isEmployee = res.isEmployee;
});
if (!this.isEmployee) {
  console.log(this.isEmployee);
  this.router.navigate(['/login']);
  console.log('user is not employee');
  return false;
}
console.log('user is approved', this.isEmployee);
return true;
}

Solution

  • Assuming you have keys isLoggedIn, isEmployee you can do following:

    return this.auth.user$.pipe(
      map((user) => {
        if(user.isLoggedIn && user.isEmployee){
          return this.router.navigate(['login']);
        } else {
          return false;
        }
      })
    );
    

    There is no point of using operator take(1) in a guard, user can attempt any number of times to get inside a page.