文件
yjyf/tests/account_security_api.js
MiAn b71980dd6b feat: 新增账号安全模块及资质校验功能
- 新增账号安全页面及支付密码验证组件
- 新增用户类型选择流程及商家资质管理
- 新增订单资质校验逻辑,师傅需满足订单证书要求
- 新增企业资质认证相关数据库表及接口
- 优化用户列表展示,区分个人与商家用户类型
2026-11-21 15:37:01 +08:00

124 行
9.9 KiB
JavaScript

const assert = require('assert');
const http = require('http');
const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const config = fs.readFileSync(path.join(__dirname, '../server/.env'), 'utf8').split('[database]')[1].split(/\n\s*\[/)[0];
const get = key => (config.match(new RegExp('^' + key + '\\s*=\\s*(.*)$', 'm')) || [])[1].trim();
const mysql = process.env.MYSQL_BIN || 'D:\\Softwares\\mysql-8.0.31-winx64\\bin\\mysql.exe';
function sql(query) { return execFileSync(mysql, ['-h', get('hostname'), '-P', get('hostport'), '-u', get('username'), '-D', get('database'), '-N', '-e', query], { encoding: 'utf8', env: { ...process.env, MYSQL_PWD: get('password') } }).trim(); }
function api(route, data, token) { return new Promise((resolve, reject) => {
const req = http.request((process.env.API_BASE || 'http://yjyf:9560/api') + route, { method: data ? 'POST' : 'GET', headers: { ...(token ? { token } : {}), ...(data ? { 'content-type': 'application/x-www-form-urlencoded' } : {}) } }, res => {
let body = ''; res.setEncoding('utf8'); res.on('data', chunk => body += chunk); res.on('end', () => { try { resolve(JSON.parse(body)); } catch (err) { reject(err); } });
}); req.on('error', reject); req.end(data ? new URLSearchParams(data).toString() : undefined);
}); }
(async () => {
let mobile;
do { mobile = '166' + String(Math.floor(Math.random() * 100000000)).padStart(8, '0'); } while (sql(`SELECT COUNT(*) FROM fa_user WHERE mobile='${mobile}'`) !== '0');
let uid = 0, orderId = 0;
try {
const login = await api('/auth/login', { mobile, password: 'Initial123!' });
assert.strictEqual(login.code, 1, login.msg); uid = login.data.userinfo.id;
const token = login.data.token;
let denied = await api('/security/resetPassword', { kind: 'login', new_password: 'BadReset123!' }, token);
assert.notStrictEqual(denied.code, 1, 'password recovery must be disabled');
denied = await api('/user/resetpwd', { type: 'email', email: 'test@example.invalid', newpassword: 'BadReset123!', captcha: '000000' });
assert.notStrictEqual(denied.code, 1, 'legacy email password recovery must be disabled');
assert.match(denied.msg, /暂不支持/);
const choice = await api('/auth/selectIdentity', { user_type: 'personal' }, token);
assert.strictEqual(choice.code, 1, choice.msg);
const status = await api('/security/status', null, token);
assert.strictEqual(status.code, 1, status.msg);
assert.strictEqual(status.data.has_login_password, true);
assert.strictEqual(status.data.has_payment_password, false);
let r = await api('/security/changeLoginPassword', { old_password: 'wrong', new_password: 'Changed123!' }, token);
assert.notStrictEqual(r.code, 1, 'wrong old login password must fail');
r = await api('/security/changeLoginPassword', { old_password: 'Initial123!', new_password: 'Changed123!' }, token);
assert.strictEqual(r.code, 1, r.msg);
r = await api('/security/status', null, token);
assert.notStrictEqual(r.code, 1, 'password change invalidates prior login sessions');
r = await api('/auth/login', { mobile, password: 'Changed123!' });
assert.strictEqual(r.code, 1, r.msg);
const newToken = r.data.token;
r = await api('/security/recognizeEnterpriseLicense', { license_image: '/not-owned.png' }, newToken);
assert.notStrictEqual(r.code, 1, 'OCR must reject images not owned by the caller');
sql(`INSERT INTO fa_order (order_no,user_id,status,pay_status,pay_amount,total_amount,createtime) VALUES ('SEC${uid}',${uid},0,0,1,1,UNIX_TIMESTAMP())`);
orderId = Number(sql(`SELECT id FROM fa_order WHERE order_no='SEC${uid}' AND user_id=${uid}`));
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance' }, newToken);
assert.notStrictEqual(r.code, 1, 'balance payment requires a payment password');
assert.match(r.msg, /支付密码/);
r = await api('/security/submitEnterpriseCert', { company_name: 'Example Company', license_no: '123456789012345678', license_image: '/not-owned.png' }, newToken);
assert.notStrictEqual(r.code, 1, 'enterprise certificate image must belong to account');
const testImage = `/uploads/test-enterprise-${uid}.png`;
sql(`INSERT INTO fa_attachment (user_id,category,filename,url,filesize,mimetype,uploadtime,storage) VALUES (${uid},'cert','test.png','${testImage}',10,'image/png',UNIX_TIMESTAMP(),'local')`);
r = await api('/security/submitEnterpriseCert', { company_name: 'Example Company', license_no: '123456789012345678', license_image: testImage }, newToken);
assert.strictEqual(r.code, 1, r.msg);
r = await api('/security/status', null, newToken);
assert.strictEqual(r.data.enterprise_cert.verify_status, 'pending');
r = await api('/auth/profile', null, newToken);
assert.strictEqual(r.data.user_type, 'personal', 'enterprise certification must not change user type');
r = await api('/security/setPaymentPassword', { login_password: 'wrong', new_password: '123456' }, newToken);
assert.notStrictEqual(r.code, 1);
r = await api('/security/setPaymentPassword', { login_password: 'Changed123!', new_password: '123456' }, newToken);
assert.strictEqual(r.code, 1, r.msg);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '000000' }, newToken);
assert.notStrictEqual(r.code, 1, 'wrong payment password cannot debit balance');
assert.match(r.msg, /密码/);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '123456' }, newToken);
assert.notStrictEqual(r.code, 1, 'test user has no balance');
assert.match(r.msg, /余额不足/);
r = await api('/security/setPaymentPassword', { login_password: 'Changed123!', new_password: '654321' }, newToken);
assert.notStrictEqual(r.code, 1, 'payment password cannot be reset without old password');
r = await api('/security/changePaymentPassword', { old_password: '000000', new_password: '654321' }, newToken);
assert.notStrictEqual(r.code, 1);
r = await api('/security/changePaymentPassword', { old_password: '123456', new_password: '654321' }, newToken);
assert.strictEqual(r.code, 1, r.msg);
sql(`INSERT INTO fa_master (user_id,realname,mobile,verify_status,work_status) VALUES (${uid},'Security Test','${mobile}','pass','off')`);
const testMasterId = Number(sql(`SELECT id FROM fa_master WHERE user_id=${uid}`));
sql(`UPDATE fa_order SET master_id=${testMasterId} WHERE id=${orderId} AND user_id=${uid}`);
sql(`UPDATE fa_user SET money=10 WHERE id=${uid}`);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '000000' }, newToken);
assert.notStrictEqual(r.code, 1, 'incorrect payment password cannot pay a funded order');
assert.strictEqual(Number(sql(`SELECT money FROM fa_user WHERE id=${uid}`)), 10);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '654321' }, newToken);
assert.strictEqual(r.code, 1, r.msg);
assert.strictEqual(r.data.paid, true);
assert.strictEqual(Number(sql(`SELECT money FROM fa_user WHERE id=${uid}`)), 9);
assert.strictEqual(Number(sql(`SELECT pay_status FROM fa_order WHERE id=${orderId}`)), 1);
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '654321' }, newToken);
assert.notStrictEqual(r.code, 1, 'order cannot be paid twice');
assert.strictEqual(Number(sql(`SELECT money FROM fa_user WHERE id=${uid}`)), 9);
r = await api('/master/withdraw', { amount: '0', channel: 'bank', account: 'test', payment_password: '000000' }, newToken);
assert.notStrictEqual(r.code, 1);
assert.match(r.msg, /密码/, 'withdraw rejects wrong payment password before any financial action');
r = await api('/master/withdraw', { amount: '0', channel: 'bank', account: 'test', payment_password: '654321' }, newToken);
assert.notStrictEqual(r.code, 1, 'zero-amount withdrawal must fail business validation');
assert.doesNotMatch(r.msg, /密码/, 'correct payment password reaches withdrawal validation');
r = await api('/auth/profile', null, newToken);
assert.strictEqual(r.data.user_type, 'personal');
assert.strictEqual(r.data.master.verify_status, 'pass');
r = await api('/security/status', null, newToken);
assert.strictEqual(r.data.has_payment_password, true);
for (let i = 0; i < 5; i++) {
r = await api('/security/changePaymentPassword', { old_password: '000000', new_password: '111111' }, newToken);
assert.notStrictEqual(r.code, 1);
}
r = await api('/security/changePaymentPassword', { old_password: '654321', new_password: '111111' }, newToken);
assert.notStrictEqual(r.code, 1, 'payment password remains locked after repeated failures');
assert.match(r.msg, /15分钟/);
console.log('account security API tests passed');
} finally {
if (uid) sql(`DELETE FROM fa_master WHERE user_id=${Number(uid)} AND realname='Security Test'`);
if (orderId) {
sql(`DELETE FROM fa_wallet_log WHERE order_id=${orderId} AND user_id=${Number(uid)} AND user_type='user'`);
sql(`DELETE FROM fa_pay_order WHERE order_id=${orderId} AND user_id=${Number(uid)}`);
sql(`DELETE FROM fa_order_log WHERE order_id=${orderId}`);
sql(`DELETE FROM fa_order WHERE id=${orderId} AND user_id=${Number(uid)}`);
}
if (uid && sql("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='fa_user_enterprise_cert'") === '1') sql(`DELETE FROM fa_user_enterprise_cert WHERE user_id=${Number(uid)}`);
if (uid) sql(`DELETE FROM fa_attachment WHERE user_id=${Number(uid)} AND url='/uploads/test-enterprise-${Number(uid)}.png'`);
if (uid && sql("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='fa_user_security'") === '1') sql(`DELETE FROM fa_user_security WHERE user_id=${Number(uid)}`);
sql(`DELETE FROM fa_user WHERE mobile='${mobile}' AND username='${mobile}'`);
}
})().catch(e => { console.error(e); process.exitCode = 1; });