64 lines
1.6 KiB
TypeScript
64 lines
1.6 KiB
TypeScript
import { AuthStatusRequest, AuthStatusResponse } from "../items";
|
|
|
|
export const apiFetch = async (
|
|
url: string,
|
|
options: RequestInit = {}
|
|
): Promise<Response> => {
|
|
const token = localStorage.getItem("token");
|
|
const headers = new Headers(options.headers);
|
|
|
|
if (token) {
|
|
headers.set("Authorization", `Bearer ${token}`);
|
|
}
|
|
|
|
const config = {
|
|
...options,
|
|
headers,
|
|
};
|
|
|
|
const response = await fetch(url, config);
|
|
|
|
if (!response.ok) {
|
|
if (response.status == 401) {
|
|
localStorage.removeItem("token");
|
|
localStorage.removeItem("isAdmin");
|
|
window.location.href = "/";
|
|
}
|
|
throw new Error(`Request failed with status ${response.status}`);
|
|
}
|
|
|
|
return response;
|
|
};
|
|
|
|
export const get_auth_status = async (): Promise<AuthStatusResponse | null> => {
|
|
const token = localStorage.getItem("token") as string;
|
|
const req = AuthStatusRequest.create({ token });
|
|
const req_buffer = AuthStatusRequest.encode(req).finish();
|
|
const response = await apiFetch("/auth/get_auth_status", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/octet-stream",
|
|
},
|
|
body: req_buffer,
|
|
});
|
|
const buffer = await response.arrayBuffer();
|
|
try {
|
|
const response = AuthStatusResponse.decode(new Uint8Array(buffer));
|
|
localStorage.setItem("isAdmin", String(response.isAdmin));
|
|
return response;
|
|
} catch (e) {
|
|
console.error("Failed to decode auth status:", e);
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export const get_is_admin = (): boolean => {
|
|
return localStorage.getItem("isAdmin") === "true";
|
|
};
|
|
|
|
export const refresh_state = async (): Promise<void> => {
|
|
await apiFetch("/api/refresh", {
|
|
method: "POST",
|
|
});
|
|
};
|