Initial commit after history purge
This commit is contained in:
+27
@@ -0,0 +1,27 @@
|
||||
# ---> Java
|
||||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
replay_pid*
|
||||
|
||||
backend/data/
|
||||
@@ -0,0 +1,73 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
||||
|
||||
Copyright 2026 louis-xiv
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,65 @@
|
||||
# for-test
|
||||
|
||||
当看到这句话时,说明代码下载成功了
|
||||
|
||||
## 商户端登录/注册 Demo
|
||||
|
||||
基于 PRD《【登陆/注册】》(飞书 Wiki)实现的可运行 Demo。
|
||||
|
||||
### 目录结构
|
||||
|
||||
```
|
||||
prototype/ # 可交互 HTML 原型(纯静态,内置 Mock,双击即用)
|
||||
frontend/ # 正式前端(原生 HTML/CSS/JS,调用后端 API)
|
||||
backend/ # 后端服务(Node.js 原生 http,零依赖)
|
||||
|
||||
```
|
||||
|
||||
### 快速启动
|
||||
|
||||
1. 启动后端(端口 3000):
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
node server.js
|
||||
```
|
||||
|
||||
预置演示账号:`demo001` / `Demo@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 | 忘记密码 |
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* 商户端登录/注册 后端服务(演示实现)
|
||||
*
|
||||
* 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 / Demo@2026(sha256)
|
||||
{ account: 'demo001', passwordHash: sha256('Demo@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(`login/register backend listening on http://localhost:${PORT}`);
|
||||
console.log(`Demo account: demo001 / Demo@2026`);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env bash
|
||||
# 商户端登录/注册 - API 回归测试
|
||||
# 前置:后端已启动(node server.js),PORT 默认 3000
|
||||
# 用法:bash regression.sh
|
||||
set -u
|
||||
BASE="http://localhost:${PORT:-3000}/api"
|
||||
PASS=0; FAIL=0
|
||||
|
||||
check() { # check <用例名> <期望code> <实际响应>
|
||||
local name="$1" expect="$2" resp="$3"
|
||||
local got
|
||||
got=$(echo "$resp" | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin).get('code','parse-error'))" 2>/dev/null)
|
||||
if [ "$got" = "$expect" ]; then
|
||||
PASS=$((PASS+1)); echo "✅ $name (code=$got)"
|
||||
else
|
||||
FAIL=$((FAIL+1)); echo "❌ $name 期望code=$expect 实际code=$got"
|
||||
echo " 响应: $resp"
|
||||
fi
|
||||
}
|
||||
|
||||
post() { curl -s -X POST "$BASE$1" -H 'Content-Type: application/json' -d "$2"; }
|
||||
|
||||
echo "========== 1. 验证码模块 =========="
|
||||
R=$(post /captcha/send '{"type":"phone","target":"13900001111"}')
|
||||
check "手机验证码发送成功" 0 "$R"
|
||||
R=$(post /captcha/send '{"type":"phone","target":"13900001111"}')
|
||||
check "60s冷却内重复发送被拦截" 1004 "$R"
|
||||
R=$(post /captcha/send '{"type":"email","target":"a@b.com"}')
|
||||
check "邮箱验证码发送成功" 0 "$R"
|
||||
R=$(post /captcha/send '{"type":"foo","target":"x"}')
|
||||
check "非法类型被拒绝" 400 "$R"
|
||||
R=$(post /login/verify-code '{"type":"phone","target":"13900001111","code":"000000"}')
|
||||
check "错误验证码登录失败" 1003 "$R"
|
||||
|
||||
echo "========== 2. 静默注册 =========="
|
||||
CODE=$(post /captcha/send '{"type":"email","target":"regress@new.com"}' | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin)['data']['devCode'])")
|
||||
R=$(post /login/verify-code "{\"type\":\"email\",\"target\":\"regress@new.com\",\"code\":\"$CODE\"}")
|
||||
check "新用户验证码登录(静默注册)" 0 "$R"
|
||||
ISNEW=$(echo "$R" | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin)['data']['isNewUser'])")
|
||||
if [ "$ISNEW" = "True" ]; then PASS=$((PASS+1)); echo "✅ isNewUser=true"; else FAIL=$((FAIL+1)); echo "❌ isNewUser 预期 True 实际 $ISNEW"; fi
|
||||
CODE2=$(post /captcha/send '{"type":"email","target":"regress@new.com"}' | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin)['data']['devCode'])")
|
||||
R=$(post /login/verify-code "{\"type\":\"email\",\"target\":\"regress@new.com\",\"code\":\"$CODE2\"}")
|
||||
ISNEW2=$(echo "$R" | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin)['data']['isNewUser'])")
|
||||
check "第二次登录不再静默注册" 0 "$R"
|
||||
if [ "$ISNEW2" = "False" ]; then PASS=$((PASS+1)); echo "✅ 老用户 isNewUser=false"; else FAIL=$((FAIL+1)); echo "❌ isNewUser 预期 False 实际 $ISNEW2"; fi
|
||||
|
||||
echo "========== 3. 账号密码登录 =========="
|
||||
R=$(post /login/password '{"account":"demo001","password":"Demo@2026"}')
|
||||
check "正确密码登录成功" 0 "$R"
|
||||
R=$(post /login/password '{"account":"demo001","password":"wrong"}')
|
||||
check "错误密码返回无效登录信息" 1001 "$R"
|
||||
R=$(post /login/password '{"account":"zhangsan@demo001","password":"Demo@2026"}')
|
||||
check "子账号(子ID@主ID)可登录" 0 "$R"
|
||||
R=$(post /login/password '{"account":"nosuch","password":"x"}')
|
||||
check "不存在的账号返回无效登录信息" 1001 "$R"
|
||||
|
||||
echo "========== 4. IP 冻结(连续错5次) =========="
|
||||
for i in 2 3 4; do post /login/password '{"account":"demo001","password":"bad"}' > /dev/null; done
|
||||
R=$(post /login/password '{"account":"demo001","password":"bad"}')
|
||||
check "第5次错误触发IP冻结" 1002 "$R"
|
||||
R=$(post /login/password '{"account":"demo001","password":"Demo@2026"}')
|
||||
check "冻结期间正确密码也无法登录" 1002 "$R"
|
||||
post /password/forgot '{"account":"demo001"}' > /dev/null
|
||||
|
||||
echo "========== 5. 忘记密码 =========="
|
||||
R=$(post /password/forgot '{"account":"demo001"}')
|
||||
check "忘记密码接口成功" 0 "$R"
|
||||
R=$(post /password/forgot '{}')
|
||||
check "缺少账号被拒绝" 400 "$R"
|
||||
|
||||
echo ""
|
||||
echo "========== 回归结果: $PASS 通过 / $FAIL 失败 =========="
|
||||
[ "$FAIL" = "0" ]
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>商户登录/注册</title>
|
||||
<link rel="stylesheet" href="css/login.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="topbar">
|
||||
<div class="lang-switcher" id="langSwitcher">
|
||||
<div class="lang-current">
|
||||
<span class="flag" id="langFlag">🇨🇳</span>
|
||||
<span id="langName">中文(简体)</span>
|
||||
<span class="arrow">▼</span>
|
||||
</div>
|
||||
<div class="lang-menu" id="langMenu"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="main">
|
||||
<div class="login-panel">
|
||||
<div class="qr-area" id="qrArea">
|
||||
<svg class="qr-logo" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M8 8h32v32H8zm8 8v16h16V16z" fill="#b9bcc2"/>
|
||||
<rect x="60" y="8" width="32" height="32" fill="none" stroke="#b9bcc2" stroke-width="8"/>
|
||||
<rect x="8" y="60" width="32" height="32" fill="none" stroke="#b9bcc2" stroke-width="8"/>
|
||||
<path d="M60 60h32v32H60zm8 8v16h16V68z" fill="#b9bcc2"/>
|
||||
<rect x="44" y="12" width="8" height="26" fill="#b9bcc2"/>
|
||||
<rect x="12" y="44" width="26" height="8" fill="#b9bcc2"/>
|
||||
<rect x="46" y="46" width="8" height="8" fill="#b9bcc2"/>
|
||||
<rect x="62" y="44" width="26" height="4" fill="#b9bcc2"/>
|
||||
</svg>
|
||||
<div class="qr-tip"><span data-i18n="qrOpen">打开</span> <span class="wx">💬微信</span> <span data-i18n="qrScan">扫码登录</span></div>
|
||||
<div class="qr-badge">
|
||||
<div class="phone-ico">📱</div>
|
||||
<p><b data-i18n="wxTitle">微信扫码登录</b><br><span data-i18n="wxReserved">MVP 首期暂不支持,敬请期待</span></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-area">
|
||||
<div class="tabs">
|
||||
<div class="tab active" data-view="phone" data-i18n="tabPhone">手机号</div>
|
||||
<div class="tab" data-view="email" data-i18n="tabEmail">邮箱</div>
|
||||
</div>
|
||||
|
||||
<div class="view active" id="view-phone">
|
||||
<div class="field">
|
||||
<span class="prefix">+86 <small>▲</small></span>
|
||||
<input type="tel" id="phoneInput" data-i18n-ph="phPhone" placeholder="请输入手机号" maxlength="11">
|
||||
</div>
|
||||
<div class="field">
|
||||
<input type="text" id="phoneCodeInput" data-i18n-ph="phCode" placeholder="输入验证码" maxlength="6">
|
||||
<button class="suffix-btn" id="phoneSendBtn" data-i18n="getCode">获取验证码</button>
|
||||
</div>
|
||||
<div class="form-error" id="phoneError"></div>
|
||||
<button class="btn-login" id="phoneLoginBtn" data-i18n="login">登录</button>
|
||||
<div class="center-links">
|
||||
<button class="link-btn" data-goto="account" data-i18n="toAccount">账号密码登录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="view" id="view-email">
|
||||
<div class="field">
|
||||
<input type="email" id="emailInput" data-i18n-ph="phEmail" placeholder="邮箱">
|
||||
</div>
|
||||
<div class="field">
|
||||
<input type="text" id="emailCodeInput" data-i18n-ph="phCode" placeholder="输入验证码" maxlength="6">
|
||||
<button class="suffix-btn" id="emailSendBtn" data-i18n="getCode">获取验证码</button>
|
||||
</div>
|
||||
<div class="form-error" id="emailError"></div>
|
||||
<button class="btn-login" id="emailLoginBtn" data-i18n="login">登录</button>
|
||||
<div class="center-links">
|
||||
<button class="link-btn" data-goto="account" data-i18n="toAccount">账号密码登录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="view" id="view-account">
|
||||
<div class="field">
|
||||
<input type="text" id="accInput" data-i18n-ph="phAccount" placeholder="请输入账号" autocomplete="username">
|
||||
</div>
|
||||
<div class="field">
|
||||
<input type="password" id="pwdInput" data-i18n-ph="phPwd" placeholder="输入密码" autocomplete="current-password">
|
||||
</div>
|
||||
<div class="row-links"><button class="link-btn" id="forgotBtn" data-i18n="forgotPwd">忘记密码</button></div>
|
||||
<div class="form-error" id="accError"></div>
|
||||
<button class="btn-login" id="accLoginBtn" data-i18n="login">登录</button>
|
||||
<div class="center-links">
|
||||
<button class="link-btn" data-goto="phone" data-i18n="toVerify">验证码登录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="agreement" id="agreementBox">
|
||||
<input type="checkbox" id="agreeCheck">
|
||||
<span>
|
||||
<span data-i18n="agreeLine1">未注册手机号、邮箱验证后自动登录</span><br>
|
||||
<span data-i18n="agreeLine2a">注册即代表我已阅读并同意</span>
|
||||
<a href="javascript:void(0)" data-i18n="agreeTos">《服务条款》</a>
|
||||
<a href="javascript:void(0)" data-i18n="agreePrivacy">《隐私政策》</a>
|
||||
<span data-i18n="agreeAnd">和</span>
|
||||
<a href="javascript:void(0)" data-i18n="agreePay">《支付服务协议》</a>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<div>© 2026 <a href="javascript:void(0)">www.example.com</a> <span data-i18n="rights">All Rights Reserved.</span></div>
|
||||
<div>
|
||||
<a href="https://beian.miit.gov.cn/" target="_blank">粤ICP备XXXXXXXX号</a>
|
||||
<a href="https://beian.mps.gov.cn/" target="_blank">粤公网安备 XXXXXXXX号</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="toast"></div>
|
||||
|
||||
<div id="successMask">
|
||||
<div class="ok-ico">✓</div>
|
||||
<h2 data-i18n="loginOk">登录成功</h2>
|
||||
<p id="successDetail"></p>
|
||||
</div>
|
||||
|
||||
<script src="js/i18n.js"></script>
|
||||
<script src="js/api.js"></script>
|
||||
<script src="js/login.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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('login_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('login_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');
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,462 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>商户登录/注册(可交互原型)</title>
|
||||
<style>
|
||||
:root {
|
||||
--primary: #2f54eb;
|
||||
--text: #333;
|
||||
--text-light: #999;
|
||||
--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; top: 0; left: 0; width: 100%; height: 100%;
|
||||
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; }
|
||||
.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 */
|
||||
#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; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- 顶部语言切换 -->
|
||||
<div class="topbar">
|
||||
<div class="lang-switcher" id="langSwitcher">
|
||||
<div class="lang-current">
|
||||
<span class="flag" id="langFlag">🇨🇳</span>
|
||||
<span id="langName">中文(简体)</span>
|
||||
<span class="arrow">▼</span>
|
||||
</div>
|
||||
<div class="lang-menu" id="langMenu"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主体 -->
|
||||
<div class="main">
|
||||
<div class="login-panel">
|
||||
<!-- 左侧:微信扫码登录(MVP 预留) -->
|
||||
<div class="qr-area" id="qrArea">
|
||||
<svg class="qr-logo" viewBox="0 0 100 100" fill="#b9bcC2" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M8 8h32v32H8zm8 8v16h16V16z"/>
|
||||
<rect x="60" y="8" width="32" height="32" fill="none" stroke="#b9bcc2" stroke-width="8"/>
|
||||
<rect x="8" y="60" width="32" height="32" fill="none" stroke="#b9bcc2" stroke-width="8"/>
|
||||
<path d="M60 60h32v32H60zm8 8v16h16V68z"/>
|
||||
<rect x="44" y="12" width="8" height="26"/>
|
||||
<rect x="12" y="44" width="26" height="8"/>
|
||||
<rect x="46" y="46" width="8" height="8"/>
|
||||
<rect x="62" y="44" width="26" height="4"/>
|
||||
</svg>
|
||||
<div class="qr-tip"><span data-i18n="qrOpen">打开</span> <span class="wx">💬微信</span> <span data-i18n="qrScan">扫码登录</span></div>
|
||||
<div class="qr-badge">
|
||||
<div class="phone-ico">📱</div>
|
||||
<p><b data-i18n="wxTitle">微信扫码登录</b><br><span data-i18n="wxReserved">MVP 首期暂不支持,敬请期待</span></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧:表单 -->
|
||||
<div class="form-area">
|
||||
<div class="tabs">
|
||||
<div class="tab active" data-view="phone" data-i18n="tabPhone">手机号</div>
|
||||
<div class="tab" data-view="email" data-i18n="tabEmail">邮箱</div>
|
||||
<div class="tab" data-view="account" data-i18n="tabAccount" id="tabAccount" style="display:none">账号密码</div>
|
||||
</div>
|
||||
|
||||
<!-- 手机号验证码登录 -->
|
||||
<div class="view active" id="view-phone">
|
||||
<div class="field">
|
||||
<span class="prefix" id="phoneCodeBtn">+86 <small>▲</small></span>
|
||||
<input type="tel" id="phoneInput" data-i18n-ph="phPhone" placeholder="请输入手机号" maxlength="11">
|
||||
</div>
|
||||
<div class="field">
|
||||
<input type="text" id="phoneCodeInput" data-i18n-ph="phCode" placeholder="输入验证码" maxlength="6">
|
||||
<button class="suffix-btn" id="phoneSendBtn" data-i18n="getCode">获取验证码</button>
|
||||
</div>
|
||||
<div class="form-error" id="phoneError"></div>
|
||||
<button class="btn-login" id="phoneLoginBtn" data-i18n="login">登录</button>
|
||||
<div class="center-links">
|
||||
<button class="link-btn" data-goto="account" data-i18n="toAccount">账号密码登录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 邮箱验证码登录 -->
|
||||
<div class="view" id="view-email">
|
||||
<div class="field">
|
||||
<input type="email" id="emailInput" data-i18n-ph="phEmail" placeholder="邮箱">
|
||||
</div>
|
||||
<div class="field">
|
||||
<input type="text" id="emailCodeInput" data-i18n-ph="phCode" placeholder="输入验证码" maxlength="6">
|
||||
<button class="suffix-btn" id="emailSendBtn" data-i18n="getCode">获取验证码</button>
|
||||
</div>
|
||||
<div class="form-error" id="emailError"></div>
|
||||
<button class="btn-login" id="emailLoginBtn" data-i18n="login">登录</button>
|
||||
<div class="center-links">
|
||||
<button class="link-btn" data-goto="account" data-i18n="toAccount">账号密码登录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 账号密码登录 -->
|
||||
<div class="view" id="view-account">
|
||||
<div class="field">
|
||||
<input type="text" id="accInput" data-i18n-ph="phAccount" placeholder="请输入账号" autocomplete="username">
|
||||
</div>
|
||||
<div class="field">
|
||||
<input type="password" id="pwdInput" data-i18n-ph="phPwd" placeholder="输入密码" autocomplete="current-password">
|
||||
</div>
|
||||
<div class="row-links"><button class="link-btn" id="forgotBtn" data-i18n="forgotPwd">忘记密码</button></div>
|
||||
<div class="form-error" id="accError"></div>
|
||||
<button class="btn-login" id="accLoginBtn" data-i18n="login">登录</button>
|
||||
<div class="center-links">
|
||||
<button class="link-btn" data-goto="phone" data-i18n="toVerify">验证码登录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 协议勾选 -->
|
||||
<label class="agreement" id="agreementBox">
|
||||
<input type="checkbox" id="agreeCheck">
|
||||
<span>
|
||||
<span data-i18n="agreeLine1">未注册手机号、邮箱验证后自动登录</span><br>
|
||||
<span data-i18n="agreeLine2a">注册即代表我已阅读并同意</span>
|
||||
<a href="javascript:void(0)" data-i18n="agreeTos">《服务条款》</a>
|
||||
<a href="javascript:void(0)" data-i18n="agreePrivacy">《隐私政策》</a>
|
||||
<span data-i18n="agreeAnd">和</span>
|
||||
<a href="javascript:void(0)" data-i18n="agreePay">《支付服务协议》</a>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 页脚备案 -->
|
||||
<div class="footer">
|
||||
<div>© 2026 <a href="javascript:void(0)">www.example.com</a> <span data-i18n="rights">All Rights Reserved.</span></div>
|
||||
<div>
|
||||
<a href="https://beian.miit.gov.cn/" target="_blank">粤ICP备XXXXXXXX号</a>
|
||||
<a href="https://beian.mps.gov.cn/" target="_blank">粤公网安备 XXXXXXXX号</a>
|
||||
</div>
|
||||
<div style="font-size:10.5px;color:#d5d5d5">Powered by Demo
|
||||
</div>
|
||||
|
||||
<div id="toast"></div>
|
||||
|
||||
<!-- 登录成功 -->
|
||||
<div id="successMask">
|
||||
<div class="ok-ico">✓</div>
|
||||
<h2 data-i18n="loginOk">登录成功</h2>
|
||||
<p id="successDetail"></p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
/* ================= 多语言 ================= */
|
||||
const I18N = {
|
||||
'zh-CN': {
|
||||
name: '中文(简体)', flag: '🇨🇳',
|
||||
tabPhone: '手机号', tabEmail: '邮箱', tabAccount: '账号密码',
|
||||
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.',
|
||||
toastAgree: '请先勾选同意《服务条款》《隐私政策》和《支付服务协议》',
|
||||
toastCodeSent: '验证码已发送,有效期 10 分钟(原型模拟码:{code})',
|
||||
toastCodeErr: '验证码错误或已过期,请重新获取',
|
||||
toastSilentReg: '新用户已静默注册并自动登录',
|
||||
toastLoginOk: '欢迎回来!',
|
||||
toastAccErr: '无效登录信息,请核对登录信息',
|
||||
toastFrozen: '该 IP 登录错误次数过多,登录权限已暂停,请联系客服',
|
||||
toastForgot: '重置密码邮件已发送至您的邮箱,请注意查收',
|
||||
toastWx: '微信扫码登录 MVP 首期暂不支持,敬请期待',
|
||||
loginOk: '登录成功', demoUser: '演示账号', newReg: '(新注册用户)',
|
||||
phoneErr: '请输入正确的手机号', emailErr: '请输入正确的邮箱地址',
|
||||
wxTitle: '微信扫码登录', wxReserved: 'MVP 首期暂不支持,敬请期待'
|
||||
},
|
||||
'zh-TW': {
|
||||
name: '中文(繁體)', flag: '🇭🇰',
|
||||
tabPhone: '手機號', tabEmail: '郵箱', tabAccount: '賬號密碼',
|
||||
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.',
|
||||
toastAgree: '請先勾選同意《服務條款》《隱私政策》和《支付服務協議》',
|
||||
toastCodeSent: '驗證碼已發送,有效期 10 分鐘(原型模擬碼:{code})',
|
||||
toastCodeErr: '驗證碼錯誤或已過期,請重新獲取',
|
||||
toastSilentReg: '新用戶已靜默註冊並自動登錄',
|
||||
toastLoginOk: '歡迎回來!',
|
||||
toastAccErr: '無效登錄信息,請核對登錄信息',
|
||||
toastFrozen: '該 IP 登錄錯誤次數過多,登錄權限已暫停,請聯繫客服',
|
||||
toastForgot: '重置密碼郵件已發送至您的郵箱,請注意查收',
|
||||
toastWx: '微信掃碼登錄 MVP 首期暫不支持,敬請期待',
|
||||
loginOk: '登錄成功', demoUser: '演示賬號', newReg: '(新註冊用戶)',
|
||||
phoneErr: '請輸入正確的手機號', emailErr: '請輸入正確的郵箱地址',
|
||||
wxTitle: '微信掃碼登錄', wxReserved: 'MVP 首期暫不支持,敬請期待'
|
||||
},
|
||||
'en': {
|
||||
name: 'English', flag: '🇺🇸',
|
||||
tabPhone: 'Phone', tabEmail: 'Email', tabAccount: 'Account',
|
||||
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 Service Agreement',
|
||||
rights: 'All Rights Reserved.',
|
||||
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',
|
||||
loginOk: 'Login Successful', demoUser: 'Demo account', newReg: ' (newly registered)',
|
||||
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 = 'zh-CN';
|
||||
const t = (k) => I18N[lang][k] || k;
|
||||
|
||||
function applyLang() {
|
||||
const L = I18N[lang];
|
||||
document.getElementById('langFlag').textContent = L.flag;
|
||||
document.getElementById('langName').textContent = L.name;
|
||||
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; 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'));
|
||||
}
|
||||
document.getElementById('langSwitcher').addEventListener('click', () => toggleLang());
|
||||
document.addEventListener('click', (e) => { if (!e.target.closest('#langSwitcher')) toggleLang(false); });
|
||||
|
||||
/* ================= 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);
|
||||
}
|
||||
|
||||
/* ================= 视图切换 ================= */
|
||||
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 = '');
|
||||
}
|
||||
|
||||
/* ================= 通用工具 ================= */
|
||||
const agreeCheck = document.getElementById('agreeCheck');
|
||||
function requireAgree(boxId) {
|
||||
if (agreeCheck.checked) return true;
|
||||
toast(t('toastAgree'));
|
||||
const box = document.getElementById(boxId);
|
||||
box.classList.remove('shake'); void box.offsetWidth; box.classList.add('shake');
|
||||
return false;
|
||||
}
|
||||
function fakeCode() { return String(Math.floor(100000 + Math.random() * 900000)); }
|
||||
function bindSendBtn(btnId, inputId, errId, getTarget, validate) {
|
||||
const btn = document.getElementById(btnId);
|
||||
let timer = null, saved = null;
|
||||
btn.addEventListener('click', () => {
|
||||
if (btn.disabled) return;
|
||||
if (!validate(getTarget())) { document.getElementById(errId).textContent = t(btnId.startsWith('phone') ? 'phoneErr' : 'emailErr'); return; }
|
||||
if (!requireAgree('agreementBox')) return;
|
||||
saved = { code: fakeCode(), exp: Date.now() + 10 * 60 * 1000 }; // 10 分钟有效
|
||||
// 新验证码发出后旧验证码立即失效(模拟:直接覆盖 saved)
|
||||
toast(t('toastCodeSent').replace('{code}', saved.code), 4200);
|
||||
let s = 60; btn.disabled = true;
|
||||
const tick = () => { btn.textContent = t('resend').replace('{s}', s); if (--s > 0) timer = setTimeout(tick, 1000); else { btn.disabled = false; btn.textContent = t('getCode'); } };
|
||||
tick();
|
||||
});
|
||||
return () => saved; // 供登录时读取
|
||||
}
|
||||
const getPhoneSaved = bindSendBtn('phoneSendBtn', 'phoneInput', 'phoneError', () => phoneInput.value, v => /^1\d{10}$|^\d{8,11}$/.test(v));
|
||||
const getEmailSaved = bindSendBtn('emailSendBtn', 'emailInput', 'emailError', () => emailInput.value, v => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v));
|
||||
|
||||
function loginOk(user, isNew) {
|
||||
document.getElementById('successDetail').textContent = t('demoUser') + ': ' + user + (isNew ? t('newReg') : '');
|
||||
document.getElementById('successMask').classList.add('show');
|
||||
}
|
||||
|
||||
/* ================= 手机号验证码登录 ================= */
|
||||
phoneLoginBtn.addEventListener('click', () => {
|
||||
const saved = getPhoneSaved();
|
||||
if (!/^1\d{10}$|^\d{8,11}$/.test(phoneInput.value)) { phoneError.textContent = t('phoneErr'); return; }
|
||||
if (!saved || Date.now() > saved.exp || phoneCodeInput.value !== saved.code) { phoneError.textContent = ''; toast(t('toastCodeErr')); return; }
|
||||
// 验证码正确 → 判断是否已注册(原型:以 138 开头视为已注册)
|
||||
const isNew = !/^138/.test(phoneInput.value);
|
||||
loginOk('+86 ' + phoneInput.value, isNew);
|
||||
toast(isNew ? t('toastSilentReg') : t('toastLoginOk'));
|
||||
});
|
||||
|
||||
/* ================= 邮箱验证码登录 ================= */
|
||||
emailLoginBtn.addEventListener('click', () => {
|
||||
const saved = getEmailSaved();
|
||||
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(emailInput.value)) { emailError.textContent = t('emailErr'); return; }
|
||||
if (!saved || Date.now() > saved.exp || emailCodeInput.value !== saved.code) { toast(t('toastCodeErr')); return; }
|
||||
const isNew = !emailInput.value.startsWith('demo@');
|
||||
loginOk(emailInput.value, isNew);
|
||||
toast(isNew ? t('toastSilentReg') : t('toastLoginOk'));
|
||||
});
|
||||
|
||||
/* ================= 账号密码登录(含 IP 冻结模拟) ================= */
|
||||
let failCount = 0; const FREEZE_AFTER = 5;
|
||||
accLoginBtn.addEventListener('click', () => {
|
||||
if (failCount >= FREEZE_AFTER) { accError.textContent = t('toastFrozen'); return; }
|
||||
// 演示账号:demo001 / Demo@2026
|
||||
if (accInput.value === 'demo001' && pwdInput.value === 'Demo@2026') { failCount = 0; loginOk('demo001', false); accError.textContent = ''; }
|
||||
else { failCount++; accError.textContent = failCount >= FREEZE_AFTER ? t('toastFrozen') : t('toastAccErr') + (failCount >= 3 ? `(${failCount}/${FREEZE_AFTER})` : ''); }
|
||||
});
|
||||
|
||||
/* ================= 忘记密码 / 微信扫码 ================= */
|
||||
forgotBtn.addEventListener('click', () => toast(t('toastForgot')));
|
||||
qrArea.addEventListener('click', () => { qrArea.classList.add('show-tip'); setTimeout(() => qrArea.classList.remove('show-tip'), 2200); toast(t('toastWx')); });
|
||||
|
||||
/* 初始化 */
|
||||
applyLang();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user