I am using Auth0 and angular2-jwtfor login, and i'm trying to implement CanActivate to block routes when user is logged in.
I have implemented the login code into the navbar.component, and trying to figure out how to make it more modular. I have some examples with services, but none of them match this case, so that's why i came here.
So i think there is 2 steps to make:
- Implement AuthGuard to block routes.
- Split this component into a service so it can send instructions to the AuthGuard to block or allow routes depending if the user is logged or not.
I am hoping someone will give me a solution and i can learn from it. Thank you.
Navbar.component.ts:
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES, CanActivate } from '@angular/router';
import {tokenNotExpired, JwtHelper} from 'angular2-jwt';
declare var Auth0Lock;
@Component({
moduleId: module.id,
selector: 'navbar',
template : `
<button *ngIf="!loggedIn()" (click)="login()">Login</button>
<button *ngIf="loggedIn()" (click)="logout()">Logout</button>
<a *ngIf="loggedIn()" [routerLink]="['/users']">Users</a>
<button *ngIf="!loggedIn()" (click)="login()" class="btn btn-danger">Login</button>
<button *ngIf="loggedIn()" (click)="logout()" class="btn btn-default">Logout</button>
`,
directives: [ROUTER_DIRECTIVES]
})
export class NavbarComponent{
lock = new Auth0Lock('xxxxxxxxxxxxxxxxx','yyyyyyyyyyyyyy')
jwtHelper: JwtHelper = new JwtHelper();
location: Location;
profile : any;
constructor(){
this.profile = JSON.parse(localStorage.getItem('profile'));
}
login(){
var self = this;
this.lock.show((err: string, profile: string, id_token: string) =>{
if (err){
throw new Error(err);
}
localStorage.setItem('profile', JSON.stringify(profile));
localStorage.setItem('id_token', id_token);
self.loggedIn();
});
}
logout(){
localStorage.removeItem('profile');
localStorage.removeItem('id_token');
this.loggedIn();
}
loggedIn(){
return tokenNotExpired();
}
}
auth.guard.ts:
import { CanActivate } from '@angular/router';
export class AuthGuard implements CanActivate {
canActivate() {
return true;
}
}
app.routes.ts
import { provideRouter, RouterConfig } from '@angular/router';
import {UsersComponent} from './users/users.component';
import {AuthGuard} from './navbar/auth.guard';
export const routes: RouterConfig = [
{ path: 'users', component: UsersComponent, canActivate: [AuthGuard] },
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes),
AuthGuard
];