Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auth guard not working in angular 5

Here is my static login service

login(email: string, password: string) {
debugger;
const user = {
  username: email,
  password: password,

};
if (email === "admin" && password === "admin") {
  localStorage.setItem("currentUser", JSON.stringify(user));
}
if (localStorage.getItem("currentUser")) {
  // logged in so return true
  return user;
} else {
  return false;
}
}

My authguard service

  export class AuthGuard implements CanActivate {
  constructor(private router: Router) {


  }
        isAuthenticated(): boolean{
      if (localStorage.getItem("currentUser")) {
        return true;
      }
      else{
        return false;
      }
    }

    canActivate(): boolean {
      if (!this.isAuthenticated()) {
        this.router.navigate(['login']);
        return false;
      }
      return true;
    }
}

my app.routing.ts

const appRoutes: Routes = [
  { path: "home", component: HomeComponent ,canActivate: [AuthGuard]},
  { path: "login", component: AuthComponent },
  { path: "", component: AuthComponent },
  { path: "employees", component: EmpComponent,canActivate: [AuthGuard] },
  // otherwise redirect to home
  { path: "**", redirectTo: "/" }
];

app.module.ts

@NgModule({
  declarations: [AppComponent, HeaderComponent, FooterComponent],
  imports: [
    BrowserModule,
    FormsModule,
    SharedModule,
    HomeModule,
    AuthModule,
    EmpModule,
    routing,
    Ng4LoadingSpinnerModule,
    AlertModule.forRoot()
  ],
  providers: [AuthGuard, AuthenticationService],
  schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
  bootstrap: [AppComponent]
})

I just tested this by entering a route directly in browser url for example /home which has canactivate enabled in its route config but when i do so the home contents are displayed instead of redirecting to the login page.Need too know what's wrong here any help will be really appreciated thanks in advance :)

like image 713
Melvin Avatar asked Dec 09 '17 07:12

Melvin


2 Answers

There is no issue with your current code, if you have routing for each component separately, remove them and have them only in the app.module.ts

like image 109
Sajeetharan Avatar answered Oct 05 '22 06:10

Sajeetharan


if you re using the route guard add it inside root app.module or what ever module.ts file

providers: [AuthGuard]
like image 24
Samithe Adhikari Avatar answered Oct 05 '22 07:10

Samithe Adhikari