@angular/router#ActivatedRouteSnapshot TypeScript Examples

The following examples show how to use @angular/router#ActivatedRouteSnapshot. 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: role.guard.ts    From Smersh with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot): boolean {
    if (
      new DecodedToken().get() &&
      new DecodedToken().getDecoded().roles.includes(route.data.role)
    ) {
      return true;
    }

    this.router.navigateByUrl(
      route.routeConfig.path === ''
        ? '/login'
        : DashboardRouter.redirectToList()
    );
    return false;
  }
Example #2
Source File: can-access-connect.guard.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return selectPersistStateInit()
      .pipe(switchMap(() => {
        return forkJoin([
          this.walletsQuery.selectAll().pipe(take(1)),
          this.walletsAccountsQuery.selectAll().pipe(take(1))
        ])
          .pipe(map(values => {
            const canAccess = values.every(value => value.length > 0);

            if (!canAccess) {
              this.router.navigate(['/connect/no-wallet'], {
                queryParams: route.queryParams,
              });
              return false;
            } else {
              return true;
            }
          }));
      }));
  }
Example #3
Source File: staking-round.resolver.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
resolve(route: ActivatedRouteSnapshot): boolean {
    if (route.routeConfig.path.includes('round-one')) {
      this.stakingService.setStakingContractAddress(ENVIRONMENT.staking.roundOneContractAddress);
      return true;
    }

    if (route.routeConfig.path.includes('round-two')) {
      this.stakingService.setStakingContractAddress(ENVIRONMENT.staking.roundTwoContractAddress);
      return true;
    }
  }
Example #4
Source File: auth-guard-service.guard.ts    From ng-devui-admin with MIT License 6 votes vote down vote up
canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (!this.authService.isUserLoggedIn()) {
      this.i18nValues = this.translate.instant('authNotice');
      this.toastService.open({
        value: [
          {
            severity: 'info',
            summary: this.i18nValues['summary'],
            content: this.i18nValues['content'],
          },
        ],
        life: 2000,
      });
      this.router.navigate(['login']);
      return false;
    } else {
      return true;
    }
  }
Example #5
Source File: auth.guard.ts    From FireAdmin with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    return new Promise(async (resolve, reject) => {
      const isSignedIn = await this.auth.isSignedIn();
      if (! isSignedIn) {
        // const rootPath = state.url.slice(0, state.url.indexOf(route.url[route.url.length - 1].path));
        // this.navigation.setRootPath(rootPath);
        this.navigation.redirectTo('login');
        resolve(false);
      } else {
        resolve(true);
      }
    });
  }
Example #6
Source File: feature-toggle.guard.ts    From canopy with Apache License 2.0 6 votes vote down vote up
isActive(route: Route | ActivatedRouteSnapshot) {
    return this.featureToggleService.toggles$.pipe(
      first(),
      map(configToggles => {
        const active = getDataPropertyValues(route, 'featureToggle')
          .map(t => {
            const value = configToggles[t];

            return value === undefined || value;
          })
          .reduce((acc, current) => acc && current, true);

        if (!active) {
          this.router.navigate([ '/' ], { queryParamsHandling: 'merge' });
        }

        return active;
      }),
    );
  }
Example #7
Source File: communityfolder.guard.ts    From msfs-community-downloader with GNU Affero General Public License v3.0 6 votes vote down vote up
canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

        const communityFolder = this.settingsService.getSettings().communityPath;
        if (!communityFolder || communityFolder === '') {
            this.router.navigateByUrl('/settings');
        }
        return true;
    }
Example #8
Source File: auth.guard.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      const loggedIn = !!this.auth.isLoggedIn();
      if (!loggedIn) {
        this.router.navigate(['/auth']);
        return false;
      }
    return true;
  }
Example #9
Source File: agent.guard.ts    From Developing-Multi-platform-Apps-with-Visual-Studio-Code with MIT License 6 votes vote down vote up
canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      debugger;
      let url = next.url[0].path;
      if (this.authorizationService.isUserLoggedIn()) {
  
        if (url == "agent" && this.authorizationService.user.role == "agent")
          return true;
        else
          this.router.navigate(['/login']);
      }
      else {
        this.router.navigate(['/login']);
      }
  }
Example #10
Source File: appIsSetup.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
canActivate(
    _route: ActivatedRouteSnapshot,
    _state: RouterStateSnapshot
  ) {
    if (getBoolean("app.setupComplete", false)) {
      return true;
    } else {
      this.router.navigate(["/initialSetup"]);

      return false;
    }
  }
Example #11
Source File: callback.guard.ts    From App with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot): boolean {
		const win = this.windowRef.getNativeWindow();

		setTimeout(() => {
			const href = new URLSearchParams(win?.location.search.replace('?', ''));
			let error: Error | null = null;
			if (href.has('error')) {
				const decoded = decodeURIComponent(href.get('error') as string);
				error = new Error(decoded);
			}

			(win
				?.opener as Window)
				?.postMessage({
					type: 'oauthCallback',
					data: {
						error,
						token: route.queryParamMap.get('token')
							?? this.cookieService.get('auth')
					}
				}, win?.location.origin ?? '');

			win?.close();
		}, 0);

		return true;
	}
Example #12
Source File: AemPageDataResolver.spec.ts    From aem-angular-editable-components with Apache License 2.0 6 votes vote down vote up
describe('AemPageDataResolver', () => {
  it('should return absolute resource path without extension (/conteent/abc)', () => {
    const route = ({ url: [ 'content', 'abc' ] } as any) as ActivatedRouteSnapshot;
    const aemPageDataResolver = new AemPageDataResolver();

    expect(aemPageDataResolver.resolve(route)).toBe('/content/abc');
  });

  it('should return absolute resource path without extension (/content/abc/def/ghi)', () => {
    const route = ({ url: [ 'content', 'abc', 'def', 'ghi.html' ] } as any) as ActivatedRouteSnapshot;
    const aemPageDataResolver = new AemPageDataResolver();

    expect(aemPageDataResolver.resolve(route)).toBe('/content/abc/def/ghi');
  });
});
Example #13
Source File: admin.guard.ts    From ReCapProject-Frontend with MIT License 6 votes vote down vote up
canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean | UrlTree> | boolean | UrlTree {
    let userMail: string | null = this.localStorageService.get<string>(
      'userMail'
    );
    return this.authService.isAuthenticated(userMail, ['admin']).pipe(
      map((response) => {
        return response.success;
      }),
      catchError(() => {
        this.router.navigate(['']);
        this.toastrService.info('You are not authorized to access this page.');
        return of(false);
      })
    );
  }
Example #14
Source File: admin.guard.ts    From ngx-admin-dotnet-starter with MIT License 6 votes vote down vote up
canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): Observable<boolean> | Promise<boolean> | boolean {
    return this.roleProvider.getRole()
      .pipe(map(role => {
        const roles = role instanceof Array ? role : [role];
        return roles.some(x => x && x.toLowerCase() === ROLES.ADMIN);
      }));
  }
Example #15
Source File: auth-guard.service.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let routeMessage: string = null;
    const isTokenExpired = this.authenticationService.isTokenExpired();

    if (!isTokenExpired) {
      const isLoggedIn = this.authenticationService.isLoggedIn();

      if (isLoggedIn) {
        return true;
      } else {
        routeMessage = "You must login to continue.";
      }
    } else {
      routeMessage = "Your session has expired."
    }

    if (routeMessage) this.alertService.info(routeMessage, { keepAfterRouteChange: false });

    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return false;
  }
Example #16
Source File: auth.guard.ts    From angular-10-basic-authentication-example with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const user = this.authenticationService.userValue;
        if (user) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return false;
    }
Example #17
Source File: auth.guard.ts    From angular-10-facebook-login-example with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const account = this.accountService.accountValue;
        if (account) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return false;
    }
Example #18
Source File: auth.guard.ts    From angular-10-jwt-authentication-example with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const currentUser = this.authenticationService.currentUserValue;
        if (currentUser) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return false;
    }
Example #19
Source File: auth.guard.ts    From angular-10-jwt-refresh-tokens with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const user = this.authenticationService.userValue;
        if (user) {
            // logged in so return true
            return true;
        } else {
            // not logged in so redirect to login page with the return url
            this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
            return false;
        }
    }
Example #20
Source File: auth.guard.ts    From angular-10-registration-login-example with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const user = this.accountService.userValue;
        if (user) {
            // authorised so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/account/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
Example #21
Source File: auth.guard.ts    From angular-10-role-based-authorization-example with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const user = this.authenticationService.userValue;
        if (user) {
            // check if route is restricted by role
            if (route.data.roles && route.data.roles.indexOf(user.role) === -1) {
                // role not authorised so redirect to home page
                this.router.navigate(['/']);
                return false;
            }

            // authorised so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return false;
    }
Example #22
Source File: auth.guard.ts    From angular-10-signup-verification-boilerplate with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const account = this.accountService.accountValue;
        if (account) {
            // check if route is restricted by role
            if (route.data.roles && !route.data.roles.includes(account.role)) {
                // role not authorized so redirect to home page
                this.router.navigate(['/']);
                return false;
            }

            // authorized so return true
            return true;
        }

        // not logged in so redirect to login page with the return url 
        this.router.navigate(['/account/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
Example #23
Source File: members.guard.ts    From dating-client with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return combineLatest([
      this.store.select(fromMembers.selectMembersLoaded),
      this.store.select(fromMembers.selectMembersLoading)
    ]).pipe(
      tap(([ loaded, loading ]) => {
        if (!loaded && !loading) {
          this.store.dispatch(MembersPageActions.loadMembers({ filters: {} }));
        }
      }),
      map(() => true)
    );
  }
Example #24
Source File: auth.guard.ts    From angular-material-admin with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const token = localStorage.getItem('token');

    if (token) {
      return true;
    } else {
      this.router.navigate([this.routers.LOGIN]);
    }
  }
Example #25
Source File: auth.guard.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.authService.getEou().then((eou) => {
      if (!eou) {
        this.router.navigate(['/', 'auth', 'sign_in']);
      }

      return !!eou;
    });
  }
Example #26
Source File: publication-lock.guard.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot // eslint-disable-line
  ): Observable<boolean> {
    const id = route.params.id

    return this.publishService.getPublishingStatus(id).pipe(
      tap((publication) => this.facade.setPublication(publication)),
      tap((publication: PublishJobStatusApiModel) => {
        if (publication.status === PublishStatusEnumApiModel.Done) {
          this.router.navigate([`${id}/publishok`])
        }
        if (publication.status === PublishStatusEnumApiModel.Running) {
          this.router.navigate([`${id}/publish`])
        }
      }),
      mapTo(true),
      catchError(() => {
        return of(true)
      })
    )
  }
Example #27
Source File: judgAuth.guard.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
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 #28
Source File: auth-guard.service.ts    From muino-time-management with GNU General Public License v3.0 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot): boolean {
  
    // this will be passed from the route config
    // on the data property
    const expectedRole = route.data.expectedRole;
    
    if (!exist_role(this.token.getInfoExchange(), expectedRole)) {
      this.router.navigate(['NoPremissions']);
      return false;
    }
    return true;
  }
Example #29
Source File: login-guard.service.ts    From litefy with MIT License 6 votes vote down vote up
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    boolean | Observable<boolean> | Promise<boolean> {
    const autenticado = this.authService.Autenticado();

    if (autenticado === false) {
      this.router.navigate(['login']);
      return false;
    }

    return true;
  }