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

72 lines
1.6 KiB
TypeScript

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import EventService from '../EventService';
@Injectable({
providedIn: 'root'
})
export class ApiAuthenticationService {
private authenticated: boolean;
private user: any;
private lastCheck: Date;
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() {
return this.user?.impersonation?.id;
}
getUsername() {
return this.user?.name;
}
logout() {
localStorage.removeItem('jwt');
this.updateAuthenticated(false, null);
}
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) {
const previous = this.authenticated;
this.authenticated = authenticated;
this.user = user;
this.lastCheck = new Date();
if (previous != authenticated) {
if (authenticated) {
this.events.emit('login', null);
} else {
this.events.emit('logoff', null);
}
}
}
}