feat: 商户端登录/注册模块 - HTML原型+前端+后端
基于飞书 PRD《【登陆/注册】》实现: - prototype/: 可交互 HTML 原型(内置 Mock,含三语切换) - frontend/: 正式前端(原生 HTML/CSS/JS,调用后端 API) - backend/: Node.js 零依赖后端(验证码冷却/静默注册/IP冻结) - design/: 飞书白板设计图导出
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
/* 后端 API 封装:统一请求、错误码处理 */
|
||||
const API_BASE = location.hostname === 'localhost' || location.hostname === '127.0.0.1'
|
||||
? 'http://localhost:3000/api' : '/api';
|
||||
|
||||
const CODE = {
|
||||
OK: 0,
|
||||
BAD_REQUEST: 400,
|
||||
INVALID_CREDENTIALS: 1001, // 无效登录信息
|
||||
IP_FROZEN: 1002, // 同 IP 连续错误过多,登录权限暂停
|
||||
CODE_INVALID: 1003, // 验证码错误/过期
|
||||
SEND_TOO_FREQUENT: 1004 // 验证码发送冷却中
|
||||
};
|
||||
|
||||
async function api(path, data) {
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(API_BASE + path, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data || {})
|
||||
});
|
||||
} catch (e) {
|
||||
throw { code: -1, message: 'NETWORK' };
|
||||
}
|
||||
const json = await res.json().catch(() => ({ code: -1, message: 'NETWORK' }));
|
||||
if (!res.ok || json.code !== CODE.OK) throw json;
|
||||
return json.data;
|
||||
}
|
||||
|
||||
const Api = {
|
||||
/** 发送验证码 type: phone | email */
|
||||
sendCode: (type, target) => api('/captcha/send', { type, target }),
|
||||
/** 验证码登录(未注册静默注册) */
|
||||
loginByCode: (type, target, code) => api('/login/verify-code', { type, target, code }),
|
||||
/** 账号密码登录(子账号格式:子ID@主ID) */
|
||||
loginByPassword: (account, password) => api('/login/password', { account, password }),
|
||||
/** 忘记密码 */
|
||||
forgotPassword: (account) => api('/password/forgot', { account })
|
||||
};
|
||||
@@ -0,0 +1,107 @@
|
||||
/* 多语言字典:zh-CN(默认)/ zh-TW / en,切换无需刷新页面 */
|
||||
const I18N = {
|
||||
'zh-CN': {
|
||||
name: '中文(简体)', flag: '🇨🇳',
|
||||
tabPhone: '手机号', tabEmail: '邮箱',
|
||||
phPhone: '请输入手机号', phEmail: '邮箱', phCode: '输入验证码',
|
||||
phAccount: '请输入账号', phPwd: '输入密码',
|
||||
getCode: '获取验证码', resend: '{s}s后重发', login: '登录',
|
||||
toAccount: '账号密码登录', toVerify: '验证码登录', forgotPwd: '忘记密码',
|
||||
qrOpen: '打开', qrScan: '扫码登录',
|
||||
agreeLine1: '未注册手机号、邮箱验证后自动登录',
|
||||
agreeLine2a: '注册即代表我已阅读并同意', agreeTos: '《服务条款》', agreePrivacy: '《隐私政策》', agreeAnd: '和', agreePay: '《支付服务协议》',
|
||||
rights: 'All Rights Reserved.', loginOk: '登录成功',
|
||||
toastAgree: '请先勾选同意《服务条款》《隐私政策》和《支付服务协议》',
|
||||
toastCodeSent: '验证码已发送,有效期 10 分钟(演示码:{code})',
|
||||
toastCodeErr: '验证码错误或已过期,请重新获取',
|
||||
toastSilentReg: '新用户已静默注册并自动登录',
|
||||
toastLoginOk: '欢迎回来!',
|
||||
toastAccErr: '无效登录信息,请核对登录信息',
|
||||
toastFrozen: '该 IP 登录错误次数过多,登录权限已暂停,请联系客服',
|
||||
toastForgot: '重置密码邮件已发送至您的邮箱,请注意查收',
|
||||
toastWx: '微信扫码登录 MVP 首期暂不支持,敬请期待',
|
||||
toastNetErr: '网络异常,请稍后重试',
|
||||
phoneErr: '请输入正确的手机号', emailErr: '请输入正确的邮箱地址',
|
||||
wxTitle: '微信扫码登录', wxReserved: 'MVP 首期暂不支持,敬请期待'
|
||||
},
|
||||
'zh-TW': {
|
||||
name: '中文(繁體)', flag: '🇭🇰',
|
||||
tabPhone: '手機號', tabEmail: '郵箱',
|
||||
phPhone: '請輸入手機號', phEmail: '郵箱', phCode: '輸入驗證碼',
|
||||
phAccount: '請輸入賬號', phPwd: '輸入密碼',
|
||||
getCode: '獲取驗證碼', resend: '{s}s後重發', login: '登錄',
|
||||
toAccount: '賬號密碼登錄', toVerify: '驗證碼登錄', forgotPwd: '忘記密碼',
|
||||
qrOpen: '打開', qrScan: '掃碼登錄',
|
||||
agreeLine1: '未註冊手機號、郵箱驗證後自動登錄',
|
||||
agreeLine2a: '註冊即代表我已閱讀並同意', agreeTos: '《服務條款》', agreePrivacy: '《隱私政策》', agreeAnd: '和', agreePay: '《支付服務協議》',
|
||||
rights: 'All Rights Reserved.', loginOk: '登錄成功',
|
||||
toastAgree: '請先勾選同意《服務條款》《隱私政策》和《支付服務協議》',
|
||||
toastCodeSent: '驗證碼已發送,有效期 10 分鐘(演示碼:{code})',
|
||||
toastCodeErr: '驗證碼錯誤或已過期,請重新獲取',
|
||||
toastSilentReg: '新用戶已靜默註冊並自動登錄',
|
||||
toastLoginOk: '歡迎回來!',
|
||||
toastAccErr: '無效登錄信息,請核對登錄信息',
|
||||
toastFrozen: '該 IP 登錄錯誤次數過多,登錄權限已暫停,請聯繫客服',
|
||||
toastForgot: '重置密碼郵件已發送至您的郵箱,請注意查收',
|
||||
toastWx: '微信掃碼登錄 MVP 首期暫不支持,敬請期待',
|
||||
toastNetErr: '網絡異常,請稍後重試',
|
||||
phoneErr: '請輸入正確的手機號', emailErr: '請輸入正確的郵箱地址',
|
||||
wxTitle: '微信掃碼登錄', wxReserved: 'MVP 首期暫不支持,敬請期待'
|
||||
},
|
||||
'en': {
|
||||
name: 'English', flag: '🇺🇸',
|
||||
tabPhone: 'Phone', tabEmail: 'Email',
|
||||
phPhone: 'Enter phone number', phEmail: 'Email', phCode: 'Enter code',
|
||||
phAccount: 'Enter account', phPwd: 'Enter password',
|
||||
getCode: 'Get code', resend: 'Resend in {s}s', login: 'Log In',
|
||||
toAccount: 'Login with account', toVerify: 'Login with code', forgotPwd: 'Forgot password',
|
||||
qrOpen: 'Open', qrScan: 'WeChat scan to log in',
|
||||
agreeLine1: 'Unregistered phone/email will auto-register after verification',
|
||||
agreeLine2a: 'By registering, I have read and agree to', agreeTos: 'Terms of Service', agreePrivacy: 'Privacy Policy', agreeAnd: 'and', agreePay: 'Payment Agreement',
|
||||
rights: 'All Rights Reserved.', loginOk: 'Login Successful',
|
||||
toastAgree: 'Please agree to the Terms, Privacy Policy and Payment Agreement first',
|
||||
toastCodeSent: 'Code sent, valid for 10 minutes (demo code: {code})',
|
||||
toastCodeErr: 'Invalid or expired code, please request a new one',
|
||||
toastSilentReg: 'New account registered & logged in automatically',
|
||||
toastLoginOk: 'Welcome back!',
|
||||
toastAccErr: 'Invalid login credentials, please check and retry',
|
||||
toastFrozen: 'Too many failed attempts from this IP. Login suspended, please contact support',
|
||||
toastForgot: 'Password reset email has been sent to your mailbox',
|
||||
toastWx: 'WeChat scan login is not available in MVP, stay tuned',
|
||||
toastNetErr: 'Network error, please try again later',
|
||||
phoneErr: 'Please enter a valid phone number', emailErr: 'Please enter a valid email address',
|
||||
wxTitle: 'WeChat Scan Login', wxReserved: 'Not available in MVP, stay tuned'
|
||||
}
|
||||
};
|
||||
|
||||
let lang = localStorage.getItem('gpx_lang') || 'zh-CN';
|
||||
const t = (k) => (I18N[lang] && I18N[lang][k]) || k;
|
||||
|
||||
function applyLang() {
|
||||
const L = I18N[lang];
|
||||
document.getElementById('langFlag').textContent = L.flag;
|
||||
document.getElementById('langName').textContent = L.name;
|
||||
document.documentElement.lang = lang;
|
||||
document.querySelectorAll('[data-i18n]').forEach(el => el.textContent = t(el.dataset.i18n));
|
||||
document.querySelectorAll('[data-i18n-ph]').forEach(el => el.placeholder = t(el.dataset.i18nPh));
|
||||
renderLangMenu();
|
||||
}
|
||||
function renderLangMenu() {
|
||||
const menu = document.getElementById('langMenu');
|
||||
menu.innerHTML = '';
|
||||
Object.entries(I18N).forEach(([code, L]) => {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'lang-item' + (code === lang ? ' active' : '');
|
||||
div.innerHTML = `<span>${L.flag}</span><span>${L.name}</span>`;
|
||||
div.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
lang = code; localStorage.setItem('gpx_lang', code);
|
||||
applyLang(); toggleLang(false);
|
||||
};
|
||||
menu.appendChild(div);
|
||||
});
|
||||
}
|
||||
function toggleLang(force) {
|
||||
const sw = document.getElementById('langSwitcher');
|
||||
sw.classList.toggle('open', force !== undefined ? force : !sw.classList.contains('open'));
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/* 登录页主逻辑:视图切换 / 验证码冷却 / 三种登录方式 */
|
||||
(function () {
|
||||
/* ===== Toast ===== */
|
||||
let toastTimer;
|
||||
function toast(msg, ms = 2600) {
|
||||
const el = document.getElementById('toast');
|
||||
el.textContent = msg; el.classList.add('show');
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => el.classList.remove('show'), ms);
|
||||
}
|
||||
function toastByKey(key, ms) { toast(t(key), ms); }
|
||||
function toastRaw(msg, ms) { toast(msg, ms); }
|
||||
|
||||
/* ===== 语言切换 ===== */
|
||||
document.getElementById('langSwitcher').addEventListener('click', () => toggleLang());
|
||||
document.addEventListener('click', (e) => { if (!e.target.closest('#langSwitcher')) toggleLang(false); });
|
||||
applyLang();
|
||||
|
||||
/* ===== 视图切换 ===== */
|
||||
const qrArea = document.getElementById('qrArea');
|
||||
document.querySelectorAll('.tab, [data-goto]').forEach(el => {
|
||||
el.addEventListener('click', () => switchView(el.dataset.view || el.dataset.goto));
|
||||
});
|
||||
function switchView(name) {
|
||||
document.querySelectorAll('.tab').forEach(x => x.classList.toggle('active', x.dataset.view === name));
|
||||
document.querySelectorAll('.view').forEach(x => x.classList.toggle('active', x.id === 'view-' + name));
|
||||
qrArea.style.display = name === 'account' ? 'none' : 'flex';
|
||||
clearErrors();
|
||||
}
|
||||
function clearErrors() { document.querySelectorAll('.form-error').forEach(e => e.textContent = ''); }
|
||||
function showErr(id, msg) { document.getElementById(id).textContent = msg || ''; }
|
||||
|
||||
/* ===== 协议勾选 ===== */
|
||||
const agreeCheck = document.getElementById('agreeCheck');
|
||||
function requireAgree() {
|
||||
if (agreeCheck.checked) return true;
|
||||
toastByKey('toastAgree');
|
||||
const box = document.getElementById('agreementBox');
|
||||
box.classList.remove('shake'); void box.offsetWidth; box.classList.add('shake');
|
||||
return false;
|
||||
}
|
||||
|
||||
/* ===== 验证码按钮冷却(60s) ===== */
|
||||
function cooldown(btn) {
|
||||
let s = 60; btn.disabled = true;
|
||||
const tick = () => {
|
||||
btn.textContent = t('resend').replace('{s}', s);
|
||||
if (--s > 0) setTimeout(tick, 1000);
|
||||
else { btn.disabled = false; btn.textContent = t('getCode'); }
|
||||
};
|
||||
tick();
|
||||
}
|
||||
|
||||
/* ===== 登录成功 ===== */
|
||||
function loginOk(user, isNew) {
|
||||
document.getElementById('successDetail').textContent = user + (isNew ? ' · ' + t('toastSilentReg') : '');
|
||||
document.getElementById('successMask').classList.add('show');
|
||||
}
|
||||
function handleApiError(err, errElId) {
|
||||
if (err.code === CODE.IP_FROZEN) {
|
||||
showErr(errElId, t('toastFrozen')); return;
|
||||
}
|
||||
if (err.code === CODE.CODE_INVALID) { toastByKey('toastCodeErr'); return; }
|
||||
if (err.code === CODE.INVALID_CREDENTIALS) {
|
||||
const left = err.data && err.data.remainAttempts;
|
||||
showErr(errElId, t('toastAccErr') + (left != null ? `(${left})` : '')); return;
|
||||
}
|
||||
if (err.code === CODE.SEND_TOO_FREQUENT) {
|
||||
toastRaw((err.data && err.data.retryAfter ? err.data.retryAfter + 's ' : '') + t('toastCodeErr')); return;
|
||||
}
|
||||
toastByKey('toastNetErr');
|
||||
}
|
||||
|
||||
/* ===== 手机号验证码登录 ===== */
|
||||
const phoneInput = document.getElementById('phoneInput');
|
||||
const phoneCodeInput = document.getElementById('phoneCodeInput');
|
||||
const phoneSendBtn = document.getElementById('phoneSendBtn');
|
||||
const isPhone = v => /^1\d{10}$|^\d{8,11}$/.test(v);
|
||||
|
||||
phoneSendBtn.addEventListener('click', async () => {
|
||||
if (phoneSendBtn.disabled) return;
|
||||
if (!isPhone(phoneInput.value)) { showErr('phoneError', t('phoneErr')); return; }
|
||||
if (!requireAgree()) return;
|
||||
try {
|
||||
const data = await Api.sendCode('phone', phoneInput.value);
|
||||
cooldown(phoneSendBtn); clearErrors();
|
||||
// 演示环境后端会回传演示验证码,便于联调;生产环境 devCode 为空
|
||||
toastRaw(t('toastCodeSent').replace('{code}', data.devCode || '****'), 4200);
|
||||
} catch (err) { handleApiError(err, 'phoneError'); }
|
||||
});
|
||||
|
||||
document.getElementById('phoneLoginBtn').addEventListener('click', async () => {
|
||||
if (!isPhone(phoneInput.value)) { showErr('phoneError', t('phoneErr')); return; }
|
||||
if (!phoneCodeInput.value) { toastByKey('toastCodeErr'); return; }
|
||||
try {
|
||||
const data = await Api.loginByCode('phone', phoneInput.value, phoneCodeInput.value);
|
||||
clearErrors(); loginOk(data.user.displayId, data.isNewUser);
|
||||
toastByKey(data.isNewUser ? 'toastSilentReg' : 'toastLoginOk');
|
||||
} catch (err) { handleApiError(err, 'phoneError'); }
|
||||
});
|
||||
|
||||
/* ===== 邮箱验证码登录 ===== */
|
||||
const emailInput = document.getElementById('emailInput');
|
||||
const emailCodeInput = document.getElementById('emailCodeInput');
|
||||
const emailSendBtn = document.getElementById('emailSendBtn');
|
||||
const isEmail = v => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v);
|
||||
|
||||
emailSendBtn.addEventListener('click', async () => {
|
||||
if (emailSendBtn.disabled) return;
|
||||
if (!isEmail(emailInput.value)) { showErr('emailError', t('emailErr')); return; }
|
||||
if (!requireAgree()) return;
|
||||
try {
|
||||
const data = await Api.sendCode('email', emailInput.value);
|
||||
cooldown(emailSendBtn); clearErrors();
|
||||
toastRaw(t('toastCodeSent').replace('{code}', data.devCode || '****'), 4200);
|
||||
} catch (err) { handleApiError(err, 'emailError'); }
|
||||
});
|
||||
|
||||
document.getElementById('emailLoginBtn').addEventListener('click', async () => {
|
||||
if (!isEmail(emailInput.value)) { showErr('emailError', t('emailErr')); return; }
|
||||
if (!emailCodeInput.value) { toastByKey('toastCodeErr'); return; }
|
||||
try {
|
||||
const data = await Api.loginByCode('email', emailInput.value, emailCodeInput.value);
|
||||
clearErrors(); loginOk(data.user.displayId, data.isNewUser);
|
||||
toastByKey(data.isNewUser ? 'toastSilentReg' : 'toastLoginOk');
|
||||
} catch (err) { handleApiError(err, 'emailError'); }
|
||||
});
|
||||
|
||||
/* ===== 账号密码登录 ===== */
|
||||
document.getElementById('accLoginBtn').addEventListener('click', async () => {
|
||||
const account = document.getElementById('accInput').value.trim();
|
||||
const password = document.getElementById('pwdInput').value;
|
||||
if (!account || !password) { showErr('accError', t('toastAccErr')); return; }
|
||||
try {
|
||||
const data = await Api.loginByPassword(account, password);
|
||||
clearErrors(); loginOk(data.user.displayId, false);
|
||||
toastByKey('toastLoginOk');
|
||||
} catch (err) { handleApiError(err, 'accError'); }
|
||||
});
|
||||
|
||||
/* ===== 忘记密码 ===== */
|
||||
document.getElementById('forgotBtn').addEventListener('click', async () => {
|
||||
const account = document.getElementById('accInput').value.trim();
|
||||
try { await Api.forgotPassword(account); toastByKey('toastForgot'); }
|
||||
catch (err) { handleApiError(err, 'accError'); }
|
||||
});
|
||||
|
||||
/* ===== 微信扫码(MVP 预留) ===== */
|
||||
qrArea.addEventListener('click', () => {
|
||||
qrArea.classList.add('show-tip');
|
||||
setTimeout(() => qrArea.classList.remove('show-tip'), 2200);
|
||||
toastByKey('toastWx');
|
||||
});
|
||||
})();
|
||||
Reference in New Issue
Block a user