Files
NwaifuWeb/apps/NwaifuAnime/src/app/services/parsers/rulib/rulib.auth.service.ts

45 lines
1.1 KiB
TypeScript

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<void>();
private api_url = "https://api.lib.social";
constructor(private http: HttpClient) {}
setToken(token: string): Observable<boolean> {
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<boolean> {
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();
}
}