Skip to content

Commit a4ac072

Browse files
author
badripaudel77
committed
AuthGuard implemented to protect route against unauthenticated requests.
1 parent 0d5788b commit a4ac072

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/app/app-routing.module.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@ import {NoRecipeSelectedComponent} from "./recipes/no-recipe-selected/no-recipe-
66
import {RecipesDetailComponent} from "./recipes/recipes-detail/recipes-detail.component";
77
import {RecipeEditComponent} from "./recipes/recipe-edit/recipe-edit.component";
88
import {AuthenticationComponent} from "./authentication/authentication.component";
9+
import {AuthGuard} from "./guards/auth.guard";
910

1011
const routes: Routes = [
1112
{ path: '', redirectTo: '/recipes', pathMatch: "full" },
1213
{
1314
path: 'recipes',
1415
component: RecipesComponent,
16+
canActivate: [AuthGuard],
1517
children: [
1618
{ path: '', component: NoRecipeSelectedComponent }, // /recipes/, /recipes
1719
{ path: 'add', component: RecipeEditComponent }, // /recipes/add

src/app/guards/auth.guard.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from "@angular/router";
2+
import {map, Observable, take} from "rxjs";
3+
import {AuthenticationService} from "../services/authentication.service";
4+
import {Injectable} from "@angular/core";
5+
6+
/**
7+
* Angular guard runs before running the code
8+
* Useful to check if route is accessible or not
9+
* This is also a "service"
10+
*/
11+
12+
@Injectable({ providedIn: 'root' })
13+
export class AuthGuard implements CanActivate {
14+
constructor(private authenticationService: AuthenticationService, private router: Router) {
15+
16+
}
17+
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
18+
// check if user is logged in or not
19+
// check if user is authorized or not
20+
// can be added to app-routing.module file with needed route.
21+
// listen for latest user value only and unsubscribe.
22+
return this.authenticationService.userSubject.pipe(take(1),map(user => {
23+
if(!user) {
24+
// this.router.navigate(['/auth']);
25+
return this.router.createUrlTree(['/auth']);
26+
}
27+
return true;
28+
}));
29+
}
30+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy