81 lines
2.8 KiB
JavaScript
81 lines
2.8 KiB
JavaScript
document.addEventListener("DOMContentLoaded", async function () {
|
|
const config = await loadMergedConfig();
|
|
const loginConf = config.apiConfig.login || {};
|
|
|
|
const loginUrl = loginConf.url;
|
|
const reqParams = loginConf.requestParams || [];
|
|
const resParams = loginConf.responseParams || [];
|
|
|
|
const reqUsernameField = reqParams.find(p => p.label.includes("用户名"))?.field || "username";
|
|
const reqPasswordField = reqParams.find(p => p.label.includes("密码"))?.field || "password";
|
|
const resTokenField = resParams.find(p => p.label.includes("Token"))?.field || "token";
|
|
const resUsernameField = resParams.find(p => p.label.includes("用户名"))?.field || "username";
|
|
|
|
const loginBtn = document.getElementById("loginBtn");
|
|
const errorBox = document.getElementById("errorBox");
|
|
|
|
loginBtn.addEventListener("click", doLogin);
|
|
document.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter") {
|
|
doLogin();
|
|
}
|
|
});
|
|
|
|
async function doLogin() {
|
|
const username = document.getElementById("username").value.trim();
|
|
const password = document.getElementById("password").value.trim();
|
|
|
|
errorBox.textContent = "";
|
|
|
|
if (!username || !password) {
|
|
errorBox.textContent = "请输入用户名和密码";
|
|
return;
|
|
}
|
|
|
|
const requestBody = {};
|
|
requestBody[reqUsernameField] = username;
|
|
requestBody[reqPasswordField] = password;
|
|
|
|
loginBtn.disabled = true;
|
|
loginBtn.textContent = "登录中...";
|
|
|
|
try {
|
|
const res = await fetch(loginUrl, {
|
|
method: "POST",
|
|
credentials: "include",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(requestBody)
|
|
});
|
|
|
|
const rawText = await res.text();
|
|
let body = {};
|
|
try {
|
|
body = rawText ? JSON.parse(rawText) : {};
|
|
} catch (e) {
|
|
body = {};
|
|
}
|
|
|
|
const token = body[resTokenField];
|
|
const returnedUser = body[resUsernameField] || username;
|
|
|
|
if (res.status === 200 && token) {
|
|
chrome.storage.local.set({
|
|
token: token,
|
|
username: returnedUser,
|
|
loginAt: Date.now()
|
|
}, () => {
|
|
window.location.href = chrome.runtime.getURL("pages/popup.html");
|
|
});
|
|
return;
|
|
}
|
|
|
|
errorBox.textContent = body.message || body.msg || "登录失败";
|
|
} catch (e) {
|
|
console.error("login error:", e);
|
|
errorBox.textContent = "网络错误,请稍后重试";
|
|
} finally {
|
|
loginBtn.disabled = false;
|
|
loginBtn.textContent = "登录";
|
|
}
|
|
}
|
|
}); |