implement token exp

This commit is contained in:
2024-07-09 14:37:00 +07:00
parent d8dc510742
commit f86f727ac7
29 changed files with 152 additions and 25 deletions

View File

@@ -1,21 +1,40 @@
import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";
import { jwtDecode } from "jwt-decode";
import { Router } from "@angular/router";
import { AuthService } from "src/app/_services/auth.service";
const BASE_URL = 'https://kapi.absys.ninja/hemat';
const BASE_URL = "https://kapi.absys.ninja/hemat";
interface CustomJwtPayload {
exp: number;
scope: string;
iat: number;
preferred_username: string;
name: string;
email: string;
family_name: string;
given_name: string;
sub: string;
}
@Injectable({
providedIn: "root",
})
export class LoginService {
constructor(private http: HttpClient) {}
private readonly tokenKey = "currentUser";
constructor(
private http: HttpClient,
private router: Router,
public logoutService: AuthService
) {}
updatePassword(data: any): Observable<any> {
const endpoint = `/users`;
const url = `${BASE_URL}${endpoint}/reset-password`;
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'x-api-key': 'j2yaYvPSQcsEEmHh3NEobfiXyyXmmnHT'
"Content-Type": "application/json",
"x-api-key": "j2yaYvPSQcsEEmHh3NEobfiXyyXmmnHT",
});
return this.http.put<any>(url, data, { headers });
}
@@ -51,4 +70,33 @@ export class LoginService {
return this.http.post(`${url}`, body, { headers });
}
isTokenExpired(): boolean {
const tokenData = localStorage.getItem(this.tokenKey);
if (tokenData) {
const tokenInfo = JSON.parse(tokenData);
const decodedToken = jwtDecode<CustomJwtPayload>(tokenInfo.refresh_token);
const expiryDate = decodedToken.exp * 1000;
const now = new Date().getTime();
return now > expiryDate;
}
return true;
}
checkTokenAndRedirect(): void {
if (this.isTokenExpired()) {
// Token sudah kedaluwarsa, arahkan ke halaman login
// console.log("Token expired, redirecting to login page...");
this.logoutService.doLogout().then(
(res) => {
this.router.navigate(["/login"]);
},
(err) => {
console.log(err);
}
);
this.router.navigate(["/login"]);
} else {
console.log("Token is valid, continuing...");
}
}
}