🔒️ Add expiration check of token
continuous-integration/drone/push Build is passing Details

master
Alix JEUDI--LEMOINE 1 week ago
parent dc9315804c
commit 5b2ee84939

@ -1,19 +1,32 @@
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class LocalStorageService {
private readonly AUTH_TOKEN_KEY = 'auth_token';
private readonly IS_ADMIN_KEY = 'isAdmin';
private readonly USERNAME_KEY = 'username';
private readonly IS_ADMIN_KEY = 'is_admin';
constructor() {}
constructor(private router: Router) {}
setToken(token: string): void {
localStorage.setItem(this.AUTH_TOKEN_KEY, token);
}
getToken(): string | null {
// Check if token is expired
const token = localStorage.getItem(this.AUTH_TOKEN_KEY);
if (token) {
const payload = JSON.parse(atob(token.split('.')[1]));
const expirationDate = new Date(payload.exp * 1000);
if (expirationDate < new Date()) {
this.removeToken(); // Remove expired token
this.router.navigate(['/login']);
return null;
}
}
return localStorage.getItem(this.AUTH_TOKEN_KEY);
}
@ -21,6 +34,18 @@ export class LocalStorageService {
localStorage.removeItem(this.AUTH_TOKEN_KEY);
}
setUsername(username: string): void {
localStorage.setItem(this.USERNAME_KEY, username);
}
getUsername(): string | null{
return localStorage.getItem(this.USERNAME_KEY);
}
removeUsername(): void {
localStorage.removeItem(this.USERNAME_KEY);
}
setIsAdmin(isAdmin: boolean): void {
localStorage.setItem(this.IS_ADMIN_KEY, isAdmin.toString());
}

Loading…
Cancel
Save