@angular/router#CanActivateChild TypeScript Examples

The following examples show how to use @angular/router#CanActivateChild. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ios-view-restriction.guard.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
@Injectable({
  providedIn: 'root'
})
export class IosViewRestrictionGuard implements CanActivate, CanActivateChild {
  constructor(
    private platform: Platform,
    private router: Router,
  ) { }

  guardLogic(): boolean {
    // We disabled this for now
    // if (!this.platform.is('ios')) {
      return true;
    // }

    // this.router.navigate(['/ios-block-message']);
    // return false;
  }

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

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


}
Example #2
Source File: is-there-wallets.guard.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
@Injectable({
  providedIn: 'root'
})
export class IsThereWalletsGuard implements CanActivate, CanActivateChild {
  constructor(
    private readonly walletsQuery: WalletsQuery,
    private readonly router: Router,
  ) { }

  guardLogic(): Observable<boolean | UrlTree> {
    return this.walletsQuery.isThereWallet$
      .pipe(switchMap(status => {
        if (!!status) {
          return of(true);
        }

        return this.router.navigate(['/create-account'])
          .then(_ => false);
      }));
  }

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

  canActivateChild(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.guardLogic();
  }

}
Example #3
Source File: auth.guard.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const url: string = state.url;
    const isAdminRoute = route.data.isAdminRoute;
    return this.checkLogin(url, isAdminRoute);
  }

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

  checkLogin(url: string, isAdminRoute: boolean): boolean {
    if (AuthService.isLoggedIn) {
      if (isAdminRoute && !this.authService.isAdmin) {
        this.router.navigate(['/projects/user']);
        return false;
      }

      return true;
    }

    // Store the attempted URL for redirecting
    const tree = this.router.parseUrl(url);
    const primary: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
    this.authService.redirectUrl = primary.toString();
    this.authService.redirictParams = tree.queryParams;

    // Navigate to the login page with extras
    this.authService.logout();
    return false;
  }
}
Example #4
Source File: auth.guard.ts    From App with MIT License 6 votes vote down vote up
@Injectable({
	providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
	constructor(
		private restService: RestService
	) {}

	canActivate(): Observable<boolean> {
		return this.isAuth();
	}
	canActivateChild(): Observable<boolean> {
		return this.isAuth();
	}

	canLoad(): Observable<boolean> {
		return this.isAuth();
	}

	private isAuth(): Observable<boolean> {
		return this.restService.awaitAuth();
	}
}
Example #5
Source File: authorization.guard.ts    From alura_angular_rxjs_1 with MIT License 6 votes vote down vote up
@Injectable({
  providedIn: 'root',
})
export class AuthorizationGuard
  implements CanActivate, CanActivateChild, CanLoad {
  constructor(
    private authService: AuthorizationService,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): canActivateReturn {
    const url: string = state.url;
    return this.checkLogin(url);
  }

  checkLogin(url: string): canActivateReturn {
    if (this.authService.isUserAuthenticated()) {
      return true;
    }
    this.authService.redirectUrl = url;
    this.router.navigate(['/login']);
    return false;
  }

  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): canActivateReturn {
    return this.canActivate(route, state);
  }

  canLoad(route: Route): canActivateReturn {
    const url = `/${route.path}`;
    return this.checkLogin(url);
  }
}
Example #6
Source File: auth.guard.ts    From auth0-angular with MIT License 6 votes vote down vote up
@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanLoad, CanActivateChild {
  constructor(private auth: AuthService) {}

  canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> {
    return this.auth.isAuthenticated$.pipe(take(1));
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    return this.redirectIfUnauthenticated(state);
  }

  canActivateChild(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    return this.redirectIfUnauthenticated(state);
  }

  private redirectIfUnauthenticated(
    state: RouterStateSnapshot
  ): Observable<boolean> {
    return this.auth.isAuthenticated$.pipe(
      tap((loggedIn) => {
        if (!loggedIn) {
          this.auth.loginWithRedirect({
            appState: { target: state.url },
          });
        }
      })
    );
  }
}
Example #7
Source File: judgLogin.guard.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
// 路由守卫,没有TokenKey则跳转登录页
@Injectable({
  providedIn: 'root'
})
export class JudgLoginGuard implements CanActivateChild {
  constructor(private windowSrc: WindowService, private router: Router) {
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    const isLogin = !!this.windowSrc.getSessionStorage(TokenKey);
    if (isLogin) {
      return true;
    }
    return this.router.parseUrl('/login');
    }
}
Example #8
Source File: auth.guard.ts    From mns with MIT License 6 votes vote down vote up
@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
  constructor(private authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const url: string = state.url;

    return this.checkLogin(url);
  }

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

  canLoad(route: Route): boolean {
    // Store the entry url i.e. /admin-- > @Idrice am i not right?
    const url = `/${route.path}`;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    }

    this.authService.redirectUrl = url;
    this.router.navigate(['/login'], { queryParams: { returnUrl: url } });
    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;
    return false;


  }
}
Example #9
Source File: auth.guard.ts    From dayz-server-manager with MIT License 6 votes vote down vote up
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

    public constructor(
        private auth: AuthService,
        private router: Router,
    ) {}

    public canActivate(): boolean {

        if (!this.auth.getAuth()) {
            void this.router.navigate(['/login']);
            return false;
        }

        return true;
    }

    public canActivateChild(): boolean {
        return this.canActivate();
    }

}
Example #10
Source File: auth.guard.ts    From dayz-server-manager with MIT License 6 votes vote down vote up
@Injectable()
export class LoginGuard implements CanActivate, CanActivateChild {

    public constructor(
        private auth: AuthService,
        private router: Router,
    ) {}

    public canActivate(): boolean {

        if (!!this.auth.getAuth()) {
            void this.router.navigate(['dashboard']);
            return false;
        }

        return true;
    }

    public canActivateChild(): boolean {
        return this.canActivate();
    }

}
Example #11
Source File: change.password.service.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
@Injectable()
export class ChangePasswordGuard implements CanActivateChild {
  constructor(private store: Store<fromRoot.State>, private router: Router) {}

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.isPasswordChangeNeeded().pipe(
      switchMap(passwordChangeNeeded => {
        if (passwordChangeNeeded) {
          this.router.navigate(['/changePassword'], { queryParams: { forced: true } });
          return observableOf(false);
        }

        return observableOf(true);
      }),
    );
  }

  private isPasswordChangeNeeded(): Observable<boolean> {
    return this.store.select(fromRoot.getAuthenticationState).pipe(
      map(state => (state.authentication.passwordExpiration ? new Date(state.authentication.passwordExpiration) : undefined)),
      map(expiryDate => (expiryDate ? expiryDate.getTime() < new Date().getTime() : false)),
    );
  }
}
Example #12
Source File: authentication.guard.ts    From nodejs-angular-typescript-boilerplate with Apache License 2.0 6 votes vote down vote up
@Injectable({
  providedIn: 'root',
})
export class AuthenticationGuard implements CanActivate, CanActivateChild {
  constructor(
    private router: Router,
    private authenticationService: AuthenticationService,
  ) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    if (this.authenticationService.isAuthenticated) {
      return of(true);
    }

    this.router.navigate(['/auth/login']).then();
    return of(true);
  }

  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | UrlTree {
    return true;
  }
}
Example #13
Source File: judgAuth.guard.ts    From ng-ant-admin with MIT License 5 votes vote down vote up
// 用于切换路由时判断该用户是否有权限进入该业务页面,如果没有权限则跳转到登录页
@Injectable({
  providedIn: 'root'
})
export class JudgAuthGuard implements CanActivateChild {
  authCodeArray: string[] = [];
  selMenu!: Menu | null;
  menuNavList: Menu[] = [];

  constructor(private windowSrc: WindowService,
              private loginOutService: LoginInOutService,
              private router: Router, private userInfoService: UserInfoService,
              private menuStoreService: MenuStoreService, private message: NzMessageService) {
    this.menuStoreService.getMenuArrayStore().subscribe(res => {
      this.menuNavList = res;
    });
  }

  getMenu(menu: Menu[], url: string): void {
    for (let i = 0; i < menu.length; i++) {
      if (url === menu[i].path) {
        this.selMenu = menu[i];
        return;
      } else {
        if (menu[i].children && menu[i].children!.length > 0) {
          this.getMenu(menu[i].children!, url);
        }
      }
    }
  }

  getResult(code: string, authCodeArray: string[]): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (authCodeArray.includes(code)) {
      return true;
    } else {
      this.message.error('您没有权限登录该模块');
      this.loginOutService.loginOut();
      return this.router.parseUrl('/login');
    }
  }

  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    this.userInfoService.getUserInfo().subscribe(res => this.authCodeArray = res.authCode);
    // 如果有authCode,则表示是页面上点击按钮跳转到新的路由,而不是菜单中的路由
    while (route.firstChild) {
      route = route.firstChild;
    }
    if (!!route.data['authCode']) {
      return this.getResult(route.data['authCode'], this.authCodeArray);
    }

    // 如果是菜单上的按钮,则走下面
    this.getMenu(this.menuNavList, state.url);
    // 没找到菜单,直接回登录页
    if (!this.selMenu) {
      return this.getResult(fnGetUUID(), this.authCodeArray);
    }
    const selMenuCode = this.selMenu.code;
    this.selMenu = null;
    // 找到了菜单,但是菜单的权限码用户不拥有,则跳转到登录页
    return this.getResult(selMenuCode!, this.authCodeArray);
  }
}
Example #14
Source File: permission.guard.ts    From digital-bank-ui with Mozilla Public License 2.0 5 votes vote down vote up
@Injectable()
export class PermissionGuard implements CanActivateChild {
  constructor(private store: Store<fromRoot.State>, private router: Router) {}

  waitForPermissions(): Observable<boolean> {
    return this.store.select(fromRoot.getPermissionsLoading).pipe(
      filter(loading => !loading),
      take(1),
    );
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    const routeData: any = route.data;

    const routePermission: FimsPermission = routeData.hasPermission;

    // No permission set on route at all
    if (!routePermission) {
      return observableOf(true);
    }

    return this.waitForPermissions().pipe(
      switchMap(() =>
        this.hasPermission(routePermission).pipe(
          map(hasPermission => {
            if (hasPermission) {
              return true;
            }
            this.router.navigate(['/denied']);
            return false;
          }),
        ),
      ),
    );
  }

  private hasPermission(routePermission: FimsPermission): Observable<boolean> {
    return this.store.select(fromRoot.getPermissions).pipe(
      map(permissions =>
        permissions.filter(permission => permission.id === routePermission.id && permission.accessLevel === routePermission.accessLevel),
      ),
      map(matches => matches.length > 0),
      take(1),
    );
  }
}