hermes-web-angular/src/app/shared/services/api/api-authentication.service.ts

67 lines
1.5 KiB
TypeScript
Raw Normal View History

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
2024-10-25 19:09:34 +00:00
import EventService from '../EventService';
@Injectable({
providedIn: 'root'
})
export class ApiAuthenticationService {
private authenticated: boolean;
private user: any;
private lastCheck: Date;
2024-10-25 19:09:34 +00:00
constructor(private http: HttpClient, private events: EventService) {
this.authenticated = false;
this.user = null;
this.lastCheck = new Date();
}
isAuthenticated() {
return this.authenticated;
}
isAdmin() {
return this.isAuthenticated() && this.user.role == 'ADMIN';
}
getImpersonatedId() {
2024-12-28 01:37:44 +00:00
return this.user?.impersonation?.id;
}
getUsername() {
return this.user?.name;
}
update() {
const jwt = localStorage.getItem('jwt');
if (!jwt) {
this.updateAuthenticated(false, null);
return;
}
// /api/auth/validate
this.http.get('/api/auth/validate', {
headers: {
'Authorization': 'Bearer ' + jwt
}
}).subscribe((data: any) => {
this.updateAuthenticated(data?.authenticated, data?.user);
});
}
private updateAuthenticated(authenticated: boolean, user: any) {
2024-10-25 19:09:34 +00:00
const previous = this.authenticated;
this.authenticated = authenticated;
this.user = user;
this.lastCheck = new Date();
2024-10-25 19:09:34 +00:00
if (previous != authenticated) {
if (authenticated) {
this.events.emit('login', null);
} else {
this.events.emit('logoff', null);
}
2024-10-25 19:09:34 +00:00
}
}
}