import {Inject, Injectable, PLATFORM_ID} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs'; import {environment} from "../../environments/environment"; import {isPlatformBrowser} from "@angular/common"; import {jwtDecode, JwtPayload} from "jwt-decode"; @Injectable({ providedIn: 'root' }) export class AuthService { private readonly authUrl: string constructor(private http: HttpClient, @Inject(PLATFORM_ID) private platformId: Object) { this.authUrl = `${environment.backendUrl}/api/auth`; } private get isBrowser(): boolean { return isPlatformBrowser(this.platformId); } isLoggedIn(): boolean { if (!this.isBrowser) return false; return localStorage.getItem("app.token") != null; } login(username: string, password: string): Observable { if (!this.isBrowser) { throw new Error('Login can only be performed in browser'); } const credentials = btoa(`${username}:${password}`); const httpOptions = { headers: { 'Authorization': `Basic ${credentials}`, 'Content-Type': 'application/json' }, responseType: 'text' as 'text', }; return this.http.post(this.authUrl, null, httpOptions); } logout() { if (!this.isBrowser) return; localStorage.removeItem("app.token"); localStorage.removeItem("app.roles"); } isUserInRole(roleFromRoute: string) { if (!this.isBrowser) return false; const roles = localStorage.getItem("app.roles"); if (roles!.includes(",")) { if (roles === roleFromRoute) { return true; } } else { const roleArray = roles!.split(","); for (let role of roleArray) { if (role === roleFromRoute) { return true; } } } return false; } getUsername(): string | null { if (!this.isBrowser) return null; const token = localStorage.getItem("app.token"); if (!token) return null; try { const decodedToken = jwtDecode(token); return decodedToken.sub || null; // 'sub' is the standard JWT claim for subject/username } catch (error) { return null; } } }