微信扫码登录
MVP 首期暂不支持,敬请期待
diff --git a/.gitignore b/.gitignore index 9154f4c..772c507 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,4 @@ hs_err_pid* replay_pid* +backend/data/ diff --git a/README.md b/README.md index c715832..50278a7 100644 --- a/README.md +++ b/README.md @@ -2,3 +2,64 @@ 当看到这句话时,说明代码下载成功了 +## 广汇通 GPX - 商户端登录/注册 Demo + +基于 PRD《【登陆/注册】》(飞书 Wiki)实现的可运行 Demo。 + +### 目录结构 + +``` +prototype/ # 可交互 HTML 原型(纯静态,内置 Mock,双击即用) +frontend/ # 正式前端(原生 HTML/CSS/JS,调用后端 API) +backend/ # 后端服务(Node.js 原生 http,零依赖) +design/ # 飞书白板设计图导出 +``` + +### 快速启动 + +1. 启动后端(端口 3000): + +```bash +cd backend +node server.js +``` + +预置演示账号:`demo001` / `Gpx@2026` +(验证码登录场景,后端会在响应中回传 `devCode` 演示验证码,便于联调) + +2. 启动前端: + +```bash +cd frontend +python3 -m http.server 8080 +# 浏览器访问 http://localhost:8080 +``` + +前端会自动请求 `http://localhost:3000` 的后端 API(CORS 已放开)。 + +3. 交互原型(无需后端):直接用浏览器打开 `prototype/index.html`。 + +### 已实现的 PRD 规则 + +| 规则 | 说明 | +|---|---| +| 验证码有效期 | 10 分钟 | +| 验证码冷却 | 发送后 60s 内不允许二次触发 | +| 新码失效旧码 | 新验证码发出后旧验证码立即失效 | +| 静默注册 | 手机号/邮箱验证码校验通过后,未注册自动注册并登录 | +| 协议勾选 | 未勾选协议时,点击【获取验证码】拦截并提示 | +| 账号密码错误提示 | 「无效登录信息,请核对登录信息」 | +| IP 冻结 | 同 IP 连续错误 5 次 → 「暂停登录权限,请联系客服」,24h 后解冻 | +| 忘记密码 | 发送重置邮件(演示实现:日志) | +| 子账号格式 | 子ID@主ID(如 `zhangsan@demo001`) | +| 多语言 | zh-CN(默认)/ zh-TW / en,右上角切换,无刷新生效 | +| 微信扫码登录 | MVP 首期暂不支持,界面与接口已预留 | + +### API 一览 + +| 方法 | 路径 | 说明 | +|---|---|---| +| POST | /api/captcha/send | 发送验证码 `{type: phone\|email, target}` | +| POST | /api/login/verify-code | 验证码登录(含静默注册) | +| POST | /api/login/password | 账号密码登录(含 IP 冻结控制) | +| POST | /api/password/forgot | 忘记密码 | diff --git a/backend/server.js b/backend/server.js new file mode 100644 index 0000000..06c47e2 --- /dev/null +++ b/backend/server.js @@ -0,0 +1,247 @@ +/** + * 广汇通 GPX - 商户端登录/注册 后端服务(演示实现) + * + * PRD:《【登陆/注册】》产品需求说明书(飞书 Wiki) + * 技术栈:Node.js 原生 http 模块,零第三方依赖 + * + * 核心业务规则: + * 1. 验证码:有效期 10 分钟;发送后 60s 冷却;新验证码发出后旧验证码立即失效 + * 2. 验证码登录:校验通过后判断是否已注册,未注册静默注册并自动登录 + * 3. 账号密码登录:账号或密码任一错误 → 「无效登录信息」; + * 同一 IP 连续错误 N 次(默认 5) → 冻结登录权限至次日,提示「暂停登录权限,请联系客服」 + * 4. 忘记密码:发送重置邮件(演示实现仅记录日志) + * 5. 微信扫码登录:MVP 首期暂不支持,仅预留接口 + * + * 启动:node server.js (默认端口 3000,可用 PORT 环境变量覆盖) + */ +'use strict'; + +const http = require('http'); +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const PORT = process.env.PORT || 3000; +const DATA_DIR = path.join(__dirname, 'data'); +const USERS_FILE = path.join(DATA_DIR, 'users.json'); + +/* ================= 业务配置 ================= */ +const CONFIG = { + CODE_TTL_MS: 10 * 60 * 1000, // 验证码有效期 10 分钟 + CODE_SEND_COOLDOWN_MS: 60 * 1000, // 验证码发送冷却 60s + PWD_FAIL_FREEZE_AFTER: 5, // 同 IP 连续密码错误 N 次后冻结 + PWD_FAIL_FREEZE_MS: 24 * 60 * 60 * 1000, // 冻结时长:至次日(演示用 24h) + SEED_ACCOUNTS: [ + // 预置演示账号:demo001 / Gpx@2026(sha256) + { account: 'demo001', passwordHash: sha256('Gpx@2026'), role: 'merchant', displayId: 'demo001' } + ] +}; + +/* ================= 内存存储 ================= */ +/** 验证码存储: key = `${type}:${target}` -> { code, exp, sentAt } */ +const codeStore = new Map(); +/** 密码错误次数: ip -> { count, frozenUntil } */ +const pwdFailStore = new Map(); +/** 会话: token -> { userId, createdAt } */ +const sessionStore = new Map(); + +/* ================= 工具函数 ================= */ +function sha256(str) { + return crypto.createHash('sha256').update(str).digest('hex'); +} +function randomCode() { + return String(crypto.randomInt(100000, 1000000)); +} +function randomToken() { + return crypto.randomUUID(); +} +function now() { return Date.now(); } + +/* ================= 用户存储(JSON 文件持久化) ================= */ +function loadUsers() { + try { + return JSON.parse(fs.readFileSync(USERS_FILE, 'utf8')); + } catch (e) { + return []; + } +} +function saveUsers(users) { + if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true }); + fs.writeFileSync(USERS_FILE, JSON.stringify(users, null, 2)); +} + +/* ================= 业务逻辑 ================= */ +/** + * 发送验证码(手机短信 / 邮件,演示环境仅返回演示码) + * 规则:60s 冷却;新验证码发出后旧验证码立即失效(覆盖式存储) + */ +function sendCode(type, target) { + if (!['phone', 'email'].includes(type) || !target) { + return { httpStatus: 400, body: err(400, 'invalid type or target') }; + } + const key = `${type}:${target}`; + const prev = codeStore.get(key); + if (prev && now() - prev.sentAt < CONFIG.CODE_SEND_COOLDOWN_MS) { + const retryAfter = Math.ceil((CONFIG.CODE_SEND_COOLDOWN_MS - (now() - prev.sentAt)) / 1000); + return { httpStatus: 429, body: err(1004, 'code send too frequent', { retryAfter }) }; + } + const code = randomCode(); + codeStore.set(key, { code, exp: now() + CONFIG.CODE_TTL_MS, sentAt: now() }); + // TODO: 生产环境接入短信网关 / 邮件服务,此处仅演示 + console.log(`[captcha] ${type} -> ${target} code=${code} (valid 10min)`); + return { httpStatus: 200, body: ok({ expireIn: 600, devCode: code }) }; +} + +/** + * 验证码登录:未注册静默注册 + * 返回 { isNewUser, user, token } + */ +function loginByCode(type, target, code) { + if (!target || !code) return { httpStatus: 400, body: err(400, 'target and code required') }; + const key = `${type}:${target}`; + const saved = codeStore.get(key); + if (!saved || now() > saved.exp || saved.code !== String(code)) { + return { httpStatus: 401, body: err(1003, 'invalid or expired code') }; + } + codeStore.delete(key); // 一次性使用 + + const users = loadUsers(); + let user = users.find(u => u.type === type && u.target === target); + let isNewUser = false; + if (!user) { + isNewUser = true; // 静默注册 + user = { + id: randomToken(), + type, target, + displayId: target, + role: 'merchant', + createdAt: new Date().toISOString() + }; + users.push(user); + saveUsers(users); + } + const token = issueSession(user.id); + return { httpStatus: 200, body: ok({ isNewUser, user: pickUser(user), token }) }; +} + +/** + * 账号密码登录(支持子账号 子ID@主ID) + * 规则:错误提示统一「无效登录信息」;同 IP 连续失败 5 次冻结 24h + */ +function loginByPassword(account, password, ip) { + const record = pwdFailStore.get(ip); + if (record && record.frozenUntil && now() < record.frozenUntil) { + return { + httpStatus: 423, + body: err(1002, 'login suspended, contact customer service', { frozenUntil: record.frozenUntil }) + }; + } + + if (!account || !password) return { httpStatus: 400, body: err(400, 'account and password required') }; + + // 子账号:子ID@主ID → 先精确匹配子账号,再回退主账号 + const tryAccounts = [account]; + if (account.includes('@')) tryAccounts.push(account.split('@')[1]); + + const users = loadUsers(); + const allAccounts = users.concat(CONFIG.SEED_ACCOUNTS); + let matched = null; + for (const acc of tryAccounts) { + matched = allAccounts.find(u => u.account === acc && u.passwordHash === sha256(password)); + if (matched) break; + } + + if (!matched) { + const fail = pwdFailStore.get(ip) || { count: 0 }; + fail.count += 1; + if (fail.count >= CONFIG.PWD_FAIL_FREEZE_AFTER) { + fail.frozenUntil = now() + CONFIG.PWD_FAIL_FREEZE_MS; + fail.count = 0; + pwdFailStore.set(ip, fail); + return { + httpStatus: 423, + body: err(1002, 'login suspended, contact customer service', { frozenUntil: fail.frozenUntil }) + }; + } + pwdFailStore.set(ip, fail); + return { + httpStatus: 401, + body: err(1001, 'invalid credentials', { remainAttempts: CONFIG.PWD_FAIL_FREEZE_AFTER - fail.count }) + }; + } + + pwdFailStore.delete(ip); // 登录成功清零 + const token = issueSession(matched.id || matched.account); + return { httpStatus: 200, body: ok({ user: pickUser(matched), token }) }; +} + +/** 忘记密码:演示实现,仅记录日志(生产接邮件服务) */ +function forgotPassword(account) { + if (!account) return { httpStatus: 400, body: err(400, 'account required') }; + // TODO: 生产环境查询账号绑定邮箱并发送重置链接 + console.log(`[forgot-password] reset mail queued for account=${account}`); + return { httpStatus: 200, body: ok({ sent: true }) }; +} + +function issueSession(userId) { + const token = randomToken(); + sessionStore.set(token, { userId, createdAt: now() }); + return token; +} +function pickUser(u) { + return { id: u.id || u.account, account: u.account, displayId: u.displayId || u.target || u.account, role: u.role || 'merchant' }; +} + +/* ================= HTTP 基础设施 ================= */ +function ok(data) { return { code: 0, message: 'success', data }; } +function err(code, message, data) { return { code, message, data: data || null }; } + +function readBody(req) { + return new Promise((resolve) => { + let raw = ''; + req.on('data', c => { raw += c; if (raw.length > 1e6) req.destroy(); }); + req.on('end', () => { + try { resolve(raw ? JSON.parse(raw) : {}); } catch (e) { resolve({}); } + }); + }); +} +function sendJson(res, status, body) { + const payload = JSON.stringify(body); + res.writeHead(status, { + 'Content-Type': 'application/json; charset=utf-8', + 'Access-Control-Allow-Origin': '*', // 演示环境放开 CORS + 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization' + }); + res.end(payload); +} + +/* ================= 路由 ================= */ +const routes = { + '/api/captcha/send': ({ type, target }) => sendCode(type, target), + '/api/login/verify-code':({ type, target, code }) => loginByCode(type, target, code), + '/api/login/password': (p, ip) => loginByPassword(p.account, p.password, ip), + '/api/password/forgot': ({ account }) => forgotPassword(account) +}; + +const server = http.createServer(async (req, res) => { + if (req.method === 'OPTIONS') return sendJson(res, 204, {}); + const handler = routes[req.url.split('?')[0]]; + if (!handler || req.method !== 'POST') { + return sendJson(res, 404, err(404, 'not found')); + } + const body = await readBody(req); + const ip = (req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim(); + try { + const { httpStatus, body: out } = handler(body, ip) || { httpStatus: 500, body: err(500, 'no response') }; + sendJson(res, httpStatus, out); + } catch (e) { + console.error('[server error]', e); + sendJson(res, 500, err(500, 'internal error')); + } +}); + +server.listen(PORT, () => { + console.log(`GPX login/register backend listening on http://localhost:${PORT}`); + console.log(`Demo account: demo001 / Gpx@2026`); +}); diff --git a/design/whiteboard.png b/design/whiteboard.png new file mode 100644 index 0000000..c9c1212 Binary files /dev/null and b/design/whiteboard.png differ diff --git a/frontend/css/login.css b/frontend/css/login.css new file mode 100644 index 0000000..a5ae78e --- /dev/null +++ b/frontend/css/login.css @@ -0,0 +1,112 @@ +:root { + --primary: #2f54eb; + --text: #333; + --line: #d9d9d9; + --btn-disabled: #c4c6cc; + --danger: #f5222d; + --wechat: #07c160; +} +* { margin: 0; padding: 0; box-sizing: border-box; } +body { + font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif; + background: #fff; color: var(--text); min-height: 100vh; + display: flex; flex-direction: column; +} +.topbar { display: flex; justify-content: flex-end; padding: 20px 32px 0; } +.lang-switcher { position: relative; cursor: pointer; user-select: none; } +.lang-current { display: flex; align-items: center; gap: 6px; font-size: 14px; color: #666; } +.lang-current .flag { font-size: 16px; } +.lang-current .arrow { font-size: 10px; color: #999; transition: transform .2s; } +.lang-switcher.open .arrow { transform: rotate(180deg); } +.lang-menu { + display: none; position: absolute; right: 0; top: 28px; z-index: 100; + background: #fff; border: 1px solid #e8e8e8; border-radius: 8px; + box-shadow: 0 4px 16px rgba(0,0,0,.1); padding: 4px; min-width: 150px; +} +.lang-switcher.open .lang-menu { display: block; } +.lang-item { display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; font-size: 13px; } +.lang-item:hover { background: #f5f6fa; } +.lang-item.active { color: var(--primary); font-weight: 500; } + +.main { flex: 1; display: flex; justify-content: center; align-items: center; padding: 12px 32px 24px; } +.login-panel { display: flex; align-items: stretch; gap: 48px; width: 760px; max-width: 100%; } + +.qr-area { flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; } +.qr-area::after { content: ""; position: absolute; right: -24px; top: 12%; bottom: 12%; width: 1px; background: #e8e8e8; } +.qr-logo { width: 170px; height: 170px; opacity: .92; } +.qr-tip { margin-top: 28px; font-size: 15px; color: #555; } +.qr-tip .wx { color: var(--wechat); font-weight: 600; } +.qr-badge { + position: absolute; inset: 0; background: rgba(255,255,255,.96); display: none; + flex-direction: column; justify-content: center; align-items: center; gap: 12px; + border-radius: 12px; text-align: center; padding: 20px; +} +.qr-area.show-tip .qr-badge { display: flex; } +.qr-badge .phone-ico { font-size: 40px; } +.qr-badge p { font-size: 13px; color: #666; line-height: 1.8; } + +.form-area { flex: 1.2; display: flex; flex-direction: column; justify-content: center; } +.tabs { display: flex; gap: 48px; border-bottom: 1px solid #eee; } +.tab { + padding: 10px 2px 12px; font-size: 17px; color: #666; cursor: pointer; + border-bottom: 3px solid transparent; margin-bottom: -1px; transition: all .2s; +} +.tab.active { color: var(--primary); border-bottom-color: var(--primary); font-weight: 600; } + +.view { display: none; } +.view.active { display: block; animation: fadeIn .25s ease; } +@keyframes fadeIn { from { opacity: 0; transform: translateY(6px);} to { opacity: 1; transform: none;} } + +.field { display: flex; align-items: center; border-bottom: 1px solid var(--line); padding: 14px 2px; margin-top: 18px; transition: border-color .2s; } +.field:focus-within { border-bottom-color: var(--primary); } +.field .prefix { display: flex; align-items: center; gap: 4px; padding-right: 12px; border-right: 1px solid #e5e5e5; margin-right: 12px; cursor: pointer; font-size: 15px; } +.field input { flex: 1; border: none; outline: none; font-size: 15px; background: transparent; color: var(--text); } +.field input::placeholder { color: #bbb; } +.field .suffix-btn { border: none; background: none; color: var(--primary); font-size: 14px; cursor: pointer; white-space: nowrap; } +.field .suffix-btn:disabled { color: #bbb; cursor: not-allowed; } + +.btn-login { + width: 100%; margin-top: 32px; padding: 13px 0; border: none; border-radius: 6px; + background: var(--btn-disabled); color: #fff; font-size: 16px; cursor: not-allowed; transition: all .25s; +} +.btn-login.ready { background: var(--primary); cursor: pointer; } +.btn-login.ready:hover { background: #1d39c4; } + +.row-links { display: flex; justify-content: flex-end; margin-top: 20px; } +.link-btn { border: none; background: none; color: var(--primary); font-size: 14px; cursor: pointer; padding: 0; } +.center-links { text-align: center; margin-top: 26px; } + +.agreement { display: flex; align-items: flex-start; gap: 8px; margin-top: 26px; font-size: 12.5px; color: #666; line-height: 1.7; cursor: pointer; } +.agreement input[type=checkbox] { width: 15px; height: 15px; margin-top: 2px; cursor: pointer; accent-color: var(--primary); flex-shrink: 0; } +.agreement a { color: var(--primary); text-decoration: none; } +.agreement.shake { animation: shake .4s; } +@keyframes shake { 0%,100%{transform:translateX(0)} 25%{transform:translateX(-5px)} 75%{transform:translateX(5px)} } + +.form-error { color: var(--danger); font-size: 12.5px; margin-top: 12px; min-height: 18px; } + +.footer { text-align: center; padding: 14px 20px 18px; font-size: 12px; color: #bbb; line-height: 1.9; } +.footer a { color: #bbb; text-decoration: none; } +.footer a:hover { color: var(--primary); } + +#toast { + position: fixed; top: 18%; left: 50%; transform: translateX(-50%) translateY(-8px); + background: rgba(0,0,0,.78); color: #fff; font-size: 14px; + padding: 11px 22px; border-radius: 8px; opacity: 0; pointer-events: none; + transition: all .25s; z-index: 999; max-width: 80vw; text-align: center; +} +#toast.show { opacity: 1; transform: translateX(-50%) translateY(0); } + +#successMask { + display: none; position: fixed; inset: 0; background: rgba(255,255,255,.97); z-index: 500; + flex-direction: column; justify-content: center; align-items: center; gap: 16px; +} +#successMask.show { display: flex; } +#successMask .ok-ico { width: 72px; height: 72px; border-radius: 50%; background: var(--wechat); color: #fff; font-size: 40px; display: flex; align-items: center; justify-content: center; } +#successMask h2 { font-size: 22px; } +#successMask p { color: #888; font-size: 14px; } + +@media (max-width: 720px) { + .login-panel { flex-direction: column; gap: 24px; } + .qr-area::after { display: none; } + .qr-logo { width: 120px; height: 120px; } +} diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..456b2fa --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,129 @@ + + +
+ + +微信扫码登录
MVP 首期暂不支持,敬请期待
微信扫码登录
MVP 首期暂不支持,敬请期待