can anyone help me with this. I am trying to implement an authentication guard for on my LogIn component. This guard should allow users to access the dashboard only in the following conditions: If there is a session token defined in local storage and if the token is valid (validity must be checked through the GET call that checks the session token). If the token is not valid, I want to delete the token from the local storage and redirect to login page. Here is what I've done so far:
core/guard/auth.guard.ts
import { Injectable } from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import { Observable } from 'rxjs';
import {AuthService} from "../services/auth.service";
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor( private service: AuthService, private router:Router) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if(this.service.isLoggedIn()){
return true;
}else {
return this.router.navigate(["login"]);
}
}
}`
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { KpiComponent } from './kpi/kpi.component';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { PieComponent } from './kpi/pie/pie.component';
import { BarComponent } from './kpi/bar/bar.component';
import { MainTemplateComponent } from './atomic/main-template/main-template.component';
import { LoginPageComponent } from './atomic/organisms/login-page/login-page.component';
import { DashboardPageComponent } from './atomic/organisms/dashboard-page/dashboard-page.component';
import { NavbarComponent } from './navbar/navbar.component';
import { MatMenuModule } from '@angular/material/menu';
import { ReactiveFormsModule } from '@angular/forms';
import { reducers } from './store';
import { HrMaterialModule } from './material/material.module';
@NgModule({
declarations: [
AppComponent,
KpiComponent,
PieComponent,
BarComponent,
MainTemplateComponent,
LoginPageComponent,
DashboardPageComponent,
NavbarComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
StoreModule.forRoot(reducers, {}),
StoreDevtoolsModule.instrument(),
BrowserAnimationsModule,
MatCardModule,
MatButtonModule,
MatIconModule,
ReactiveFormsModule,
MatMenuModule,
HrMaterialModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
navbar.component.ts
<div class="navbar">
<a routerLink="/dashboard">
<img src="../../assets/imbus-logo.svg" alt="imbus-logo">
</a>
<div class="navbar-elements">
<div class="user-elements">
<a routerLink="/dashboard" class="account-icon" [matMenuTriggerFor]="menu">
<img src="../../assets/manage-account.svg" alt="">
</a>
<mat-menu #menu="matMenu" xPosition="before">
<button mat-menu-item>
<mat-icon>settings</mat-icon>
<span>My Settings</span>
</button>
<button mat-menu-item routerLink="/login">
<mat-icon>keyboard_backspace</mat-icon>
<span>Logout</span>
</button>
</mat-menu>
</div>
<a routerLink="/dashboard" class="settings-icon">
<img src="../../assets/setttings.svg" alt="">
</a>
</div>
</div>
login-page.component.html
<div class="container">
<div class="screen">
<div class="screen-content">
<form [formGroup]="loginForm" (ngSubmit)="loginUser()" class="login">
<div class="logo">
<img src="../../../../assets/imbus-logo.svg" alt="imbus-logo" />
</div>
<div class="user-field">
<input #email
formControlName="email"
type="text"
class="login-input"
placeholder="User login"
/>
<br />
<span *ngIf="user && user.invalid && user.touched" style="color: red"
>User name is required.</span
>
</div>
<div class="password-field">
<input
formControlName="password"
type="{{ type }}"
class="login-input"
placeholder="Password"
/>
<mat-icon
(click)="togglePassword($event)"
*ngIf="showPassword"
svgIcon="hr:hide-text"
class="hide-icon"
></mat-icon>
<mat-icon
(click)="togglePassword($event)"
*ngIf="!showPassword"
svgIcon="hr:show-text"
class="show-icon"
></mat-icon>
<span
*ngIf="password && password.invalid && password.touched"
style="color: red"
>
Password is required.</span
>
</div>
<button [disabled]="loginForm.invalid" class="button login-submit">
<span class="button-text" (click)="proceedlogin(name.value)">LogIn</span>
</button>
</form>
<p id="copy-rights-text" class="copy-right">© IMBUS HR DASHBOARD 2023</p>
</div>
</div>
</div>
login-page.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import {Router} from "@angular/router";
import {AuthService} from "../../../core/services/auth.service";
@Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.scss'],
})
export class LoginPageComponent implements OnInit {
public showPassword = false;
public type = 'password';
constructor( private service: AuthService,
private router: Router) {
localStorage.clear();
}
loginForm = new FormGroup({
email: new FormControl('', [Validators.required]),
password: new FormControl('', [
Validators.required,
Validators.minLength(8),
]),
});
loginUser() {
console.warn(this.loginForm.value);
if (this.loginForm.valid) {
console.log('Form Submitted!', this.loginForm.value);
}
}
ngOnInit():void {}
proceedlogin(email:any){
localStorage.setItem("user", email);
this.router.navigate(["/dashboard"])
}
get user() {
return this.loginForm.get('user');
}
get password() {
return this.loginForm.get('password');
}
togglePassword(e: Event) {
e.stopPropagation();
e.preventDefault();
this.showPassword = !this.showPassword;
this.type = this.showPassword ? 'text' : 'password';
}
}
core/service/authservice.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() {}
isLoggedIn(){
return localStorage.getItem("user")!=null;
}
}
I don't understand the logic on how to validate the token.