Skip to content

Commit feb098f

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

3 files changed

Lines changed: 48 additions & 1 deletion

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: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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 { timelessLocalStorageKey } from '../constants';
11+
import { TimelessApiService } from '../timeless-api.service';
12+
import { Observable, of } from 'rxjs';
13+
import { catchError, map } from 'rxjs/operators';
14+
15+
@Injectable({ providedIn: 'root' })
16+
export class AuthGuard implements CanActivate, CanActivateChild {
17+
constructor(
18+
private readonly router: Router,
19+
private readonly apiService: TimelessApiService,
20+
) {}
21+
22+
canActivate(
23+
route: ActivatedRouteSnapshot,
24+
state: RouterStateSnapshot,
25+
): Observable<boolean | UrlTree> {
26+
return this.apiService.userInfo().pipe(
27+
map(() => true),
28+
catchError(() => {
29+
return of(this.router.createUrlTree(['/']));
30+
}),
31+
);
32+
}
33+
34+
canActivateChild(
35+
childRoute: ActivatedRouteSnapshot,
36+
state: RouterStateSnapshot,
37+
): Observable<boolean | UrlTree> {
38+
return this.canActivate(childRoute, state);
39+
}
40+
}

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,11 @@ export class TimelessApiService {
5151
throw new Error();
5252
}
5353
const user = JSON.parse(data);
54-
return this.httpClient.get(`/api/users/${user.id}`);
54+
return this.httpClient.get(`/api/users/${user.id}`, {
55+
headers: {
56+
Authorization: `Bearer ${user.token}`,
57+
},
58+
});
5559
}
5660

5761
deleteRecord(id: number) {

0 commit comments

Comments
 (0)