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 { return new Promise((resolve, reject) => { this.httpClient.get(`${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=/;'; } }