87 lines
2.8 KiB
TypeScript
87 lines
2.8 KiB
TypeScript
// کلاینتِ APIِ پنل. احرازِ هویت با Basic Auth (همان کاربر/پسوردِ پنل ادمین)
|
|
// که پس از ورود در localStorage نگهداری میشود و در هر درخواست فرستاده میشود.
|
|
|
|
// همان مبدأ (nginx، /admin/api → بکاند). برای توسعهی محلی با
|
|
// NEXT_PUBLIC_API_URL قابلِ override است.
|
|
const BASE =
|
|
process.env.NEXT_PUBLIC_API_URL || "https://hakem.approagency.ir/admin/api";
|
|
|
|
// مبدأِ فایلهای استاتیک (کارت/فرش): همان دامنه بدونِ /admin/api.
|
|
export const ASSET_BASE = BASE.replace(/\/admin\/api\/?$/, "");
|
|
|
|
const AUTH_KEY = "hakem_admin_auth";
|
|
|
|
export function saveAuth(user: string, pass: string) {
|
|
if (typeof window !== "undefined") {
|
|
localStorage.setItem(AUTH_KEY, btoa(`${user}:${pass}`));
|
|
}
|
|
}
|
|
export function clearAuth() {
|
|
if (typeof window !== "undefined") localStorage.removeItem(AUTH_KEY);
|
|
}
|
|
export function getAuth(): string | null {
|
|
if (typeof window === "undefined") return null;
|
|
return localStorage.getItem(AUTH_KEY);
|
|
}
|
|
export function isAuthed(): boolean {
|
|
return !!getAuth();
|
|
}
|
|
|
|
class ApiError extends Error {
|
|
status: number;
|
|
constructor(status: number, msg: string) {
|
|
super(msg);
|
|
this.status = status;
|
|
}
|
|
}
|
|
|
|
async function request<T>(
|
|
method: string,
|
|
path: string,
|
|
body?: unknown,
|
|
): Promise<T> {
|
|
const auth = getAuth();
|
|
const headers: Record<string, string> = { Accept: "application/json" };
|
|
if (auth) headers["Authorization"] = `Basic ${auth}`;
|
|
const opts: RequestInit = { method, headers };
|
|
if (body !== undefined) {
|
|
if (body instanceof FormData) {
|
|
opts.body = body;
|
|
} else {
|
|
headers["Content-Type"] = "application/json";
|
|
opts.body = JSON.stringify(body);
|
|
}
|
|
}
|
|
const res = await fetch(`${BASE}${path}`, opts);
|
|
if (res.status === 401) {
|
|
clearAuth();
|
|
if (typeof window !== "undefined") window.location.href = "/panel/login/";
|
|
throw new ApiError(401, "unauthorized");
|
|
}
|
|
if (!res.ok) {
|
|
const e = await res.json().catch(() => ({}));
|
|
throw new ApiError(res.status, (e as { error?: string }).error || "خطا");
|
|
}
|
|
return res.json() as Promise<T>;
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(p: string) => request<T>("GET", p),
|
|
post: <T>(p: string, body?: unknown) => request<T>("POST", p, body),
|
|
put: <T>(p: string, body?: unknown) => request<T>("PUT", p, body),
|
|
del: <T>(p: string) => request<T>("DELETE", p),
|
|
// ورود: اعتبارسنجی با فراخوانی /me.
|
|
async login(user: string, pass: string) {
|
|
const prev = getAuth();
|
|
saveAuth(user, pass);
|
|
try {
|
|
await request("GET", "/me");
|
|
return true;
|
|
} catch {
|
|
if (prev) localStorage.setItem(AUTH_KEY, prev);
|
|
else clearAuth();
|
|
return false;
|
|
}
|
|
},
|
|
};
|