wg_index/frontend/js/auth.js
2025-12-27 05:02:10 +03:00

65 lines
1.7 KiB
JavaScript
Executable file

import { CONFIG } from "./config.js";
import { saveSession, loadSession, clearSession } from "./storage.js";
import { apiFetch } from "./api.js";
function deviceLabel() {
const ua = navigator.userAgent || "browser";
return ua.slice(0, 120);
}
export function isLoggedIn() {
return !!loadSession();
}
export function requireAuthOrRedirect() {
if (!isLoggedIn()) {
location.replace("./login.html");
return false;
}
return true;
}
export async function login(email, password, remember) {
const headers = {
email: String(email),
password: String(password),
remember: remember ? "1" : "0"
};
const data = await apiFetch(CONFIG.ENDPOINTS.login, { method: "GET", headers, auth: false });
if (!data?.short_token || !data?.live_token || !data?.user_id) {
throw new Error("BAD_LOGIN_RESPONSE");
}
saveSession({
short_token: data.short_token,
live_token: data.live_token,
user_id: data.user_id,
user_name: data.user_name || ""
});
return data;
}
export async function logout() {
const s = loadSession();
try {
if (s?.user_id && s?.live_token) {
// /kill_session/ удаляет live_token :contentReference[oaicite:5]{index=5}
await apiFetch(CONFIG.ENDPOINTS.logout, {
method: "GET",
headers: {
user_id: String(s.user_id),
live_token: String(s.live_token)
},
auth: false
});
}
} catch {
// игнор: локально всё равно очищаем
} finally {
clearSession();
}
}