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 lastCheck: Date; constructor(private http: HttpClient, private events: EventService) { this.authenticated = false; this.lastCheck = new Date(); } isAuthenticated() { return this.authenticated; } update() { const jwt = localStorage.getItem('jwt'); if (!jwt) { this.updateAuthenticated(false); return; } // /api/auth/jwt this.http.get('/api/auth/jwt', { headers: { 'Authorization': 'Bearer ' + jwt } }).subscribe((data: any) => { console.log('jwt validation', data); this.updateAuthenticated(data?.authenticated); }); } private updateAuthenticated(value: boolean) { const previous = this.authenticated; this.authenticated = value; this.lastCheck = new Date(); if (previous != value) { if (value) { this.events.emit('login', null); } else { this.events.emit('logoff', null); } } } }