Skip to content

Commit 49f3c19

Browse files
committed
feat: Protect home page with Angular Guards, version clean
1 parent 4769146 commit 49f3c19

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

timeless-api/src/main/webui/src/app/app.routes.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { SignInComponent } from './pages/sign/sign-in/sign-in.component';
66
import { RegisteredComponent } from './pages/sign/registered/registered.component';
77
import { UserConfigComponent } from './pages/user-config/user-config.component';
88
import { RecordsComponent } from './components/records/records.component';
9+
import { AuthGuard } from './guards/auth_guard.guard';
910

1011
export const routes: Routes = [
1112
{
@@ -29,6 +30,8 @@ export const routes: Routes = [
2930
{
3031
path: 'home',
3132
component: HomeComponent,
33+
canActivate: [AuthGuard],
34+
canActivateChild: [AuthGuard],
3235
children: [
3336
{
3437
path: '',
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { Injectable } from '@angular/core';
2+
import {
3+
CanActivate,
4+
CanActivateChild,
5+
Router,
6+
ActivatedRouteSnapshot,
7+
RouterStateSnapshot,
8+
UrlTree,
9+
} from '@angular/router';
10+
import { TimelessApiService } from '../timeless-api.service';
11+
import { Observable, of } from 'rxjs';
12+
import { catchError, map } from 'rxjs/operators';
13+
14+
@Injectable({ providedIn: 'root' })
15+
export class AuthGuard implements CanActivate, CanActivateChild {
16+
constructor(
17+
private readonly router: Router,
18+
private readonly apiService: TimelessApiService,
19+
) {}
20+
21+
canActivate(
22+
route: ActivatedRouteSnapshot,
23+
state: RouterStateSnapshot,
24+
): Observable<boolean | UrlTree> {
25+
return this.apiService.userInfo().pipe(
26+
map(() => true),
27+
catchError(() => {
28+
return of(this.router.createUrlTree(['/']));
29+
}),
30+
);
31+
}
32+
33+
canActivateChild(
34+
childRoute: ActivatedRouteSnapshot,
35+
state: RouterStateSnapshot,
36+
): Observable<boolean | UrlTree> {
37+
return this.canActivate(childRoute, state);
38+
}
39+
}

0 commit comments

Comments
 (0)