import { HttpClient } from "@angular/common/http"; import { Injectable, OnDestroy } from "@angular/core"; import { Observable, Subject, catchError, map, of, takeUntil } from "rxjs"; @Injectable({ providedIn: "root", }) export class RulibAuthService implements OnDestroy { private destroy$ = new Subject(); private api_url = "https://api.lib.social"; constructor(private http: HttpClient) {} setToken(token: string): Observable { return this.checkToken(token) .pipe(takeUntil(this.destroy$)) .pipe( map((data) => { if (!data) return false; localStorage.setItem("token", token); return true; }), ); } getToken(): string { return localStorage.getItem("token") ?? ""; } checkToken(token: string): Observable { return this.http .get(this.api_url + "/api/auth/me", { headers: { Authorization: `Bearer ${token}` }, }) .pipe( takeUntil(this.destroy$), map(() => true), catchError(() => of(false)), ); } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); } }