(function () {
const KEY = 'pouchlab.user.v1';
let user = null;
let pending = null;
let mode = 'email'; // email | password | phone
let countdown = 0;
let countdownTimer = null;
const listeners = [];
try {
user = JSON.parse(localStorage.getItem(KEY) || 'null');
if (user && !user.phone && !user.email) user = null;
} catch (e) {
user = null;
}
function emit() {
listeners.forEach(function (fn) {
try { fn(user); } catch (e) {}
});
document.dispatchEvent(new CustomEvent('pl:auth', { detail: { user: user } }));
}
function notify(msg, kind) {
if (window.PL && PL.ui && PL.ui.message) {
if (kind === 'warn') PL.ui.message.warning(msg);
else PL.ui.message.success(msg);
return;
}
window.alert(msg);
}
function maskPhone(phone) {
const p = String(phone || '');
if (p.length !== 11) return p;
return p.slice(0, 3) + '****' + p.slice(7);
}
function validEmail(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v); }
const STYLE = '';
function ensureModal() {
if (document.getElementById('plAuthModal')) return;
const wrap = document.createElement('div');
wrap.id = 'plAuthModal';
wrap.className = 'pl-auth-mask';
wrap.hidden = true;
wrap.innerHTML = STYLE +
'
' +
'
' +
'
袋研社 POUCHLAB
' +
'
登录 / 注册
' +
'
登录后可保存设计、同步订单进度与下载记录。
' +
'
' +
'' +
'' +
'' +
'
' +
// —— 邮箱验证码 ——
'
' +
'
' +
'
' +
'
' +
'
' +
'' +
'' +
'
' +
'
' +
// —— 邮箱密码 ——
'
' +
'' +
'' +
'' +
'' +
'
' +
// —— legacy 手机号 ——
'
' +
'
' +
'
' +
'
' +
'
' +
'' +
'' +
'
' +
'
' +
'
输入邮箱获取验证码登录;演示环境验证码会直接弹出显示。
' +
'
' +
'
' +
'
登录即表示同意《服务条款》与《隐私政策》
' +
'
';
document.body.appendChild(wrap);
wrap.querySelector('.pl-auth-close').addEventListener('click', close);
wrap.addEventListener('click', function (e) {
if (e.target === wrap) close();
});
wrap.querySelectorAll('.pl-auth-tabs button').forEach(function (b) {
b.addEventListener('click', function () { setMode(b.dataset.mode); });
});
wrap.querySelector('#plAuthSend').addEventListener('click', function () { sendCode('email'); });
wrap.querySelector('#plPhoneSend').addEventListener('click', function () { sendCode('phone'); });
wrap.querySelector('#plAuthSubmit').addEventListener('click', submit);
wrap.querySelector('#plAuthPhone').addEventListener('input', function () {
this.value = this.value.replace(/\D/g, '').slice(0, 11); hideError();
});
[['#plAuthCode', '#plAuthEmail'], ['#plPhoneCode', '#plAuthPhone'], ['#plPwdPass', '#plPwdEmail']]
.forEach(function (pair) {
wrap.querySelector(pair[0]).addEventListener('keydown', function (e) {
if (e.key === 'Enter') { e.preventDefault(); submit(); }
});
wrap.querySelector(pair[1]).addEventListener('input', hideError);
});
}
function setMode(m) {
mode = m;
const modal = document.getElementById('plAuthModal');
modal.querySelectorAll('.pl-auth-tabs button').forEach(function (b) {
b.classList.toggle('on', b.dataset.mode === m);
});
document.getElementById('plSecEmail').hidden = m !== 'email';
document.getElementById('plSecPwd').hidden = m !== 'password';
document.getElementById('plSecPhone').hidden = m !== 'phone';
document.getElementById('plAuthHint').textContent =
m === 'phone' ? '老手机号验证码登录;登录后需绑定邮箱。' :
m === 'password' ? '未设置密码的账号请用邮箱验证码登录。' :
'输入邮箱获取验证码登录;演示环境验证码会直接弹出显示。';
hideError();
}
function showError(msg) {
const el = document.getElementById('plAuthError');
if (!el) return;
el.textContent = msg; el.hidden = false;
}
function hideError() {
const el = document.getElementById('plAuthError');
if (el) el.hidden = true;
}
function open() {
ensureModal();
const modal = document.getElementById('plAuthModal');
const email = document.getElementById('plAuthEmail');
email.value = user && user.email ? user.email : '';
document.getElementById('plAuthCode').value = '';
setMode(user && user.phone && !user.email ? 'phone' : 'email');
modal.hidden = false;
document.body.classList.add('pl-auth-open');
setTimeout(function () { (user && user.email ? document.getElementById('plAuthCode') : email).focus(); }, 30);
}
function close() {
const modal = document.getElementById('plAuthModal');
if (modal) modal.hidden = true;
document.body.classList.remove('pl-auth-open');
pending = null;
}
function fillDemoCode(r, inputSel, msgPrefix) {
if (r && r.demo && r.code) {
notify(msgPrefix + r.code + '(已自动填入)');
const input = document.querySelector(inputSel);
if (input) { input.value = r.code; input.focus(); }
} else {
notify('验证码已发送,请查收邮件/短信');
}
}
function sendCode(m) {
const btn = m === 'phone' ? document.getElementById('plPhoneSend') : document.getElementById('plAuthSend');
if (btn.disabled) return;
if (!window.PL || !PL.api) { notify('离线演示验证码:123456'); return; }
let req, sel;
if (m === 'phone') {
const phone = document.getElementById('plAuthPhone').value.trim();
if (!/^1\d{10}$/.test(phone)) { showError('请输入 11 位手机号'); return; }
req = PL.api.post('/auth/sms/send', { phone: phone }, { timeout: 10000 });
sel = '#plPhoneCode';
} else {
const email = document.getElementById('plAuthEmail').value.trim();
if (!validEmail(email)) { showError('请输入正确的邮箱地址'); return; }
req = PL.api.post('/auth/email/send', { email: email }, { timeout: 15000 });
sel = '#plAuthCode';
}
hideError();
btn.disabled = true; btn.textContent = '发送中…';
req.then(function (r) {
fillDemoCode(r, sel, '演示验证码:');
startCountdown(btn);
}, function (err) {
btn.disabled = false; btn.textContent = '获取验证码';
if (err.network) {
notify('服务器暂不可达,离线演示验证码:123456', 'warn');
startCountdown(btn);
} else {
showError(err.message || '发送失败,请稍后再试');
}
});
}
function startCountdown(btn) {
countdown = 60;
btn.disabled = true;
btn.textContent = countdown + 's 后重发';
clearInterval(countdownTimer);
countdownTimer = setInterval(function () {
countdown -= 1;
if (countdown <= 0) {
clearInterval(countdownTimer);
btn.disabled = false; btn.textContent = '获取验证码';
return;
}
btn.textContent = countdown + 's 后重发';
}, 1000);
}
function persist(u) {
user = u;
try { localStorage.setItem(KEY, JSON.stringify(user)); } catch (e) {}
emit();
}
function applyLogin(u) {
persist({
id: u.id, phone: u.phone || '', email: u.email || '', name: u.name || '',
role: u.role || 'user', hasPassword: !!u.hasPassword,
needsBindEmail: !!u.needsBindEmail, at: Date.now()
});
if (u.needsBindEmail) {
close();
openBind();
return;
}
const cb = pending; pending = null;
close();
notify('登录成功');
if (cb) setTimeout(cb, 60);
}
function submit() {
if (!window.PL || !PL.api) return;
let req;
if (mode === 'password') {
const email = document.getElementById('plPwdEmail').value.trim();
const pass = document.getElementById('plPwdPass').value;
if (!validEmail(email)) { showError('请输入正确的邮箱地址'); return; }
if (!pass) { showError('请输入密码'); return; }
req = PL.api.post('/auth/email/password-login', { email: email, password: pass }, { timeout: 10000 });
} else if (mode === 'phone') {
const phone = document.getElementById('plAuthPhone').value.trim();
const code = document.getElementById('plPhoneCode').value.trim();
if (!/^1\d{10}$/.test(phone)) { showError('请输入 11 位手机号'); return; }
if (!/^\d{6}$/.test(code)) { showError('请输入 6 位验证码'); return; }
req = PL.api.post('/auth/sms/login', { phone: phone, code: code }, { timeout: 10000 })
.catch(function (err) {
if (err.network) { // 保留旧的离线演示登录
applyLogin({ id: 0, phone: phone, name: '用户' + phone.slice(-4), role: 'user', needsBindEmail: false });
notify('离线演示模式登录(数据不会上传)', 'warn');
return new Promise(function () {});
}
throw err;
});
} else {
const email = document.getElementById('plAuthEmail').value.trim();
const code = document.getElementById('plAuthCode').value.trim();
if (!validEmail(email)) { showError('请输入正确的邮箱地址'); return; }
if (!/^\d{6}$/.test(code)) { showError('请输入 6 位验证码'); return; }
req = PL.api.post('/auth/email/login', { email: email, code: code }, { timeout: 10000 });
}
const btn = document.getElementById('plAuthSubmit');
btn.disabled = true; btn.textContent = '登录中…';
req.then(function (r) {
btn.disabled = false; btn.textContent = '登录';
if (!r || !r.token) return;
PL.api.setToken(r.token);
applyLogin(r.user);
}, function (err) {
btn.disabled = false; btn.textContent = '登录';
showError(err.message || '登录失败,请重试');
});
}
// ---------- 强制绑定邮箱 ----------
function ensureBindModal() {
if (document.getElementById('plBindModal')) return;
const wrap = document.createElement('div');
wrap.id = 'plBindModal';
wrap.className = 'pl-auth-mask';
wrap.hidden = true;
wrap.innerHTML =
'' +
'
袋研社 POUCHLAB
' +
'
绑定邮箱
' +
'
为保障订单通知与账号安全,请先绑定邮箱。绑定后方可继续使用。
' +
'
' +
'
' +
'
' +
'
' +
'' +
'' +
'
' +
'
' +
'
' +
'
';
document.body.appendChild(wrap);
wrap.querySelector('#plBindSend').addEventListener('click', bindSendCode);
wrap.querySelector('#plBindSubmit').addEventListener('click', submitBind);
wrap.querySelector('#plBindCode').addEventListener('keydown', function (e) {
if (e.key === 'Enter') { e.preventDefault(); submitBind(); }
});
}
function openBind() {
ensureBindModal();
const m = document.getElementById('plBindModal');
document.getElementById('plBindEmail').value = '';
document.getElementById('plBindCode').value = '';
const err = document.getElementById('plBindError'); err.hidden = true;
m.hidden = false;
document.body.classList.add('pl-auth-open');
setTimeout(function () { document.getElementById('plBindEmail').focus(); }, 30);
}
function closeBind() {
const m = document.getElementById('plBindModal');
if (m) m.hidden = true;
if (!document.getElementById('plAuthModal') || document.getElementById('plAuthModal').hidden) {
document.body.classList.remove('pl-auth-open');
}
}
function bindError(msg) {
const el = document.getElementById('plBindError');
el.textContent = msg; el.hidden = false;
}
function bindSendCode() {
const email = document.getElementById('plBindEmail').value.trim();
if (!validEmail(email)) { bindError('请输入正确的邮箱地址'); return; }
const btn = document.getElementById('plBindSend');
btn.disabled = true; btn.textContent = '发送中…';
PL.api.post('/auth/email/send', { email: email }, { timeout: 15000 }).then(function (r) {
fillDemoCode(r, '#plBindCode', '演示验证码:');
startCountdown(btn);
}, function (err) {
btn.disabled = false; btn.textContent = '获取验证码';
bindError(err.message || '发送失败,请稍后再试');
});
}
function submitBind() {
const email = document.getElementById('plBindEmail').value.trim();
const code = document.getElementById('plBindCode').value.trim();
if (!validEmail(email)) { bindError('请输入正确的邮箱地址'); return; }
if (!/^\d{6}$/.test(code)) { bindError('请输入 6 位验证码'); return; }
const btn = document.getElementById('plBindSubmit');
btn.disabled = true; btn.textContent = '绑定中…';
PL.api.post('/auth/bind-email', { email: email, code: code }, { timeout: 10000 }).then(function (r) {
btn.disabled = false; btn.textContent = '确认绑定';
user.email = r.user.email; user.needsBindEmail = false; user.name = r.user.name || user.name;
persist(user);
closeBind();
notify('邮箱已绑定');
if (PL.api.flushBind) PL.api.flushBind();
}, function (err) {
btn.disabled = false; btn.textContent = '确认绑定';
bindError(err.message || '绑定失败,请重试');
});
}
document.addEventListener('pl:bind-email-required', function () {
if (user) openBind();
});
// ---------- 账户设置 ----------
function ensureAccountModal() {
if (document.getElementById('plAccModal')) return;
const wrap = document.createElement('div');
wrap.id = 'plAccModal';
wrap.className = 'pl-auth-mask';
wrap.hidden = true;
wrap.innerHTML = STYLE +
'' +
'
' +
'
袋研社 POUCHLAB
' +
'
账户设置
' +
'
' +
'
' +
'' +
'' +
'' +
'' +
'' +
'' +
'
' +
'
' +
'
' +
'
' +
'
';
document.body.appendChild(wrap);
wrap.querySelector('.pl-auth-close').addEventListener('click', function () { wrap.hidden = true; });
wrap.querySelector('#plAccSubmit').addEventListener('click', submitAccount);
wrap.querySelector('#plAccBind').addEventListener('click', function () {
wrap.hidden = true;
openBind();
});
}
function openAccount() {
ensureAccountModal();
if (!user) return;
const info = document.getElementById('plAccInfo');
info.textContent = user.email
? '邮箱:' + user.email + ' · ' + (user.hasPassword ? '已设置密码' : '未设置密码')
: '尚未绑定邮箱(' + (user.phone ? '手机号 ' + maskPhone(user.phone) : '演示账号') + ')';
document.getElementById('plAccBind').hidden = !!user.email;
document.getElementById('plAccPwdSec').hidden = !!user.needBindBlock || !user.email && user.id === 0;
document.getElementById('plAccSubmit').hidden = document.getElementById('plAccPwdSec').hidden;
document.getElementById('plAccOldLabel').textContent = user.hasPassword ? '旧密码' : '旧密码(首次设置无需填写)';
document.getElementById('plAccOld').hidden = !user.hasPassword;
document.getElementById('plAccError').hidden = true;
document.getElementById('plAccModal').hidden = false;
}
function accError(msg) {
const el = document.getElementById('plAccError');
el.textContent = msg; el.hidden = false;
}
function submitAccount() {
const np = document.getElementById('plAccNew').value;
const np2 = document.getElementById('plAccNew2').value;
if (np !== np2) { accError('两次输入的密码不一致'); return; }
if (np.length < 8 || !/[A-Za-z]/.test(np) || !/\d/.test(np)) {
accError('密码需至少 8 位且包含字母和数字'); return;
}
const btn = document.getElementById('plAccSubmit');
btn.disabled = true;
PL.api.post('/auth/set-password',
{ oldPassword: user.hasPassword ? document.getElementById('plAccOld').value : '', newPassword: np },
{ timeout: 10000 }).then(function () {
btn.disabled = false;
user.hasPassword = true;
persist(user);
document.getElementById('plAccModal').hidden = true;
notify('密码已保存');
}, function (err) {
btn.disabled = false;
accError(err.message || '保存失败,请重试');
});
}
// ---------- 入口渲染 ----------
function displayName() {
if (!user) return '登录';
return user.name || user.email || maskPhone(user.phone) || '登录';
}
function logout() {
user = null;
pending = null;
try { localStorage.removeItem(KEY); } catch (e) {}
if (window.PL && PL.api) PL.api.setToken('');
emit();
notify('已退出登录');
}
function requireAuth(cb) {
if (user) {
if (user.needsBindEmail) openBind();
if (cb) cb();
return true;
}
pending = cb || null;
open();
return false;
}
function renderEntry(entry) {
const btn = entry.querySelector('.pl-auth-btn');
const menu = entry.querySelector('.pl-auth-menu');
if (!btn) return;
btn.textContent = displayName();
btn.classList.toggle('on', !!user);
if (menu) {
const name = menu.querySelector('.pl-auth-name');
if (name) name.textContent = user ? '已登录 · ' + (user.email || user.name) : '';
}
}
function buildEntry(entry) {
entry.innerHTML =
'' +
'';
const btn = entry.querySelector('.pl-auth-btn');
const menu = entry.querySelector('.pl-auth-menu');
btn.addEventListener('click', function (e) {
e.stopPropagation();
if (!user) { open(); return; }
menu.hidden = !menu.hidden;
});
entry.querySelector('.pl-auth-account').addEventListener('click', function (e) {
e.stopPropagation();
menu.hidden = true;
openAccount();
});
entry.querySelector('.pl-auth-logout').addEventListener('click', function (e) {
e.stopPropagation();
menu.hidden = true;
logout();
});
document.addEventListener('click', function () { menu.hidden = true; });
renderEntry(entry);
}
function mount() {
const trigger = document.getElementById('loginTrigger');
if (trigger) {
if (trigger.tagName === 'A') {
trigger.addEventListener('click', function (e) { e.preventDefault(); });
}
trigger.addEventListener('click', function () {
if (user) { logout(); } else { open(); }
});
const sync = function () {
trigger.textContent = displayName();
trigger.classList.toggle('on', !!user);
trigger.title = user ? '点击退出登录' : '登录';
};
listeners.push(sync);
sync();
}
const actions = document.querySelector('.studio-actions');
if (actions && !actions.querySelector('.pl-auth-entry')) {
const entry = document.createElement('span');
entry.className = 'pl-auth-entry';
actions.insertBefore(entry, actions.firstChild);
buildEntry(entry);
listeners.push(function () { renderEntry(entry); });
}
emit();
}
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
const modal = document.getElementById('plAuthModal');
if (modal && !modal.hidden) close();
// 强制绑定框不响应 Esc
}
});
window.PL = window.PL || {};
window.PL.auth = {
user: function () { return user; },
open: open,
logout: logout,
require: requireAuth,
openBind: openBind,
openAccount: openAccount,
onChange: function (fn) {
listeners.push(fn);
return function () { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1); };
}
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', mount);
} else {
mount();
}
})();