feat(rulib): token check
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user