feat(rulib): token check

This commit is contained in:
2024-07-10 19:22:53 +03:00
parent 82a0ba102d
commit d1e32a94ca
3 changed files with 53 additions and 4 deletions

View File

@@ -1,15 +1,41 @@
import { Injectable } from "@angular/core";
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 {
export class RulibAuthService implements OnDestroy {
private destroy$ = new Subject<void>();
private api_url = "https://api.lib.social";
constructor(private http: HttpClient) {}
setToken(token: string) {
localStorage.setItem("token", token);
this.checkToken(token)
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
if (!data) return;
localStorage.setItem("token", token);
});
}
getToken(): string {
return localStorage.getItem("token") ?? "";
}
//TODO: Проверка токена
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();
}
}