From 49f3c19c1fb6e1f0a53c4ea12085e060d53f5257 Mon Sep 17 00:00:00 2001 From: Matheus Andre Date: Sat, 24 Jan 2026 20:34:26 -0300 Subject: [PATCH] feat: Protect home page with Angular Guards, version clean --- .../src/main/webui/src/app/app.routes.ts | 3 ++ .../webui/src/app/guards/auth_guard.guard.ts | 39 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 timeless-api/src/main/webui/src/app/guards/auth_guard.guard.ts diff --git a/timeless-api/src/main/webui/src/app/app.routes.ts b/timeless-api/src/main/webui/src/app/app.routes.ts index 2494b4b..7f62a4c 100644 --- a/timeless-api/src/main/webui/src/app/app.routes.ts +++ b/timeless-api/src/main/webui/src/app/app.routes.ts @@ -6,6 +6,7 @@ import { SignInComponent } from './pages/sign/sign-in/sign-in.component'; import { RegisteredComponent } from './pages/sign/registered/registered.component'; import { UserConfigComponent } from './pages/user-config/user-config.component'; import { RecordsComponent } from './components/records/records.component'; +import { AuthGuard } from './guards/auth_guard.guard'; export const routes: Routes = [ { @@ -29,6 +30,8 @@ export const routes: Routes = [ { path: 'home', component: HomeComponent, + canActivate: [AuthGuard], + canActivateChild: [AuthGuard], children: [ { path: '', diff --git a/timeless-api/src/main/webui/src/app/guards/auth_guard.guard.ts b/timeless-api/src/main/webui/src/app/guards/auth_guard.guard.ts new file mode 100644 index 0000000..660e004 --- /dev/null +++ b/timeless-api/src/main/webui/src/app/guards/auth_guard.guard.ts @@ -0,0 +1,39 @@ +import { Injectable } from '@angular/core'; +import { + CanActivate, + CanActivateChild, + Router, + ActivatedRouteSnapshot, + RouterStateSnapshot, + UrlTree, +} from '@angular/router'; +import { TimelessApiService } from '../timeless-api.service'; +import { Observable, of } from 'rxjs'; +import { catchError, map } from 'rxjs/operators'; + +@Injectable({ providedIn: 'root' }) +export class AuthGuard implements CanActivate, CanActivateChild { + constructor( + private readonly router: Router, + private readonly apiService: TimelessApiService, + ) {} + + canActivate( + route: ActivatedRouteSnapshot, + state: RouterStateSnapshot, + ): Observable { + return this.apiService.userInfo().pipe( + map(() => true), + catchError(() => { + return of(this.router.createUrlTree(['/'])); + }), + ); + } + + canActivateChild( + childRoute: ActivatedRouteSnapshot, + state: RouterStateSnapshot, + ): Observable { + return this.canActivate(childRoute, state); + } +}