#Authentication and JWT decode token.
5 messages · Page 1 of 1 (latest)
---- LOGINDTO.TS ---
export interface LoginDTO {
username: string;
password: string;
}
--- AUTH.SERVICE.TS ----
private isAuthenticated = false;
public utente$: Subject<LoginDTO> = new Subject<LoginDTO>();
constructor(private http: HttpClient) {}
isLoggedIn(): boolean {
return this.isAuthenticated;
}
setAuthenticated(isAuthenticated: boolean) {
this.isAuthenticated = isAuthenticated;
}
public login(login: LoginDTO): Observable<AuthResponseDTO> {
return this.http.post<AuthResponseDTO>(`/api/auth/v1/login`, login).pipe(
map((response: AuthResponseDTO) => {
// Check if the accessToken exists in the response
if (response && response.accessToken) {
this.isAuthenticated = true;
// Save the access token in local storage
localStorage.setItem('accessToken', response.accessToken);
}
return response;
})
);
}
---- TOKEN.SERVICE.TS ----
constructor(private authService: AuthService, private http: HttpClient) {}
checkAccessTokenValidity(): Observable<boolean> {
const accessToken = localStorage.getItem('accessToken');
if (!accessToken) {
return of(false); // No access token, user needs to log in
}
const expirationDate = this.getAccessTokenExpirationDate(accessToken);
if (!expirationDate || expirationDate <= new Date()) {
// Access token is expired or missing, attempt to refresh it
return this.refreshAccessToken();
}
return of(true); // Access token is still valid
}
private getAccessTokenExpirationDate(token: string): Date | null {
const tokenData = JSON.parse(atob(token.split('.')[1]));
if (tokenData && tokenData.exp) {
return new Date(tokenData.exp * 1000);
}
return null;
}
private refreshAccessToken(): Observable<boolean> {
const refreshToken = localStorage.getItem('refreshToken');
if (!refreshToken) {
return of(false); // No refresh token, user needs to log in
}
// Send a request to the server to refresh the access token
return this.http.post('/api/auth/v1/refresh', { refreshToken }).pipe(
map((response: AuthResponseDTO) => {
if (response && response.accessToken) {
localStorage.setItem('accessToken', response.accessToken);
return true; // Access token refreshed successfully
}
return false; // Refresh failed, user needs to log in
})
);
}
}
---- RISORSE.SERVICE.TS ----
// GET Risorse
getRisorse(): Observable<RisorsaDTO[]> {
return this.http.get<{ content: RisorsaDTO[] }>('/api/v1/risorsa').pipe(
map((response) => response.content),
catchError((error) => {
console.error('Error fetching risorse:', error);
throw error;
})
);
}