Files
hobbypj-contents/ui/auth.js
T
Bkk1234 cd5cb5dd08 feat(admin): gate the backoffice behind a name and password
- ui/auth.js: name/password check, session kept in sessionStorage (new tab asks again),
  5 wrong attempts lock the form for 30s
- admin view renders a login card until authenticated; adds an explicit logout button
- SW precache includes auth.js, version bumped to 2026.11.19.3 (meta + sw.js in sync)
- docs: AGENTS.md notes the gate is client-side; real protection is the server ADMIN_TOKEN
2026-11-19 11:28:20 +07:00

60 lines
2.2 KiB
JavaScript

/* auth.js — ประตูหน้าหลังบ้าน (ชื่อ + รหัส)
หมายเหตุความปลอดภัย: นี่คือ "ด่านหน้า" ฝั่งเบราว์เซอร์ ทำให้คนเดินผ่านหน้าจอ
ไม่เข้าไปแก้ข้อความได้ง่าย ๆ เท่านั้น ไม่ใช่ระบบยืนยันตัวตนจริง
การป้องกันจริงอยู่ที่ ADMIN_TOKEN ของ server/publish.mjs (ฝั่งเซิร์ฟเวอร์)
ห้ามใช้รหัสเดียวกับระบบอื่น และอย่าเปิดหลังบ้านให้เครื่องอื่นโดยไม่ตั้ง ADMIN_TOKEN */
const ADMIN_NAME = "admin";
const ADMIN_PASSWORD = "admin007";
const SESSION_KEY = "hobbypj.admin.session.v1";
const MAX_ATTEMPTS = 5;
const LOCK_MS = 30_000;
let failures = 0;
let lockedUntil = 0;
export function isAuthed() {
try {
return sessionStorage.getItem(SESSION_KEY) === "1";
} catch {
return false;
}
}
/** @returns {{ok:boolean, locked?:boolean, retryIn?:number, remaining?:number}} */
export function login(name, password) {
const now = Date.now();
if (now < lockedUntil) {
return { ok: false, locked: true, retryIn: Math.ceil((lockedUntil - now) / 1000) };
}
const ok = String(name ?? "").trim() === ADMIN_NAME && String(password ?? "") === ADMIN_PASSWORD;
if (!ok) {
failures += 1;
if (failures >= MAX_ATTEMPTS) {
failures = 0;
lockedUntil = now + LOCK_MS;
return { ok: false, locked: true, retryIn: Math.round(LOCK_MS / 1000) };
}
return { ok: false, remaining: MAX_ATTEMPTS - failures };
}
failures = 0;
lockedUntil = 0;
try {
sessionStorage.setItem(SESSION_KEY, "1");
} catch {
/* โหมดส่วนตัวที่ปิด storage → ให้เข้าได้เฉพาะรอบนี้ */
}
return { ok: true };
}
export function logout() {
try {
sessionStorage.removeItem(SESSION_KEY);
} catch {
/* ignore */
}
}