|
| 1 | +import {inject, Injectable} from '@angular/core'; |
| 2 | +import {HttpClient} from "@angular/common/http"; |
| 3 | +import {Observable} from "rxjs"; |
| 4 | +import {OAuth} from "../common/interface/oauth"; |
| 5 | +import {environment} from "../../environments/environment"; |
| 6 | +import {UserRolesResponse} from "../common/interface/user-roles-response"; |
| 7 | +import {FeatureToggleResponse} from "../common/interface/feature-toggle-response"; |
| 8 | + |
| 9 | +@Injectable({ |
| 10 | + providedIn: 'root' |
| 11 | +}) |
| 12 | +export class AuthService { |
| 13 | + private httpClient = inject(HttpClient); |
| 14 | + private oauth: OAuth | null = null; |
| 15 | + |
| 16 | + constructor() { |
| 17 | + this.oauth = { |
| 18 | + AccessToken: localStorage.getItem('auth-AccessToken') ?? '', |
| 19 | + RefreshToken: localStorage.getItem('auth-RefreshToken') ?? '', |
| 20 | + ExpiresUtc: localStorage.getItem('auth-ExpiresUtc') ?? '' |
| 21 | + }; |
| 22 | + |
| 23 | + if (!this.oauth.AccessToken) { |
| 24 | + this.oauth = null; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + setToken(token: OAuth): void { |
| 29 | + console.log('Setting token', token); |
| 30 | + this.oauth = token; |
| 31 | + localStorage.setItem('auth-AccessToken', token.AccessToken); |
| 32 | + localStorage.setItem('auth-RefreshToken', token.RefreshToken); |
| 33 | + localStorage.setItem('auth-ExpiresUtc', token.ExpiresUtc); |
| 34 | + } |
| 35 | + |
| 36 | + getToken(): string | null { |
| 37 | + console.log('Getting token', this.oauth); |
| 38 | + console.log('Getting token', this.oauth?.AccessToken); |
| 39 | + return this.oauth?.AccessToken ?? null; |
| 40 | + } |
| 41 | + |
| 42 | + clearToken(): void { |
| 43 | + console.log('Clearing token'); |
| 44 | + this.oauth = null; |
| 45 | + localStorage.removeItem('auth-AccessToken'); |
| 46 | + localStorage.removeItem('auth-RefreshToken'); |
| 47 | + localStorage.removeItem('auth-ExpiresUtc'); |
| 48 | + } |
| 49 | + |
| 50 | + getOAuth(): OAuth | null { |
| 51 | + return this.oauth; |
| 52 | + } |
| 53 | + |
| 54 | + refreshToken(token: string): Observable<OAuth> { |
| 55 | + return this.httpClient.post<OAuth>(`${environment.apiUrl}/user/token/refresh`, {token: token}); |
| 56 | + } |
| 57 | + |
| 58 | + validateToken(token: string): Observable<boolean> { |
| 59 | + return this.httpClient.post<boolean>(`${environment.apiUrl}/user/token/validate`, {token: token}); |
| 60 | + } |
| 61 | + |
| 62 | + getUserRoles(): Observable<UserRolesResponse> { |
| 63 | + return this.httpClient.get<UserRolesResponse>(`${environment.apiUrl}/user/roles`); |
| 64 | + } |
| 65 | + |
| 66 | + getFeatureToggles(): Observable<FeatureToggleResponse[]> { |
| 67 | + return this.httpClient.get<FeatureToggleResponse[]>(`${environment.apiUrl}/featureToggle`); |
| 68 | + } |
| 69 | +} |
0 commit comments