@angular/router#CanActivate TypeScript Examples

The following examples show how to use @angular/router#CanActivate. 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: auth.guard.ts    From Uber-ServeMe-System with MIT License 6 votes vote down vote up
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(
    public auth: AngularFireAuth,
    public user: UserService,
    public router: Router
  ) { }

  canActivate(): Promise<boolean> {
    return new Promise(resolve => {
      this.auth.auth.onAuthStateChanged(user => {
        if(!user) this.router.navigate(['login'])
        resolve(user ? true : false)
      })
    })
  }
  
}
Example #2
Source File: auth.guard.ts    From Smersh with MIT License 6 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    if (new DecodedToken().get()) {
      return true;
    }

    this.router.navigate(['/login']);
    return false;
  }
}
Example #3
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 #4
Source File: lp-round-time.guard.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
@Injectable()
export class LpRoundTimeGuard implements CanActivate {
  private readonly redirectUrl = EXTERNAL_LINKS.LANDING_LP;

  constructor(
    @Inject(WINDOW) private readonly window: RubicWindow,
    private readonly lpService: LiquidityProvidingService
  ) {}

  canActivate(): ActivationResult {
    return this.redirectIfNotStarted() as ActivationResult;
  }

  private redirectIfNotStarted(): Observable<Boolean> {
    return this.lpService.getStartAndEndTime().pipe(
      switchMap(([startTime]) => {
        const isStarted = new Date().getTime() > +startTime * 1000;

        if (!isStarted) {
          this.window.location.href = this.redirectUrl;
        }

        return of(isStarted);
      })
    );
  }
}
Example #5
Source File: auth-guard-service.guard.ts    From ng-devui-admin with MIT License 6 votes vote down vote up
@Injectable()
export class AuthGuardService implements CanActivate {
  i18nValues: any;

  constructor(
    private router: Router,
    private authService: AuthService,
    private toastService: ToastService,
    private translate: TranslateService
  ) {}

  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 #6
Source File: auth.guard.ts    From FireAdmin with MIT License 6 votes vote down vote up
@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private navigation: NavigationService) { }

  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 #7
Source File: auth.guard.ts    From ng-conf-2020-workshop with MIT License 6 votes vote down vote up
@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {
    constructor(private router: Router, private userService: UserService) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (this.userService.currentUser) {
            return true;
        }
        this.router.navigate([''], { queryParams: { returnUrl: state.url } });
        return false;
    }
}
Example #8
Source File: communityfolder.guard.ts    From msfs-community-downloader with GNU Affero General Public License v3.0 6 votes vote down vote up
@Injectable({
    providedIn: 'root'
})
export class CommunityfolderGuard implements CanActivate {
    constructor(
        private router: Router,
        private settingsService: SettingsService
    ) { }

    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 #9
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 #10
Source File: auth.guard.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor (private auth: AuthService, private router: Router) {}
  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 #11
Source File: agent.guard.ts    From Developing-Multi-platform-Apps-with-Visual-Studio-Code with MIT License 6 votes vote down vote up
@Injectable({
  providedIn: 'root'
})
export class AgentGuard implements CanActivate {
  constructor(private authorizationService: AuthorizationService, private router:Router){}
  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 #12
Source File: appIsSetup.ts    From pantry_party with Apache License 2.0 6 votes vote down vote up
@Injectable()
export class ApplicationIsSetup implements CanActivate {
  constructor(private router: Router) {}

  canActivate(
    _route: ActivatedRouteSnapshot,
    _state: RouterStateSnapshot
  ) {
    if (getBoolean("app.setupComplete", false)) {
      return true;
    } else {
      this.router.navigate(["/initialSetup"]);

      return false;
    }
  }
}
Example #13
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 #14
Source File: auth-guard.guard.ts    From NetCoreTutes with MIT License 6 votes vote down vote up
@Injectable({
  providedIn: 'root'
})
export class AuthGuardGuard implements CanActivate {
  constructor(private authservice: AuthServiceService, private router: Router) {

  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> {
    return this.authservice
      .getUserobservable()
      .pipe(map(u => u != null && u.isSignedIn));
  }

}
Example #15
Source File: auth.guard.ts    From CloudeeCMS with Apache License 2.0 6 votes vote down vote up
@Injectable()
export class AuthGuard implements CanActivate {

    constructor(
        private userLoginSVC: UserLoginService,
        private tabSVC: TabsNavService
    ) { }

    public canActivate(): boolean | Observable<boolean> {
        return new Observable<boolean>((observer) => {
            this.userLoginSVC.isSessionValidAuthGuard((isAuth: boolean, groups: any) => {
                observer.next(isAuth);
                observer.complete();

                if (!isAuth) this.tabSVC.showLoginForm({ onSuccessReload: true });
            });
        });
    }
}
Example #16
Source File: admin.guard.ts    From ReCapProject-Frontend with MIT License 6 votes vote down vote up
@Injectable({
  providedIn: 'root',
})
export class AdminGuard implements CanActivate {
  constructor(
    private authService: AuthService,
    private toastrService: ToastrService,
    private localStorageService: LocalStorageService,
    private router: Router
  ) {}

  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 #17
Source File: admin.guard.ts    From ngx-admin-dotnet-starter with MIT License 6 votes vote down vote up
@Injectable()
export class AdminGuard implements CanActivate {
  constructor(private roleProvider: NbRoleProvider) {}

  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 #18
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 #19
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 #20
Source File: app.guard.ts    From budget-angular with GNU General Public License v3.0 6 votes vote down vote up
@Injectable({
  providedIn: "root",
})
export class AppGuard implements CanActivate, CanLoad {
  constructor(private authService: AuthService, private router: Router) {}

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

  canLoad(): Observable<boolean> {
    return this.authService.isLoggedIn$().pipe(
      tap((isLoggedIn) => {
        if (!isLoggedIn) {
          this.router.navigate(["/login"]);
        }
      })
    );
  }
}
Example #21
Source File: auth-guard.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (!this.authService.isLoggedIn) {
      console.warn('not logged in, going to /login')
      this.router.navigate(['/login'])
      return false
    }
    return true
  }

}
Example #22
Source File: authenticated-user.guard.ts    From blockcore-hub with MIT License 6 votes vote down vote up
@Injectable({
    providedIn: 'root'
})
export class AuthenticatedUserGuard implements CanActivate {
    constructor(private authService: AuthenticationService) { }

    canActivate(
        // eslint-disable-next-line @typescript-eslint/naming-convention, no-underscore-dangle, id-blacklist, id-match
        _next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.authService.isAuthenticated();
    }
}
Example #23
Source File: auth-guard.service.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private router: Router, private authenticationService: AuthenticationService,
    private alertService: AlertService) { }

  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 #24
Source File: auth.guard.ts    From angular-10-basic-authentication-example with MIT License 6 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) { }

    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 #25
Source File: auth.guard.ts    From angular-10-facebook-login-example with MIT License 6 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private accountService: AccountService
    ) { }

    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 #26
Source File: auth.guard.ts    From angular-10-jwt-authentication-example with MIT License 6 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) { }

    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 #27
Source File: auth.guard.ts    From angular-10-jwt-refresh-tokens with MIT License 6 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) { }

    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 #28
Source File: auth.guard.ts    From angular-10-registration-login-example with MIT License 6 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private accountService: AccountService
    ) {}

    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 #29
Source File: auth.guard.ts    From angular-10-role-based-authorization-example with MIT License 6 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private authenticationService: AuthenticationService
    ) { }

    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;
    }
}