[accelerator] refresh auth state when logging out

This commit is contained in:
nymkappa
2024-07-01 16:21:47 +09:00
parent 2d12d2e5ef
commit 5b93c8e875
4 changed files with 95 additions and 8 deletions

View File

@@ -0,0 +1,71 @@
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { map, Observable, ReplaySubject, switchMap, tap } from 'rxjs';
import { ServicesApiServices } from './services-api.service';
export interface IAuth {
token: string;
user: {
userId: number;
username: string;
}
}
@Injectable({
providedIn: 'root'
})
export class AuthServiceMempool {
private auth$: ReplaySubject<IAuth | null> = new ReplaySubject(1);
constructor(
private servicesApiService: ServicesApiServices,
private router: Router,
) {
const localStorageAuth = localStorage.getItem('auth');
if (!localStorageAuth || localStorageAuth.length === 0) {
this.setAuth(null);
} else {
try {
this.setAuth(JSON.parse(localStorageAuth));
} catch (e) {
console.error(`Unable to parse 'auth' from localStorage`, e);
localStorage.removeItem('auth');
this.setAuth(null);
}
}
}
refreshAuth$(): Observable<IAuth | null> {
return this.servicesApiService.getJWT$()
.pipe(
tap((user) => {
this.setAuth(user);
}),
map((user) => {
return user;
})
);
}
logout() {
this.setAuth(null);
}
setAuth(auth: any) {
if (!auth) {
localStorage.removeItem('auth');
} else {
localStorage.setItem('auth', JSON.stringify(auth));
}
this.auth$.next(auth);
}
getAuth$(): Observable<IAuth | null> {
if (!localStorage.getItem('auth')) {
return this.refreshAuth$().pipe(
switchMap(() => this.auth$.asObservable())
);
}
return this.auth$.asObservable();
}
}

View File

@@ -120,6 +120,10 @@ export class ServicesApiServices {
return this.httpClient.post(`${SERVICES_API_PREFIX}/auth/logout`, {});
}
getJWT$() {
return this.httpClient.get<any>(`${SERVICES_API_PREFIX}/auth/getJWT`);
}
getServicesBackendInfo$(): Observable<IBackendInfo> {
return this.httpClient.get<IBackendInfo>(`${SERVICES_API_PREFIX}/version`);
}