auth.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. (function () {
  2. const KEY = 'pouchlab.user.v1';
  3. let user = null;
  4. let pending = null;
  5. let countdown = 0;
  6. let countdownTimer = null;
  7. const listeners = [];
  8. try {
  9. user = JSON.parse(localStorage.getItem(KEY) || 'null');
  10. if (user && !user.phone) user = null;
  11. } catch (e) {
  12. user = null;
  13. }
  14. function emit() {
  15. listeners.forEach(function (fn) {
  16. try { fn(user); } catch (e) {}
  17. });
  18. document.dispatchEvent(new CustomEvent('pl:auth', { detail: { user: user } }));
  19. }
  20. function notify(msg, kind) {
  21. if (window.PL && PL.ui && PL.ui.message) {
  22. if (kind === 'warn') PL.ui.message.warning(msg);
  23. else PL.ui.message.success(msg);
  24. return;
  25. }
  26. window.alert(msg);
  27. }
  28. function maskPhone(phone) {
  29. const p = String(phone || '');
  30. if (p.length !== 11) return p;
  31. return p.slice(0, 3) + '****' + p.slice(7);
  32. }
  33. function ensureModal() {
  34. if (document.getElementById('plAuthModal')) return;
  35. const wrap = document.createElement('div');
  36. wrap.id = 'plAuthModal';
  37. wrap.className = 'pl-auth-mask';
  38. wrap.hidden = true;
  39. wrap.innerHTML =
  40. '<div class="pl-auth-card" role="dialog" aria-modal="true" aria-labelledby="plAuthTitle">' +
  41. '<button class="pl-auth-close" type="button" aria-label="关闭">✕</button>' +
  42. '<div class="pl-auth-brand">袋研社 <em>POUCHLAB</em></div>' +
  43. '<h2 id="plAuthTitle">登录 / 注册</h2>' +
  44. '<p class="pl-auth-sub">登录后可保存设计、同步订单进度与下载记录。</p>' +
  45. '<label class="pl-auth-label" for="plAuthPhone">手机号</label>' +
  46. '<input id="plAuthPhone" class="pl-auth-input" type="tel" inputmode="numeric" maxlength="11" autocomplete="tel" placeholder="请输入 11 位手机号">' +
  47. '<label class="pl-auth-label" for="plAuthCode">验证码</label>' +
  48. '<div class="pl-auth-code-row">' +
  49. '<input id="plAuthCode" class="pl-auth-input" type="text" inputmode="numeric" maxlength="6" autocomplete="one-time-code" placeholder="6 位验证码">' +
  50. '<button id="plAuthSend" class="pl-auth-send" type="button">获取验证码</button>' +
  51. '</div>' +
  52. '<p class="pl-auth-hint" id="plAuthHint">输入手机号获取验证码登录;演示环境验证码会直接弹出显示。</p>' +
  53. '<p class="pl-auth-error" id="plAuthError" hidden></p>' +
  54. '<button id="plAuthSubmit" class="pl-auth-submit" type="button">登录</button>' +
  55. '<p class="pl-auth-terms">登录即表示同意《服务条款》与《隐私政策》</p>' +
  56. '</div>';
  57. document.body.appendChild(wrap);
  58. wrap.querySelector('.pl-auth-close').addEventListener('click', close);
  59. wrap.addEventListener('click', function (e) {
  60. if (e.target === wrap) close();
  61. });
  62. wrap.querySelector('#plAuthSend').addEventListener('click', sendCode);
  63. wrap.querySelector('#plAuthSubmit').addEventListener('click', submit);
  64. wrap.querySelector('#plAuthPhone').addEventListener('input', function () {
  65. this.value = this.value.replace(/\D/g, '').slice(0, 11);
  66. hideError();
  67. });
  68. wrap.querySelector('#plAuthCode').addEventListener('input', function () {
  69. this.value = this.value.replace(/\D/g, '').slice(0, 6);
  70. hideError();
  71. });
  72. wrap.querySelector('#plAuthCode').addEventListener('keydown', function (e) {
  73. if (e.key === 'Enter') { e.preventDefault(); submit(); }
  74. });
  75. wrap.querySelector('#plAuthPhone').addEventListener('keydown', function (e) {
  76. if (e.key === 'Enter') { e.preventDefault(); wrap.querySelector('#plAuthCode').focus(); }
  77. });
  78. }
  79. function showError(msg) {
  80. const el = document.getElementById('plAuthError');
  81. if (!el) return;
  82. el.textContent = msg;
  83. el.hidden = false;
  84. }
  85. function hideError() {
  86. const el = document.getElementById('plAuthError');
  87. if (el) el.hidden = true;
  88. }
  89. function open() {
  90. ensureModal();
  91. const modal = document.getElementById('plAuthModal');
  92. const phone = document.getElementById('plAuthPhone');
  93. phone.value = user ? user.phone : '';
  94. document.getElementById('plAuthCode').value = '';
  95. hideError();
  96. modal.hidden = false;
  97. document.body.classList.add('pl-auth-open');
  98. setTimeout(function () { (user ? document.getElementById('plAuthCode') : phone).focus(); }, 30);
  99. }
  100. function close() {
  101. const modal = document.getElementById('plAuthModal');
  102. if (modal) modal.hidden = true;
  103. document.body.classList.remove('pl-auth-open');
  104. pending = null;
  105. }
  106. function sendCode() {
  107. const phone = document.getElementById('plAuthPhone').value.trim();
  108. if (!/^1\d{10}$/.test(phone)) {
  109. showError('请输入 11 位手机号');
  110. return;
  111. }
  112. hideError();
  113. const btn = document.getElementById('plAuthSend');
  114. if (!window.PL || !PL.api) { // 极旧的离线演示:无 api 层
  115. notify('离线演示验证码:123456');
  116. return;
  117. }
  118. btn.disabled = true;
  119. btn.textContent = '发送中…';
  120. PL.api.post('/auth/sms/send', { phone: phone }, { timeout: 10000 }).then(function (r) {
  121. if (r && r.demo && r.code) {
  122. notify('演示验证码:' + r.code + '(已自动填入)');
  123. const input = document.getElementById('plAuthCode');
  124. if (input) {
  125. input.value = r.code;
  126. input.focus();
  127. }
  128. } else {
  129. notify('验证码已发送,请注意查收短信');
  130. }
  131. startCountdown(btn);
  132. }, function (err) {
  133. btn.disabled = false;
  134. btn.textContent = '获取验证码';
  135. if (err.network) {
  136. notify('服务器暂不可达,离线演示验证码:123456', 'warn');
  137. startCountdown(btn);
  138. } else {
  139. showError(err.message || '发送失败,请稍后再试');
  140. }
  141. });
  142. }
  143. function startCountdown(btn) {
  144. countdown = 60;
  145. btn.disabled = true;
  146. btn.textContent = countdown + 's 后重发';
  147. clearInterval(countdownTimer);
  148. countdownTimer = setInterval(function () {
  149. countdown -= 1;
  150. if (countdown <= 0) {
  151. clearInterval(countdownTimer);
  152. btn.disabled = false;
  153. btn.textContent = '获取验证码';
  154. return;
  155. }
  156. btn.textContent = countdown + 's 后重发';
  157. }, 1000);
  158. }
  159. function applyLogin(u) {
  160. user = { id: u.id, phone: u.phone, name: u.name || ('用户' + String(u.phone || '').slice(-4)), role: u.role || 'user', at: Date.now() };
  161. try { localStorage.setItem(KEY, JSON.stringify(user)); } catch (e) {}
  162. const cb = pending;
  163. pending = null;
  164. close();
  165. emit();
  166. notify('登录成功');
  167. if (cb) setTimeout(cb, 60);
  168. }
  169. function submit() {
  170. const phone = document.getElementById('plAuthPhone').value.trim();
  171. const code = document.getElementById('plAuthCode').value.trim();
  172. if (!/^1\d{10}$/.test(phone)) {
  173. showError('请输入 11 位手机号');
  174. return;
  175. }
  176. if (!/^\d{6}$/.test(code)) {
  177. showError('请输入 6 位验证码');
  178. return;
  179. }
  180. if (!window.PL || !PL.api) return;
  181. PL.api.post('/auth/sms/login', { phone: phone, code: code }, { timeout: 10000 }).then(function (r) {
  182. PL.api.setToken(r.token);
  183. applyLogin(r.user);
  184. }, function (err) {
  185. if (err.network) {
  186. // 服务器不可达:保留旧的离线演示登录,站点可继续本地体验
  187. applyLogin({ id: 0, phone: phone, name: '用户' + phone.slice(-4), role: 'user' });
  188. notify('离线演示模式登录(数据不会上传)', 'warn');
  189. return;
  190. }
  191. showError(err.message || '登录失败,请重试');
  192. });
  193. }
  194. function logout() {
  195. user = null;
  196. pending = null;
  197. try { localStorage.removeItem(KEY); } catch (e) {}
  198. if (window.PL && PL.api) PL.api.setToken('');
  199. emit();
  200. notify('已退出登录');
  201. }
  202. function requireAuth(cb) {
  203. if (user) {
  204. if (cb) cb();
  205. return true;
  206. }
  207. pending = cb || null;
  208. open();
  209. return false;
  210. }
  211. function renderEntry(entry) {
  212. const btn = entry.querySelector('.pl-auth-btn');
  213. const menu = entry.querySelector('.pl-auth-menu');
  214. if (!btn) return;
  215. btn.textContent = user ? maskPhone(user.phone) : '登录';
  216. btn.classList.toggle('on', !!user);
  217. if (menu) {
  218. const name = menu.querySelector('.pl-auth-name');
  219. if (name) name.textContent = user ? '已登录 · ' + user.name : '';
  220. }
  221. }
  222. function buildEntry(entry) {
  223. entry.innerHTML =
  224. '<button class="pl-auth-btn" type="button"></button>' +
  225. '<div class="pl-auth-menu" hidden>' +
  226. '<span class="pl-auth-name"></span>' +
  227. '<button type="button" class="pl-auth-logout">退出登录</button>' +
  228. '</div>';
  229. const btn = entry.querySelector('.pl-auth-btn');
  230. const menu = entry.querySelector('.pl-auth-menu');
  231. btn.addEventListener('click', function (e) {
  232. e.stopPropagation();
  233. if (!user) {
  234. open();
  235. return;
  236. }
  237. menu.hidden = !menu.hidden;
  238. });
  239. entry.querySelector('.pl-auth-logout').addEventListener('click', function (e) {
  240. e.stopPropagation();
  241. menu.hidden = true;
  242. logout();
  243. });
  244. document.addEventListener('click', function () { menu.hidden = true; });
  245. renderEntry(entry);
  246. }
  247. function mount() {
  248. const trigger = document.getElementById('loginTrigger');
  249. if (trigger) {
  250. if (trigger.tagName === 'A') {
  251. trigger.addEventListener('click', function (e) { e.preventDefault(); });
  252. }
  253. trigger.addEventListener('click', function () {
  254. if (user) {
  255. logout();
  256. } else {
  257. open();
  258. }
  259. });
  260. const sync = function () {
  261. trigger.textContent = user ? maskPhone(user.phone) : '登录';
  262. trigger.classList.toggle('on', !!user);
  263. trigger.title = user ? '点击退出登录' : '登录';
  264. };
  265. listeners.push(sync);
  266. sync();
  267. }
  268. const actions = document.querySelector('.studio-actions');
  269. if (actions && !actions.querySelector('.pl-auth-entry')) {
  270. const entry = document.createElement('span');
  271. entry.className = 'pl-auth-entry';
  272. actions.insertBefore(entry, actions.firstChild);
  273. buildEntry(entry);
  274. listeners.push(function () { renderEntry(entry); });
  275. }
  276. emit();
  277. }
  278. document.addEventListener('keydown', function (e) {
  279. if (e.key === 'Escape') {
  280. const modal = document.getElementById('plAuthModal');
  281. if (modal && !modal.hidden) close();
  282. }
  283. });
  284. window.PL = window.PL || {};
  285. window.PL.auth = {
  286. user: function () { return user; },
  287. open: open,
  288. logout: logout,
  289. require: requireAuth,
  290. onChange: function (fn) { listeners.push(fn); return function () { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1); }; }
  291. };
  292. if (document.readyState === 'loading') {
  293. document.addEventListener('DOMContentLoaded', mount);
  294. } else {
  295. mount();
  296. }
  297. })();