Striving to enhance frontend security by restricting access to specific IDs. The goal is to redirect anyone trying to access routes other than /login/:id
to a page-not-found error message if not already logged in, but encountering some issues.
Below are the routing table and guard implementations:
UPDATE: Issue resolved with updated code:
app-routing.module.ts
// Routing array - setting routes for each HTML page
const appRoutes: Routes = [{
path: 'login/:id',
canActivate: [AuthGuard],
children: []
},
{
path: '',
canActivate: [AuthGuard],
canActivateChild: [AuthGuard],
children: [{
path: '',
redirectTo: '/courses',
pathMatch: 'full'
},
{
path: 'courses',
component: CourseListComponent,
pathMatch: 'full'
},
{
path: 'courses/:courseId',
component: CourseDetailComponent,
pathMatch: 'full'
},
{
path: 'courses/:courseId/unit/:unitId',
component: CoursePlayComponent,
children: [{
path: '',
component: CourseListComponent
},
{
path: 'lesson/:lessonId',
component: CourseLessonComponent,
data: {
type: 'lesson'
}
},
{
path: 'quiz/:quizId',
component: CourseQuizComponent,
data: {
type: 'quiz'
}
}
]
}
]
},
{
path: '**',
component: PageNotFoundComponent,
pathMatch: 'full'
}
];
auth.guard.ts
canActivate(route: ActivatedRouteSnapshot, state:
RouterStateSnapshot): boolean |
Observable<boolean> | Promise<boolean> {
// saving the ID from route snapshot
const id = +route.params.id;
// handle logging with ID
if (id) {
this.authUserService.login(id);
// return false on error
if (this.authUserService.errorMessage) {
this.router.navigate(["/page_not_found"]);
return false;
}
// no errors - redirect to courses and continue
else {
this.router.navigate(["courses"]);
return true;
}
}
// already logged in and navigating between pages
else if (this.authUserService.isLoggedIn())
return true;
else {
this.router.navigate(["/page_not_found"]);
return false;
}
}
canActivateChild(route: ActivatedRouteSnapshot, state:
RouterStateSnapshot): boolean |
Observable<boolean> | Promise<boolean> {
return this.canActivate(route, state);
}
auth-user.service.ts
export class AuthUserService implements OnDestroy {
private user: IUser;
public errorMessage: string;
isLoginSubject = new BehaviorSubject<boolean>(this.hasToken());
constructor(private userService: UserService) {}
login(id: number) {
this.userService.getUser(id).subscribe(
user => {
this.user = user;
localStorage.setItem('user', JSON.stringify(this.user));
localStorage.setItem('token', 'JWT');
this.isLoginSubject.next(true);
},
error => this.errorMessage = <any>error
);
}
private hasToken(): boolean {
return !!localStorage.getItem('token');
}
isLoggedIn(): Observable<boolean> {
return this.isLoginSubject.asObservable();
}
logout() {
localStorage.removeItem('user');
localStorage.removeItem('token');
this.isLoginSubject.next(false);
}
ngOnDestroy() {
this.logout();
}