Skip to content

Commit 6172260

Browse files
authored
Create auth.js
1 parent 1ab3a71 commit 6172260

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

‎app/views/js/auth.js‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Auth + top-level view switching (login screen ⇄ app ⇄ profile) and
2+
// the theme toggle.
3+
import { $, api, errMsg, state } from "./core.js";
4+
import { loadMe } from "./account.js";
5+
import { loadConversations } from "./conversations.js";
6+
7+
export function showAuth(msg) {
8+
$("app").style.display = "none";
9+
$("auth").style.display = "flex";
10+
$("profile").style.display = "none";
11+
$("authMsg").textContent = msg || "";
12+
sessionStorage.removeItem("token");
13+
api.token = "";
14+
state.accountProfile = null; // don't leak one user's credits to the next
15+
}
16+
17+
export function showApp() {
18+
$("auth").style.display = "none";
19+
$("app").style.display = "block";
20+
$("profile").style.display = "none";
21+
loadConversations();
22+
loadMe();
23+
}
24+
25+
// A 401 from any api.req bounces back to the login screen.
26+
api.onUnauthorized = () => showAuth("登录已过期,请重新登录");
27+
28+
$("loginBtn").onclick = async () => {
29+
const email = $("email").value.trim(),
30+
password = $("password").value;
31+
let res = await fetch("/auth/login", {
32+
method: "POST",
33+
headers: { "Content-Type": "application/json" },
34+
body: JSON.stringify({ email, password }),
35+
});
36+
if (res.status === 401 || res.status === 403) {
37+
res = await fetch("/auth/register", {
38+
method: "POST",
39+
headers: { "Content-Type": "application/json" },
40+
body: JSON.stringify({ email, password }),
41+
});
42+
}
43+
if (!res.ok) {
44+
$("authMsg").textContent = "登录失败: " + (await errMsg(res));
45+
return;
46+
}
47+
const tokens = await res.json();
48+
api.token = tokens.access_token;
49+
sessionStorage.setItem("token", api.token);
50+
showApp();
51+
};
52+
$("password").addEventListener("keydown", (e) => {
53+
if (e.key === "Enter") $("loginBtn").click();
54+
});
55+
56+
$("themeBtn").onclick = () => {
57+
const dark = document.documentElement.dataset.theme === "dark";
58+
document.documentElement.dataset.theme = dark ? "" : "dark";
59+
$("themeBtn").textContent = dark ? "🌙 深色" : "☀️ 浅色";
60+
};

0 commit comments

Comments
 (0)