I have the following API function:
checkLoggedInAdmin():boolean
{
//Get the JWT token from local storage
let jwt = localStorage.getItem('jwt');
let httpParams = new HttpParams().set('jwt', jwt);
let headerOptions = new HttpHeaders();
headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
if(jwt=="" || jwt!=null)
{
this.http.post('http://dev.local/scripts/checkLoginAdmin.php', httpParams, {
headers: headerOptions
}).subscribe(
(data)=>{
if(data==true){
return this.loggedIn = true;
}
else{
return this.loggedIn = false;
}
},
(error)=>{
console.log(error)
}
)
}
else
{
this.loggedIn = false;
return this.loggedIn;
}
}
This function, will check if a JWT exists, then if the user logged in is an admin, to let him navigate through different component.
The following, is the canActivate method. I created a new service for it, and include it at the app.module.ts:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthApiService } from './auth-api.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(private router: Router, private authApi: AuthApiService) { }
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot) :boolean
{
if(this.authApi.checkLoggedInAdmin()==true)
{
return true;
}
else
{
//return false;
this.router.navigate(['/login'])
}
}
}
The PHP is returning true when the user logging in is an admin, and false if it's not the case, but the their is no redirection, to the component called forgot
if it is true. And even no redirection when it is false to login
component.
Here is my routes:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { ForgotPasswordComponent } from './forgot-password/forgot-password.component';
import { AuthGuardService } from './auth-guard.service';
const routes: Routes = [
{
path: 'login',
component: LoginComponent
},
{
path:'',
component: LoginComponent
},
{
path: 'forgot',
component: ForgotPasswordComponent,
canActivate: [AuthGuardService]
},
{
path: '**',
redirectTo: 'login',
pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }