Angular : Routes access restrictions for Logged users

48 views Asked by At

I Need to restrict the logged in user from accessing all the routes when the user is forced to change password after its expiry.

The user should not be able to manipulate the URL in the address bar once he is redirected to the change-password screen.

New to Angular and need assistance in implementing this.

1

There are 1 answers

0
s_erfani On

You can use Guards. For example if you have a LoginComponent and MainComponent, you can use a guard to check if the user logged in or not. you can define it in your route.module.ts

route.module.ts:

const routes: Routes = [
  { path: 'login',  component: LoginComponent },
  { path: '', component: MainComponent ,canActivate: [AuthGuard]},
];

authGaurd:

export class AuthGuard implements CanActivate {
  constructor( private loginService: LoginService, private router: Router) { }

  canActivate(_route: import('@angular/router').ActivatedRouteSnapshot, _state: import('@angular/router').RouterStateSnapshot): boolean | import('@angular/router').UrlTree | import('rxjs').Observable<boolean | import('@angular/router').UrlTree> | Promise<boolean | import('@angular/router').UrlTree> {
    return this.loginService.checkLogin().then(e=>{
      if(e==true) {
          return true;
      } else {
        this.router.navigate(['login']);
        return false;
      }
    });
  }
}

for further information check docs : https://angular.io/api/router/CanActivate