sign-in-guard-activate.service.ts 1.24 KB
Newer Older
kunw's avatar
kunw committed
1 2 3 4 5 6 7 8
import { Injectable } from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild
} from '@angular/router';
import { SessionService } from '../../shared/session.service';
9
import { CommonRoutes } from '../../shared/shared.const';
kunw's avatar
kunw committed
10 11 12 13 14 15 16 17 18

@Injectable()
export class SignInGuard implements CanActivate, CanActivateChild {
  constructor(private authService: SessionService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> | boolean {
    //If user has logged in, should not login again
    return new Promise((resolve, reject) => {
      let user = this.authService.getCurrentUser();
Steven Zou's avatar
Steven Zou committed
19
      if (user === null) {
kunw's avatar
kunw committed
20 21
        this.authService.retrieveUser()
          .then(() => {
22
            this.router.navigate([CommonRoutes.HARBOR_DEFAULT]);
kunw's avatar
kunw committed
23 24 25 26 27 28
            return resolve(false);
          })
          .catch(error => {
            return resolve(true);
          });
      } else {
29
        this.router.navigate([CommonRoutes.HARBOR_DEFAULT]);
kunw's avatar
kunw committed
30 31 32 33 34 35 36 37 38
        return resolve(false);
      }
    });
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> | boolean {
    return this.canActivate(route, state);
  }
}