Redirect If Token Not Valid - javascript

I am using Angular2 and Auth0 for authentication. I can see the token is being stored into local storage. I am writing a function in my auth.service.ts file to check for a valid token then calling that function on init in the component. I have tried many different variations of this function but cannot get the app to validate correctly.
After I login it forwards me back to the home page even when I do login and retrieve a valid token.
My goal is to not allow access to this page without a valid token. But when there is a valid token allow access to this page.
This is what I have tried currently,
auth.service.ts
import { Injectable } from '#angular/core';
import { Router, CanActivate } from '#angular/router';
import { tokenNotExpired, JwtHelper } from 'angular2-jwt';
import { myConfig } from './auth.config';
// Avoid name not found warnings
declare var Auth0Lock: any;
var options = {
theme: {
logo: '../assets/img/logo.png',
primaryColor: '#779476'
},
auth: {
responseType: 'token',
redirect: true,
redirectUrl: "http://localhost:3000/dashboard",
},
languageDictionary: {
emailInputPlaceholder: "email#example.com",
title: "Login or SignUp"
},
};
#Injectable()
export class Auth {
// Configure Auth0
lock = new Auth0Lock(myConfig.clientID, myConfig.domain, options,{});
constructor(private router: Router ) {
// Add callback for lock `authenticated` event
this.lock.on('authenticated', (authResult) => {
localStorage.setItem('jwtToken', authResult.idToken);
});
}
public login() {
this.lock.show();
};
public authenticated() {
return tokenNotExpired();
};
public isAuthenticated(): boolean {
try {
var jwtHelper: JwtHelper = new JwtHelper();
var token = this.accessToken;
if (jwtHelper.isTokenExpired(token))
return false;
return true;
}
catch (err) {
return false;
}
}
private get accessToken(): string {
return localStorage.getItem('jwtToken');
}
public logout() {
localStorage.removeItem('jwtToken');
};
}
guard.service.ts
import { Injectable } from '#angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { Auth } from './auth.service';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class Guard implements CanActivate {
constructor(protected router: Router, protected auth: Auth ) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
if (state.url !== '/pages/home' && !this.auth.isAuthenticated()) {
this.auth.logout();
this.router.navigate(['/pages/home']);
return false;
}
return true;
}
}
app.routing.ts
import {Guard} from "./services/guard.service";
const appRoutes: Routes = [
{
path: '',
redirectTo: 'pages/home',
pathMatch: 'full',
},
{
path: '',
component: FullLayoutComponent,
canActivate: [Guard],
data: {
title: 'Home'
},
children: [
{
path: 'dashboard',
component: DashboardComponent,
data: {
title: 'Dashboard'
}
},
app.module.ts
import { Guard } from "./services/guard.service";
import { Auth } from "./services/auth.service";
providers: [
Guard,
Auth
],

right way to achieve this to use Guards
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { AuthService } from './authService';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class AuthGuard implements CanActivate {
constructor(protected router: Router, protected authService: AuthService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
if (state.url !== '/login' && !this.authService.isAuthenticated()) {
this.authService.logOut();
this.router.navigate(['/login']);
return false;
}
return true;
}
}
And in you rotes set
path: 'admin',
component: AdminPages.AdminPagesComponent,
canActivate: [AuthGuard],
children: [
{
path: 'dashboard',
component: Dashboard,
data: {
menu: {
title: 'Dashboard',
icon: 'ion-android-home',
selected: false,
expanded: false,
order: 0
}
}
},
authservice
public isAuthenticated(): boolean {
try {
var jwtHelper: JwtHelper = new JwtHelper();
var token = this.accessToken;
if (jwtHelper.isTokenExpired(token))
return false;
return true;
}
catch (err) {
return false;
}
}
public logOut(): void {
localStorage.removeItem("access_token");
}
private get accessToken(): string {
return localStorage.getItem('access_token');
}
private saveJwt(jwt): void {
if (jwt) {
localStorage.setItem('access_token', jwt)
}
}
public login(loginModel: LoginModel): Promise<void> {
return new Promise<void>((resolve, reject) => {
var username = loginModel.email;
var password = loginModel.password;
var creds =
"username=" + username + "&password=" + password + "&client_id=" + this.clientId + "&grant_type=" + this.grant_type;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.httpClient.post(this.identityServerUrl + "/connect/token", creds, { headers })
.toPromise()
.then(response => {
this.saveJwt(response.json().access_token);
resolve();
})
.catch(err => {
reject(err.json().error_description)
});
});
}

Related

Can't resolve all parameters for AuthService on Angular

I'm trying to start my angular app and i'm getting this error below for some reason. I tried removing the auth service provider from my component and removing also the auth service from my constractor inside my component, but nothing changed... I can't figure out what i'm doing wrong and i'm beginner on angular.
The error:
Can't resolve all parameters for AuthService: (?, ?, [object Object]).
My component:
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { AuthService } from '../../Services/auth.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [AuthService]
})
export class LoginComponent {
isUserLoggedIn: boolean;
emailAddress: string;
password: string;
invalidLogin: boolean;
invalidText: string;
constructor(private authService: AuthService, private router: Router) {
if (authService.getCurrentUser() != null) {
router.navigate(['/home']);
}
}
login() {
if (!this.authService.login(this.emailAddress.toString(), this.password.toString())) {
this.invalidLogin = true;
this.invalidText = "Wrong Email Address or password";
}
}
}
My service:
import { Inject } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
import { UserModel } from "../Models/UserModel";
export class AuthService {
constructor(private router: Router, private http: HttpClient, #Inject('BASE_URL') private baseUrl: string) {}
login(email: string, password: string) {
const headers = {'Content-Type': 'application/json', };
const body = { emailAddress: email, password: password };
let userLoggedIn: Boolean = false;
this.http.post<any>(this.baseUrl + "Api/Login", body, { headers }).subscribe(response => {
if (response.username != null) {
let user: UserModel
user = response;
this.router.navigate(['/home']);
this.saveUserToLocalStorage(user);
userLoggedIn = true
}
}, error => console.error(error));
return userLoggedIn;
}
saveUserToLocalStorage(loggedInUser: UserModel) {
sessionStorage.setItem("loggedInUser", JSON.stringify(loggedInUser));
}
getCurrentUser() {
return sessionStorage.getItem("loggedInUser")
}
logout() {
sessionStorage.removeItem("loggedInUser")
this.router.navigate([''])
}
createUser(userData: UserModel) {}
sendResetPasswordEmail() {}
}
I think this is because you use Router in your constructor, try to do this
constructor(private readonly injector: Injector,
...) {}
public get router(): Router {
return this.injector.get(Router);
}
I found what was the problem. I had to mark my service class as #Injectable()
Like this:
#Injectable()
export class SchoolService {
...
}

refresh header component after login using angular 11

actually i am using angular 11 and i want to show username in header component but my header is load first then my login component is load so after loading login component data store in local storage that why when i refresh page then user name is show but i dont want refresh page so what can i do for that please help me
below code is my authservice
import { Injectable } from '#angular/core';
import { environment } from 'src/environments/environment'
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
baseUrl = environment.apiUrl;
constructor(private http: HttpClient, private router: Router) { }
loginUser(data: {}) {
return this.http.post(this.baseUrl + 'signin', data)
}
isLoggedIn() {
//console.log(localStorage.getItem('user_details'))
if (localStorage.getItem('user_details') !== undefined && localStorage.getItem('user_details') !== null) {
//console.log("if")
return true;
} else {
return false;
}
//return !!localStorage.getItem('user_details')
}
getUserName(): any {
const userName = localStorage.getItem('user_details');
if (userName) {
return JSON.parse(userName);
}
return false;
}
isLoggedOut() {
localStorage.removeItem('user_details');
this.router.navigate(['/login']);
}
}
this is my header component
import { Component, OnInit, HostListener } from '#angular/core';
import { AuthService } from '../../login/services/auth.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
scrolled: boolean = false;
userName: string = '';
fname: string = '';
lname: string = "";
#HostListener("window:scroll", [])
onWindowScroll() {
this.scrolled = window.scrollY > 1;
}
constructor(public auth: AuthService, private router: Router) { }
ngOnInit(): void {
if (this.auth.isLoggedIn()) {
this.router.navigate(['dashboard']);
}
const user = this.auth.getUserName();
this.userName = user.role_name;
this.fname = user.first_name.charAt(0);
this.lname = user.last_name.charAt(0);
}
logOut() {
localStorage.removeItem('user_details');
this.router.navigate(['/login']);
}
}
below is login component
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import { AuthService } from './services/auth.service';
import { Router } from '#angular/router';
import { Md5 } from 'md5-typescript';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm: any;
data: any;
success: any;
message: any;
constructor( private auth: AuthService, private router: Router ) {
this.loginForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.pattern('^[\\w-\\.]+#([\\w-]+\\.)+[\\w-]{2,4}$')]),
password: new FormControl('', Validators.required)
});
}
ngOnInit(): void { }
onSubmit() {
console.log(this.loginForm.value);
let data = {
"email_id": this.loginForm.value.email,
"password": Md5.init(this.loginForm.controls['password'].value)
}
this.auth.loginUser(data).subscribe(
(response: any) => {
this.data == response;
this.success == response.success;
if (response.success == 1) {
localStorage.setItem("user_details", JSON.stringify(JSON.parse(response.data).user_details))
console.log(localStorage.getItem('user_details'));
this.router.navigate(['dashboard']);
} else {
this.message = response.message;
}
}
);
this.loginForm.reset();
}
}
You can't use local storage to get logged in user details, because you component is already loaded. You need to create shared service using Subject or Behaviorsubject (RXJS operatoer) You can find example https://medium.com/#hitensharma1515/sharing-data-between-components-using-service-2d662a653a89

Angular authentication and route guard

I'm building a angular spa front-end that consumes a GraphQL endpoint. After the users login, i set the token on localstorage and on my AuthService i set the auth state.My idea (coming from a React) was when the App component mounts ngOnInit i'll make a request for a me query who will return the user from the token stored on local storage, and i want to set the user on the AuthService. The problem i'm facing is that i've created a dashboard route which is protected, but the AuthGuard is not waiting for the App Component ngOnInit to finish and it will redirect to the login page.
import {Component, OnDestroy, OnInit} from '#angular/core';
import {MeGQL, User} from "../generated/graphql";
import {AuthService} from "./auth.service";
import {Router} from "#angular/router";
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
title = 'frontend';
loading: boolean = true
private meSubs: any;
constructor(private meQuery: MeGQL, private authService: AuthService, private router: Router) {
}
async ngOnInit() {
this.loading = true
console.log("MONTOU APP")
this.loading = true
return this.meQuery.fetch({}, {
fetchPolicy: "network-only",
}).toPromise()
.then(({data}) => {
console.log("ENTROU NO THEN")
if (data.me) {
console.log(data.me)
this.authService.setUser(data.me)
this.loading = false
}
}).catch(e => {
this.loading = false
console.log("ERROR: ", e)
})
}
}
{{ loading }}
<div *ngIf="loading">Carregando...</div>
<div *ngIf="!loading">
<router-outlet></router-outlet>
</div>
import { Injectable } from '#angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from "#angular/router";
import {AuthService} from "../auth.service";
import {Observable} from "rxjs";
#Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate{
constructor(private authService: AuthService, private router: Router) { }
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean > {
console.log("Auth Guard user mount")
if(!this.authService.isAuthenticated()) {
console.log("Não autenticado")
await this.router.navigate(['/login'])
return false
}
return true
}
}
import {Injectable} from '#angular/core';
import {User, MeQuery, MeDocument, MeQueryVariables} from "../generated/graphql";
import {BehaviorSubject} from "rxjs";
import {Apollo} from "apollo-angular";
export type CurrentUserType = Pick<User, 'id' | 'name' | 'email' | 'active' | 'type'>
#Injectable({
providedIn: 'root'
})
export class AuthService {
private TOKEN_KEY = "AGENDEI_TOKEN"
private currentUser: CurrentUserType | null = null
private _isAuthenticated = new BehaviorSubject(false);
private authSource = new BehaviorSubject<CurrentUserType | null>(null)
constructor(private apollo: Apollo) { }
loginUser(user: CurrentUserType, accessToken: string) {
localStorage.setItem(this.TOKEN_KEY, accessToken)
this.setUser(user)
this._isAuthenticated.next(true)
}
setUser(user: CurrentUserType) {
this.currentUser = user
}
async logout() {
localStorage.removeItem(this.TOKEN_KEY)
await this.apollo.getClient().resetStore()
this._isAuthenticated.next(false);
}
public isAuthenticated(): Boolean {
return this._isAuthenticated.value
}
public getUserFromMeQuery() {
return this.apollo.query<MeQuery, MeQueryVariables>({
query: MeDocument
}).toPromise()
}
}
I believe making changes in canActivate method in your guard service will work.
Cause While checking if a user is logged in or not you are not waiting for auth service to set the Authentication state.
AuthService
public isAuthenticated(): Promise<boolean> {
return this._isAuthenticated.toPromise();
}
AuthGuardService
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean > {
console.log("Auth Guard user mount")
const isAuthenticated = await this.authService.isAuthenticated()
if(!isAuthenticated) {
console.log("Não autenticado")
await this.router.navigate(['/login'])
return false
}
return true
}
Try to use await in ngOninit of AppComponent:
async ngOnInit() {
this.loading = true
console.log("MONTOU APP")
this.loading = true
let response;
try {
response = await this.meQuery.fetch({}, {
fetchPolicy: "network-only",
}).toPromise()
let {data} = response;
if (data.me) {
console.log(data.me)
this.authService.setUser(data.me)
}
this.loading = false
} catch (err) {
this.loading = false
console.log("ERROR: ", err)
}
}

Login In Angular 10 with JWT

I am facing trouble in logging in with JWT in angular, I have successfully logged in via the login and also stored the token, but my frontend is not updating itself with the same
Auth.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { ErrorprocessorService } from './errorprocessor.service';
import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';
interface LogUser {
success: boolean;
message: string;
token: string;
user: {
name: string;
username: string;
email: string;
};
}
interface JWTResponse {
success: boolean;
message: string;
user: any;
}
#Injectable({
providedIn: 'root'
})
export class AuthService {
tokenKey = 'JWT';
isAuthenticated: Boolean = false;
username: Subject<string> = new Subject<string>();
authToken: string = undefined;
constructor(private http: HttpClient, private errorProcessor: ErrorprocessorService) { }
loadUserCredentials() {
const credentials = JSON.parse(localStorage.getItem(this.tokenKey));
console.log('Loading User Credentials : ', credentials);
if (credentials && credentials.username !== undefined) {
this.useCredentials(credentials);
if (this.authToken) {
this.checkJWTtoken();
}
}
}
checkJWTtoken() {
this.http.get<JWTResponse>('http://localhost:3000/auth/checkToken')
.subscribe(res => {
console.log('JWT Token Valid: ', res);
this.sendUsername(res.user.username);
}, err => {
console.log('JWT Token Invalid: ', err);
this.destroyUserCedentials();
});
}
storeUserCredentials(credentials: any) {
console.log('Storing User Credentials : ', credentials);
localStorage.setItem(this.tokenKey, JSON.stringify(credentials));
this.storeUserCredentials(credentials);
}
useCredentials(credentials: any) {
this.isAuthenticated = true;
this.sendUsername(credentials.username);
this.authToken = credentials.token;
}
sendUsername(name: string) {
this.username.next(name);
}
loginUser(user: any): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post<LogUser>('http://localhost:3000/auth/login', user, httpOptions)
.pipe(map(res => {
this.storeUserCredentials({ username: user.username, token: res.token });
return { 'success': true, 'username': user.username };
}))
}
destroyUserCedentials() {
this.authToken = undefined;
this.clearUsername();
this.isAuthenticated = false;
localStorage.removeItem(this.tokenKey);
}
clearUsername() {
this.username.next(undefined);
}
logOut() {
this.destroyUserCedentials();
}
isLoggedIn(): Boolean {
return this.isAuthenticated;
}
getUsername(): Observable<string> {
return this.username.asObservable();
}
getToken(): string {
return this.authToken;
}
}
Login.component.ts
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
errMsg: string;
user = {
username: '',
password: ''
};
constructor(private authService: AuthService, private router: Router) { }
ngOnInit(): void {
}
onSubmit(): void {
console.log(this.user);
this.authService.loginUser(this.user)
.subscribe(res => {
if (res.success) {
this.router.navigate(['/dashboard']);
} else {
console.log(res);
}
}, err => {
this.errMsg = <any>err;
});
}
}
Auth-guard.server.ts
import { Injectable } from '#angular/core';
import { Router, CanActivate } from '#angular/router';
import { AuthService } from './auth.service';
#Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) { }
canActivate(): boolean {
if (!this.auth.isLoggedIn()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
Header.component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { Subscription } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
username: string = undefined;
subscription: Subscription;
constructor(private authService: AuthService, private router: Router) { }
ngOnInit(): void {
this.authService.loadUserCredentials();
this.subscription = this.authService.getUsername()
.subscribe(name => { console.log(name); this.username = name; });
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
openProfile(): void {
this.router.navigate(['/profile']);
}
logOut(): void {
this.username = undefined;
this.authService.logOut();
}
}
can anyone help me with this?
Thanks in advance and also if you need any other files ping me ill send you those
Your code has infinite loop:
storeUserCredentials(credentials: any) {
console.log('Storing User Credentials : ', credentials);
localStorage.setItem(this.tokenKey, JSON.stringify(credentials));
this.storeUserCredentials(credentials);
}
It could be be an error that blocking your app running

guard in angular how can I get value from auth.service.ts (user login or not)

I use canActivate in history.guard and how can I check if the user login or not!
the value which I console always return false!
Do I need to create a new function in auth.service or just edit in history.guard ? Is there any way instead of using subscribe ??
auth.service.ts
import { Injectable } from '#angular/core';
import { Router } from '#angular/router';
import { Subject } from 'rxjs/Subject';
import { ApiService, VERSION, ENDPOINT } from '../api/api.service';
import { Observable, BehaviorSubject } from 'rxjs';
#Injectable()
export class AuthService {
logger = new BehaviorSubject<Object>(false);
referralRoute: string;
constructor(
private router: Router,
private api: ApiService
) {
}
logout() {
localStorage.removeItem('access-token');
localStorage.removeItem('uid');
localStorage.removeItem('client');
this.redirectToLogin();
this.logger.next(false);
}
postLogin(body: any) {
this.api.get(['token.json'], {}).subscribe(
(res: any) => {
localStorage.setItem('access-token', res['access-token']);
localStorage.setItem('uid', res['uid']);
localStorage.setItem('client', res['client']);
this.logger.next(true);
this.redirectToPrevStep();
},
(err) => {
this.logger.next(err);
});
}
checkLogin(body: any) {
this.api.get([VERSION, ENDPOINT.checkLogin], {}).subscribe(
(res: any) => {
this.logger.next(true);
},
(err) => {
this.logger.next(err);
});
}
checkUserLogin() {
const isLogin = !!localStorage.getItem('JWT_TOKEN');
if (isLogin) {
this.logger.next(true);
} else {
this.logger.next(false);
}
}
subscribeLogger(): Observable<Object> {
return this.logger.asObservable();
}
isAuthenticated() {
const token = localStorage.getItem('access-token');
let isAuthenticated: boolean;
if (this.isTokenInvalid()) {
localStorage.removeItem('access-token');
isAuthenticated = false;
} else {
isAuthenticated = true;
}
return isAuthenticated;
}
getUserInfo() {
const token = localStorage.getItem('access-token');
// let userInfo = this.jwtHelper.decodeToken(token);
return {};
// this.jwtHelper.decodeToken(token),
// this.jwtHelper.getTokenExpirationDate(token),
// this.jwtHelper.isTokenExpired(token)
// );
}
isTokenInvalid() {
const token = localStorage.getItem('access-token');
if (!token) {
return true
} else {
// this.api.setHeaders(token);
return false;
}
}
/**
* Helper method for set up referral route, enable useful redirect after login
* #method setRoute
* #param {string} route Route as defined in app.routes, eg. /user/1
*/
setRoute(route: string): void {
this.referralRoute = route;
}
redirectToPrevStep() {
const route = this.referralRoute ? this.referralRoute : '/';
this.router.navigateByUrl(route);
}
redirectToLogin(current: string = '/') {
// Store current url as referral and use latter for login redirection
this.setRoute(current);
window.scroll(0, 0);
this.router.navigate(['/auth/login']);
}
}
history.guard.ts
import { Injectable } from '#angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { AuthService } from '../../core/service/auth/auth.service';
#Injectable({ providedIn: 'root' })
export class HistoryGuard implements CanActivate {
checkUserLogin: boolean;
constructor(
private router: Router,
private auth: AuthService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const checkUserLogin = this.auth.subscribeLogger().subscribe(
(data: any) => {
this.checkUserLogin = data;
}
);
if (!this.checkUserLogin) {
return this.router.navigate(['mypage']);
}
else {
return this.checkUserLogin;
}
}
}
history.module.ts
import { NgModule } from '#angular/core';
import { HistoryComponent } from './history.component';
import { HistoryItemComponent } from './history-item/history-item.component';
import { RouterModule, Routes } from '#angular/router';
import { CommonModule } from '#angular/common';
import { HistoryGuard } from './history.guard';
const routes: Routes = [
{
path: '',
component: HistoryComponent,
canActivate: [HistoryGuard]
},
{
path: ':id',
component: HistoryItemComponent,
canActivate: [HistoryGuard]
}
];
#NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes)
],
declarations: [HistoryComponent, HistoryItemComponent]
})
export class HistoryModule { }
Hi this how I implemented AuthGuard, you can check just if in local storage is a JWT token or not, because on logout you should delete jwt token from localStorage and that's it
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.authService.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
// Auth service
isLoggedIn() {
return Boolean(this.getToken());
}
getToken() {
return this.localStorage$.retrieve('authenticationToken');
}
logout() {
this.localStorage$.clear('authenticationtoken');
}
This is how your canActivate should look like:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.auth.subscribeLogger().pipe(
tap(login => {
if(!login) {
this.router.navigate(['mypage']); // If user is not logged in, just navigate away
}
})
);
}

Categories