73 lines
2.8 KiB
JavaScript
73 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";
|
|
|
|
// 自动填充 LLM 密码(与登录无关,只是附带存储)
|
|
chrome.storage.local.get(["llmPassword"], function (res) {
|
|
if (res.llmPassword) {
|
|
document.getElementById("llmPassword").value = res.llmPassword;
|
|
}
|
|
});
|
|
|
|
document.getElementById("loginBtn").addEventListener("click", doLogin);
|
|
document.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter") doLogin();
|
|
});
|
|
|
|
function doLogin() {
|
|
const username = document.getElementById("username").value.trim();
|
|
const password = document.getElementById("password").value.trim();
|
|
const llmPassword = document.getElementById("llmPassword").value;
|
|
const errorBox = document.getElementById("errorBox");
|
|
errorBox.textContent = "";
|
|
|
|
if (!username || !password) {
|
|
errorBox.textContent = "请输入用户名和密码";
|
|
return;
|
|
}
|
|
|
|
chrome.storage.local.set({ llmPassword });
|
|
|
|
const requestBody = {};
|
|
requestBody[reqUsernameField] = username;
|
|
requestBody[reqPasswordField] = password;
|
|
|
|
fetch(loginUrl, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(requestBody)
|
|
})
|
|
.then(res => res.json().then(data => ({ status: res.status, body: data })))
|
|
.then(({ status, body }) => {
|
|
const token = body[resTokenField];
|
|
const returnedUser = body[resUsernameField] || username;
|
|
|
|
if (status === 200 && token) {
|
|
chrome.storage.local.set({
|
|
token: token,
|
|
username: returnedUser,
|
|
loginAt: Date.now()
|
|
}, () => {
|
|
window.location.href = chrome.runtime.getURL("pages/popup.html");
|
|
});
|
|
} else {
|
|
errorBox.textContent = body.message || "登录失败";
|
|
}
|
|
})
|
|
.catch(() => {
|
|
errorBox.textContent = "网络错误,请稍后重试";
|
|
});
|
|
}
|
|
});
|