nise/nise-frontend/src/corelib/service/user.service.ts

85 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-02-17 19:54:56 +00:00
import {Injectable} from '@angular/core';
import {HttpBackend, HttpClient} from "@angular/common/http";
import {environment} from "../../environments/environment";
interface UserInfo {
userId: number;
username: string;
}
@Injectable({
providedIn: 'root'
})
export class UserService {
private httpClient: HttpClient;
currentUser: UserInfo | null = null;
loginCallback: () => void = () => {};
logoutCallback: () => void = () => {};
constructor(private httpBackend: HttpBackend) {
this.httpClient = new HttpClient(httpBackend);
this.currentUser = this.loadCurrentUserFromLocalStorage();
this.updateUser()
.catch(reason => console.debug(reason));
}
public doLogout(): void {
this.currentUser = null;
this.clearCurrentUserFromLocalStorage();
this.updateUser().then(
() => this.logoutCallback()
)
}
isUserLoggedIn(): boolean {
return this.currentUser !== null;
}
public updateUser(): Promise<any> {
return new Promise((resolve, reject) => {
this.httpClient.get<UserInfo>(`${environment.apiUrl}/auth`, {withCredentials: true})
.subscribe({
next: (user) => {
this.currentUser = user;
this.saveCurrentUserToLocalStorage(user);
this.loginCallback();
resolve(user);
},
error: (err) => {
if (err.status === 401) {
this.currentUser = null;
this.clearCurrentUserFromLocalStorage();
}
reject(err);
}
});
});
}
public getLoginUrl(): string {
return `${environment.apiUrl}/oauth2/authorization/osu`
}
public getLogoutUrl(): string {
return `${environment.apiUrl}/logout`
}
saveCurrentUserToLocalStorage(user: UserInfo) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
loadCurrentUserFromLocalStorage(): UserInfo {
const savedUser = localStorage.getItem('currentUser');
return savedUser ? JSON.parse(savedUser) : null;
}
clearCurrentUserFromLocalStorage() {
localStorage.clear();
document.cookie = 'SESSION=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}
}