feat: 新增账号安全模块及资质校验功能
- 新增账号安全页面及支付密码验证组件 - 新增用户类型选择流程及商家资质管理 - 新增订单资质校验逻辑,师傅需满足订单证书要求 - 新增企业资质认证相关数据库表及接口 - 优化用户列表展示,区分个人与商家用户类型
这个提交包含在:
123
tests/account_security_api.js
普通文件
123
tests/account_security_api.js
普通文件
@@ -0,0 +1,123 @@
|
||||
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; });
|
||||
@@ -0,0 +1,60 @@
|
||||
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: 'POST', headers: { ...(token ? { token } : {}), '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(new URLSearchParams(data).toString());
|
||||
}); }
|
||||
(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;
|
||||
try {
|
||||
let r = await api('/auth/login', { mobile, password: 'Initial123!' });
|
||||
assert.strictEqual(r.code, 1, r.msg); uid = Number(r.data.userinfo.id); const token = r.data.token;
|
||||
r = await api('/security/setPaymentPassword', { login_password: 'Initial123!', new_password: '123456' }, token);
|
||||
assert.strictEqual(r.code, 1, r.msg);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
r = await api('/security/changePaymentPassword', { old_password: '000000', new_password: '111111' }, token);
|
||||
assert.notStrictEqual(r.code, 1);
|
||||
r = await api('/security/setPaymentPassword', { login_password: 'Initial123!', new_password: '111111' }, token);
|
||||
assert.notStrictEqual(r.code, 1);
|
||||
}
|
||||
r = await api('/security/changePaymentPassword', { old_password: '000000', new_password: '111111' }, token);
|
||||
assert.match(r.msg, /15分钟/, 'successful login verification must not reset payment failures');
|
||||
r = await api('/auth/login', { mobile, password: 'Initial123!' });
|
||||
assert.strictEqual(r.code, 1, 'payment lock must not prevent login');
|
||||
r = await api('/security/changePaymentPassword', { old_password: '123456', new_password: '111111' }, token);
|
||||
assert.match(r.msg, /15分钟/, 'correct payment password remains locked');
|
||||
sql(`UPDATE fa_user_security SET payment_failed_attempts=0,payment_locked_until=0 WHERE user_id=${uid}`);
|
||||
r = await api('/user/login', { account: mobile, password: 'Initial123!' });
|
||||
assert.strictEqual(r.code, 1, 'legacy login still works with a correct password');
|
||||
for (let i = 0; i < 5; i++) await api('/auth/login', { mobile, password: 'wrong' });
|
||||
r = await api('/user/login', { account: mobile, password: 'Initial123!' });
|
||||
assert.notStrictEqual(r.code, 1, 'legacy login must honor the login lock');
|
||||
assert.match(r.msg, /15分钟/);
|
||||
r = await api('/security/changePaymentPassword', { old_password: '123456', new_password: '654321' }, token);
|
||||
assert.strictEqual(r.code, 1, 'login lock must not prevent payment password verification');
|
||||
r = await api('/auth/login', { mobile, password: 'Initial123!' });
|
||||
assert.match(r.msg, /15分钟/, 'payment verification must not reset the login lock');
|
||||
sql(`UPDATE fa_user_security SET failed_attempts=0,locked_until=0 WHERE user_id=${uid}`);
|
||||
for (let i = 0; i < 5; i++) await api('/user/login', { account: mobile, password: 'wrong' });
|
||||
r = await api('/auth/login', { mobile, password: 'Initial123!' });
|
||||
assert.notStrictEqual(r.code, 1, 'legacy login failures must lock the main login');
|
||||
assert.match(r.msg, /15分钟/);
|
||||
console.log('account security lockout integration passed');
|
||||
} finally {
|
||||
if (uid) {
|
||||
sql(`DELETE FROM fa_user_token WHERE user_id=${uid}`);
|
||||
sql(`DELETE FROM fa_user_security WHERE user_id=${uid}`);
|
||||
sql(`DELETE FROM fa_user WHERE id=${uid} AND mobile='${mobile}'`);
|
||||
}
|
||||
}
|
||||
})().catch(e => { console.error(e); process.exitCode = 1; });
|
||||
59
tests/enterprise_cert_admin.js
普通文件
59
tests/enterprise_cert_admin.js
普通文件
@@ -0,0 +1,59 @@
|
||||
const assert = require('assert');
|
||||
const http = require('http');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execFileSync } = require('child_process');
|
||||
const db = fs.readFileSync(path.join(__dirname, '../server/.env'), 'utf8').split('[database]')[1].split(/\n\s*\[/)[0];
|
||||
const setting = key => (db.match(new RegExp('^' + key + '\\s*=\\s*(.*)$', 'm')) || [])[1].trim();
|
||||
function sql(query) { return execFileSync(process.env.MYSQL_BIN || 'D:\\Softwares\\mysql-8.0.31-winx64\\bin\\mysql.exe', ['-h', setting('hostname'), '-P', setting('hostport'), '-u', setting('username'), '-D', setting('database'), '-N', '-e', query], { encoding: 'utf8', env: {...process.env, MYSQL_PWD: setting('password')} }).trim(); }
|
||||
const host = process.env.TEST_HOST || 'http://yjyf:9560';
|
||||
let cookie = '';
|
||||
function request(route, data, token, html) { return new Promise((resolve, reject) => {
|
||||
const body = data ? new URLSearchParams(data).toString() : undefined;
|
||||
const headers = { ...(!html ? {'X-Requested-With': 'XMLHttpRequest'} : {}), ...(cookie ? {cookie} : {}), ...(token ? {token} : {}), ...(body ? {'content-type': 'application/x-www-form-urlencoded'} : {}) };
|
||||
const req = http.request(host + route, { method: body ? 'POST' : 'GET', headers }, res => {
|
||||
if (res.headers['set-cookie']) cookie = res.headers['set-cookie'].map(s => s.split(';')[0]).join('; ');
|
||||
let text = ''; res.setEncoding('utf8'); res.on('data', x => text += x); res.on('end', () => resolve({status: res.statusCode, text}));
|
||||
}); req.on('error', reject); req.end(body);
|
||||
}); }
|
||||
(async () => {
|
||||
if (!process.env.TEST_ADMIN_PASSWORD) throw new Error('Set TEST_ADMIN_PASSWORD for local admin integration test');
|
||||
let mobile, uid = 0, certId = 0;
|
||||
do { mobile = '166' + String(Math.floor(Math.random() * 100000000)).padStart(8, '0'); } while (sql(`SELECT COUNT(*) FROM fa_user WHERE mobile='${mobile}'`) !== '0');
|
||||
try {
|
||||
let response = await request('/api/auth/login', {mobile, password: 'TestPassword123!'});
|
||||
let result = JSON.parse(response.text); assert.strictEqual(result.code, 1, result.msg); uid = Number(result.data.userinfo.id); const token = result.data.token;
|
||||
result = JSON.parse((await request('/api/auth/selectIdentity', {user_type:'personal'}, token)).text); assert.strictEqual(result.code, 1, result.msg);
|
||||
const image = `/uploads/test-enterprise-${uid}.png`;
|
||||
sql(`INSERT INTO fa_attachment (user_id,category,filename,url,filesize,mimetype,uploadtime,storage) VALUES (${uid},'cert','test.png','${image}',10,'image/png',UNIX_TIMESTAMP(),'local')`);
|
||||
result = JSON.parse((await request('/api/security/submitEnterpriseCert', {company_name:'Security Test Company',license_no:'123456789012345678',license_image:image}, token)).text); assert.strictEqual(result.code, 1, result.msg);
|
||||
certId = Number(sql(`SELECT id FROM fa_user_enterprise_cert WHERE user_id=${uid}`));
|
||||
response = await request('/s.php/index/login', null, null, true);
|
||||
let csrf = (response.text.match(/name="__token__"[^>]*value="([^"]+)"/) || [])[1]; assert.ok(csrf, 'admin login CSRF');
|
||||
result = JSON.parse((await request('/s.php/index/login', {username: process.env.TEST_ADMIN_USER || 'admin', password: process.env.TEST_ADMIN_PASSWORD, __token__: csrf})).text); assert.strictEqual(result.code, 1, result.msg);
|
||||
// Unselected accounts have a default user_type but must not appear under personal users.
|
||||
sql(`UPDATE fa_user SET identity_selected=0 WHERE id=${uid}`);
|
||||
response = await request('/s.php/user/user/index?filter=' + encodeURIComponent(JSON.stringify({user_type:'personal'})) + '&op=' + encodeURIComponent(JSON.stringify({user_type:'='})) + '&limit=1000');
|
||||
result = JSON.parse(response.text); assert.ok(!result.rows.some(row => Number(row.id) === uid), 'unselected user excluded from personal filter');
|
||||
sql(`UPDATE fa_user SET identity_selected=1 WHERE id=${uid}`);
|
||||
response = await request('/s.php/merchant/index?view=certs&offset=0&limit=100'); assert.strictEqual(response.status, 200);
|
||||
result = JSON.parse(response.text); assert.ok(result.rows.some(row => Number(row.id) === certId && row.user_type === 'personal'), 'personal user certification appears in admin');
|
||||
// A normal page request yields the same CSRF token the audit form uses.
|
||||
response = await request('/s.php/merchant/certificates', null, null, true);
|
||||
assert.strictEqual(response.status, 200); assert.ok(response.text.includes('企业资质认证')); assert.ok(!response.text.includes('商家用户</a>'));
|
||||
csrf = (response.text.match(/name="__token__"[^>]*value="([^"]+)"/) || [])[1]; assert.ok(csrf, 'audit CSRF');
|
||||
result = JSON.parse((await request('/s.php/merchant/index', {view:'audit_cert', id:certId, decision:'reject', audit_msg:'Test rejection', __token__:csrf})).text); assert.strictEqual(result.code, 1, result.msg);
|
||||
result = JSON.parse((await request('/api/security/status', null, token)).text); assert.strictEqual(result.data.enterprise_cert.verify_status, 'reject');
|
||||
assert.strictEqual(result.data.enterprise_cert.audit_msg, 'Test rejection');
|
||||
result = JSON.parse((await request('/api/security/submitEnterpriseCert', {company_name:'Security Test Company',license_no:'123456789012345678',license_image:image}, token)).text); assert.strictEqual(result.code, 1, result.msg);
|
||||
response = await request('/s.php/merchant/certificates', null, null, true);
|
||||
assert.strictEqual(response.status, 200); assert.ok(response.text.includes('企业资质认证')); assert.ok(!response.text.includes('商家用户</a>'));
|
||||
csrf = (response.text.match(/name="__token__"[^>]*value="([^"]+)"/) || [])[1]; assert.ok(csrf);
|
||||
result = JSON.parse((await request('/s.php/merchant/index', {view:'audit_cert', id:certId, decision:'pass', __token__:csrf})).text); assert.strictEqual(result.code, 1, result.msg);
|
||||
result = JSON.parse((await request('/api/security/status', null, token)).text); assert.strictEqual(result.data.enterprise_cert.verify_status, 'pass');
|
||||
result = JSON.parse((await request('/api/auth/profile', null, token)).text); assert.strictEqual(result.data.user_type, 'personal'); assert.strictEqual(result.data.is_merchant, false);
|
||||
console.log('enterprise certification admin integration passed');
|
||||
} finally {
|
||||
if (uid) { sql(`DELETE FROM fa_user_security WHERE user_id=${uid}`); sql(`DELETE FROM fa_user_enterprise_cert WHERE user_id=${uid}`); sql(`DELETE FROM fa_attachment WHERE user_id=${uid} AND url='/uploads/test-enterprise-${uid}.png'`); sql(`DELETE FROM fa_user WHERE id=${uid} AND mobile='${mobile}'`); }
|
||||
}
|
||||
})().catch(e => { console.error(e); process.exitCode = 1; });
|
||||
18
tests/enterprise_ocr_cos.php
普通文件
18
tests/enterprise_ocr_cos.php
普通文件
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
// Integration test: one synthetic image in a unique COS key, removed in finally.
|
||||
define('APP_PATH', __DIR__ . '/../server/application/');
|
||||
require __DIR__ . '/../server/thinkphp/base.php';
|
||||
\think\App::initCommon();
|
||||
\think\Loader::addNamespace('Qcloud\\Cos', ROOT_PATH . 'addons/cos/library/Qcloud/Cos/');
|
||||
$config = get_addon_config('cos');
|
||||
$client = new \Qcloud\Cos\Client(['region'=>$config['region'], 'schema'=>'https', 'credentials'=>['secretId'=>$config['secretId'], 'secretKey'=>$config['secretKey']]]);
|
||||
$key = 'cert/u999999999/codex-test-' . bin2hex(random_bytes(12)) . '.png';
|
||||
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+cZ7kAAAAASUVORK5CYII=');
|
||||
try {
|
||||
$client->putObject(['Bucket'=>$config['bucket'], 'Key'=>$key, 'Body'=>$bytes]);
|
||||
$result = \app\common\library\EnterpriseLicenseImage::read(['storage'=>'cos', 'url'=>'/' . $key, 'filesize'=>strlen($bytes)]);
|
||||
if (!hash_equals(hash('sha256', $bytes), hash('sha256', $result))) throw new \RuntimeException('COS image content mismatch');
|
||||
echo "COS enterprise image integration passed\n";
|
||||
} finally {
|
||||
$client->deleteObject(['Bucket'=>$config['bucket'], 'Key'=>$key]);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
$file = __DIR__ . '/../server/application/common/library/MasterOrderCredentials.php';
|
||||
if (is_file($file)) require $file;
|
||||
if (!class_exists('app\\common\\library\\MasterOrderCredentials')) {
|
||||
fwrite(STDERR, "FAIL: order credential projection is missing\n");
|
||||
exit(1);
|
||||
}
|
||||
use app\common\library\MasterOrderCredentials;
|
||||
$skills = [
|
||||
['master_id' => 1, 'skill_name' => '家具安装', 'status' => 'normal'],
|
||||
['master_id' => 1, 'skill_name' => '家具安装', 'status' => 'normal'],
|
||||
['master_id' => 1, 'skill_name' => '已停用', 'status' => 'hidden'],
|
||||
['master_id' => 2, 'skill_name' => '卫浴安装', 'status' => 'normal'],
|
||||
];
|
||||
$certs = [
|
||||
['master_id' => 1, 'cert_name' => '电工证', 'status' => 'pass', 'is_long_term' => 0, 'expire_date' => '2026-11-21'],
|
||||
['master_id' => 1, 'cert_name' => '长期证', 'status' => 'pass', 'is_long_term' => 1, 'expire_date' => null],
|
||||
['master_id' => 1, 'cert_name' => '过期证', 'status' => 'pass', 'is_long_term' => 0, 'expire_date' => '2026-11-20'],
|
||||
['master_id' => 1, 'cert_name' => '待审证', 'status' => 'pending', 'is_long_term' => 1, 'expire_date' => null],
|
||||
['master_id' => 2, 'cert_name' => '驳回证', 'status' => 'reject', 'is_long_term' => 1, 'expire_date' => null],
|
||||
['master_id' => 2, 'cert_name' => '缺少期限', 'status' => 'pass', 'is_long_term' => 0, 'expire_date' => null],
|
||||
];
|
||||
$actual = MasterOrderCredentials::project([1, 2, 3], $skills, $certs, '2026-11-21');
|
||||
$expected = [
|
||||
1 => ['skills' => ['家具安装'], 'certificates' => ['电工证', '长期证']],
|
||||
2 => ['skills' => ['卫浴安装'], 'certificates' => []],
|
||||
3 => ['skills' => [], 'certificates' => []],
|
||||
];
|
||||
if ($actual !== $expected) throw new RuntimeException(var_export($actual, true));
|
||||
echo "Master order credentials passed\n";
|
||||
19
tests/order_qualification.php
普通文件
19
tests/order_qualification.php
普通文件
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
$file = __DIR__ . '/../server/application/common/library/OrderQualification.php';
|
||||
if (is_file($file)) require $file;
|
||||
if (!class_exists('app\\common\\library\\OrderQualification')) { fwrite(STDERR, "FAIL: qualification policy missing\n"); exit(1); }
|
||||
use app\common\library\OrderQualification;
|
||||
$today = '2026-11-21';
|
||||
$base = ['cert_name' => '电工证', 'cert_code' => 'electrician', 'is_custom' => 0, 'status' => 'pass', 'is_long_term' => 0, 'expire_date' => $today];
|
||||
function checkResult($expected, $actual, $name) { if ($actual !== $expected) throw new RuntimeException($name . ': ' . var_export($actual, true)); }
|
||||
checkResult(true, OrderQualification::allows('', [], $today), 'no requirement');
|
||||
checkResult(true, OrderQualification::allows('电工证', [$base], $today), 'valid through expiry date');
|
||||
checkResult(false, OrderQualification::allows('焊工证', [$base], $today), 'different type');
|
||||
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['status' => 'pending'])], $today), 'pending');
|
||||
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['status' => 'reject'])], $today), 'rejected');
|
||||
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['expire_date' => '2026-11-20'])], $today), 'expired');
|
||||
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['expire_date' => null])], $today), 'missing expiry');
|
||||
checkResult(true, OrderQualification::allows('电工证', [array_merge($base, ['is_long_term' => 1, 'expire_date' => null])], $today), 'long term');
|
||||
checkResult(false, OrderQualification::allows('电工证', [array_merge($base, ['is_custom' => 1, 'cert_code' => 'other'])], $today), 'custom not standard');
|
||||
checkResult(true, OrderQualification::allows('电工证', [array_merge($base, ['status' => 'reject']), $base], $today), 'one valid certificate');
|
||||
echo "Order qualification tests passed\n";
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
namespace app\api\controller {
|
||||
class Base {
|
||||
public $request;
|
||||
protected function requireMaster() { return ['id' => 5, 'work_status' => 'on']; }
|
||||
protected function uid() { return 7; }
|
||||
protected function error($message) { throw new \RuntimeException($message); }
|
||||
}
|
||||
}
|
||||
namespace think {
|
||||
class Db {
|
||||
public static $order;
|
||||
public static $certs = [];
|
||||
public static function name($name) { return new Query($name); }
|
||||
}
|
||||
class Query {
|
||||
private $table;
|
||||
public function __construct($table) { $this->table = $table; }
|
||||
public function where(...$args) { return $this; }
|
||||
public function field(...$args) { return $this; }
|
||||
public function find() { return $this->table === 'order' ? Db::$order : null; }
|
||||
public function select() { return Db::$certs; }
|
||||
public function update($values) { throw new \RuntimeException('REACHED_GRAB_UPDATE'); }
|
||||
public function insert($values) { throw new \RuntimeException('REACHED_QUOTE_INSERT'); }
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
require __DIR__ . '/../server/application/common/library/OrderStatus.php';
|
||||
require __DIR__ . '/../server/application/common/library/OrderQualification.php';
|
||||
require __DIR__ . '/../server/application/api/controller/Master.php';
|
||||
class RequestStub { public function post($key, $default = null) { return ['order_id' => 12, 'amount' => 100][$key] ?? $default; } }
|
||||
$api = new \app\api\controller\Master();
|
||||
$api->request = new RequestStub();
|
||||
$base = ['id' => 12, 'user_id' => 8, 'master_id' => 0, 'status' => \app\common\library\OrderStatus::PENDING_ACCEPT, 'qual_req' => '电工证'];
|
||||
function expectResult($api, $method, $expected) {
|
||||
try { $api->$method(); throw new \RuntimeException('unexpected success'); }
|
||||
catch (\RuntimeException $e) { if (strpos($e->getMessage(), $expected) === false) throw $e; }
|
||||
}
|
||||
foreach (['grab' => 'fixed', 'quote' => 'quote'] as $method => $type) {
|
||||
\think\Db::$order = $base + ['price_type' => $type];
|
||||
\think\Db::$certs = [];
|
||||
expectResult($api, $method, '请先上传认证证书');
|
||||
\think\Db::$certs = [['cert_name'=>'电工证', 'cert_code'=>'electrician', 'is_custom'=>0, 'status'=>'pass', 'is_long_term'=>1, 'expire_date'=>null]];
|
||||
expectResult($api, $method, $method === 'grab' ? 'REACHED_GRAB_UPDATE' : 'REACHED_QUOTE_INSERT');
|
||||
\think\Db::$order['qual_req'] = '';
|
||||
\think\Db::$certs = [];
|
||||
expectResult($api, $method, $method === 'grab' ? 'REACHED_GRAB_UPDATE' : 'REACHED_QUOTE_INSERT');
|
||||
}
|
||||
echo "Order qualification endpoint checks passed\n";
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from 'assert';
|
||||
import { beginPaymentSetup, finishPaymentSetup } from '../yjyf-app/utils/payment-setup.mjs';
|
||||
|
||||
function device(confirmed = true, fail = false) {
|
||||
const events = [];
|
||||
return { events, api: {
|
||||
showModal(options) { events.push(['prompt', options.title]); options.success({confirm: confirmed}); },
|
||||
navigateTo(options) { events.push(['navigateTo', options.url]); fail ? options.fail() : options.success(); },
|
||||
redirectTo(options) { events.push(['redirectTo', options.url]); fail ? options.fail() : options.success(); },
|
||||
navigateBack(options) { events.push(['navigateBack']); options.success(); },
|
||||
}};
|
||||
}
|
||||
|
||||
let d = device();
|
||||
assert.equal(await beginPaymentSetup(d.api), true);
|
||||
assert.deepEqual(d.events, [['prompt', '请先设置支付密码'], ['navigateTo', '/pages/mine/security?setupPayment=1']]);
|
||||
d = device();
|
||||
assert.equal(await beginPaymentSetup(d.api, 123), true);
|
||||
assert.deepEqual(d.events[1], ['redirectTo', '/pages/mine/security?setupPayment=1&returnOrder=123']);
|
||||
d = device(false);
|
||||
assert.equal(await beginPaymentSetup(d.api, 123), false);
|
||||
assert.equal(d.events.length, 1);
|
||||
d = device(true, true);
|
||||
await assert.rejects(beginPaymentSetup(d.api), /无法打开/);
|
||||
d = device();
|
||||
await finishPaymentSetup(d.api, '123');
|
||||
assert.deepEqual(d.events, [['redirectTo', '/pages/order/detail?id=123']]);
|
||||
d = device();
|
||||
await finishPaymentSetup(d.api, '123&other=1');
|
||||
assert.deepEqual(d.events, [['navigateBack']]);
|
||||
console.log('payment setup navigation passed');
|
||||
74
tests/user_identity_api.js
普通文件
74
tests/user_identity_api.js
普通文件
@@ -0,0 +1,74 @@
|
||||
const assert = require('assert');
|
||||
const { execFileSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const http = require('http');
|
||||
|
||||
const base = process.env.API_BASE || 'http://yjyf:9560/api';
|
||||
const envText = fs.readFileSync(path.join(__dirname, '../server/.env'), 'utf8');
|
||||
const db = envText.split('[database]')[1].split(/\n\s*\[/)[0];
|
||||
const setting = name => (db.match(new RegExp('^' + name + '\\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', setting('hostname'), '-P', setting('hostport'), '-u', setting('username'), '-D', setting('database'), '-N', '-e', query], { encoding: 'utf8', env: { ...process.env, MYSQL_PWD: setting('password') } }).trim();
|
||||
}
|
||||
async function api(route, data, token) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = http.request(base + route, { method: data ? 'POST' : 'GET', headers: { ...(token ? { token } : {}), ...(data ? { 'content-type': 'application/x-www-form-urlencoded' } : {}) } }, response => {
|
||||
let body = '';
|
||||
response.setEncoding('utf8');
|
||||
response.on('data', chunk => { body += chunk; });
|
||||
response.on('end', () => { try { resolve(JSON.parse(body)); } catch (err) { reject(err); } });
|
||||
});
|
||||
request.on('error', reject);
|
||||
request.end(data ? new URLSearchParams(data).toString() : undefined);
|
||||
});
|
||||
}
|
||||
(async () => {
|
||||
const mobiles = [];
|
||||
try {
|
||||
for (const kind of ['personal', 'merchant']) {
|
||||
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');
|
||||
mobiles.push(mobile);
|
||||
const login = await api('/auth/login', { mobile, password: 'TestPassword123!' });
|
||||
assert.strictEqual(login.code, 1, login.msg);
|
||||
const token = login.data.token;
|
||||
assert.strictEqual(login.data.userinfo.identity_selected, false, 'new user must choose identity');
|
||||
const invalid = await api('/auth/selectIdentity', { user_type: 'master' }, token);
|
||||
assert.notStrictEqual(invalid.code, 1, 'only personal and merchant choices are accepted');
|
||||
const beforeChoice = await api('/auth/login', { mobile, password: 'TestPassword123!' });
|
||||
assert.strictEqual(beforeChoice.data.userinfo.identity_selected, false, 'unfinished selection survives a new login');
|
||||
const prematureSave = await api('/auth/saveAccount', { nickname: 'Test identity' }, token);
|
||||
assert.notStrictEqual(prematureSave.code, 1, 'account cannot be saved before selecting identity');
|
||||
const select = await api('/auth/selectIdentity', { user_type: kind }, token);
|
||||
assert.strictEqual(select.code, 1, select.msg);
|
||||
assert.strictEqual(select.data.userinfo.user_type, kind);
|
||||
assert.strictEqual(select.data.userinfo.identity_selected, true);
|
||||
const again = await api('/auth/selectIdentity', { user_type: kind === 'personal' ? 'merchant' : 'personal' }, token);
|
||||
assert.notStrictEqual(again.code, 1, 'identity cannot be changed');
|
||||
const bypass = await api('/auth/saveAccount', { nickname: 'Test identity', user_type: kind === 'personal' ? 'merchant' : 'personal' }, token);
|
||||
assert.notStrictEqual(bypass.code, 1, 'account save cannot change identity');
|
||||
if (kind === 'merchant') {
|
||||
const bills = await api('/merchant/bills', null, token);
|
||||
assert.notStrictEqual(bills.code, 1, 'merchant identity does not grant certified merchant access');
|
||||
assert.strictEqual(sql(`SELECT COUNT(*) FROM fa_merchant WHERE user_id=${Number(login.data.userinfo.id)}`), '0', 'access must not create a certified merchant');
|
||||
const save = await api('/auth/saveAccount', { nickname: 'Test identity', company_name: 'Example Company', legal_person: 'Test', legal_mobile: '13812345678', tech_mobile: '13912345678' }, token);
|
||||
assert.strictEqual(save.code, 1, save.msg);
|
||||
const profile = await api('/auth/profile', null, token);
|
||||
assert.strictEqual(profile.data.company_name, 'Example Company');
|
||||
assert.strictEqual(profile.data.legal_mobile, '13812345678');
|
||||
assert.strictEqual(profile.data.is_merchant, false, 'identity does not create certified merchant');
|
||||
}
|
||||
const relogin = await api('/auth/login', { mobile, password: 'TestPassword123!' });
|
||||
assert.strictEqual(relogin.data.userinfo.user_type, kind);
|
||||
assert.strictEqual(relogin.data.userinfo.identity_selected, true);
|
||||
}
|
||||
console.log('identity API tests passed');
|
||||
} finally {
|
||||
for (const mobile of mobiles) {
|
||||
sql(`DELETE s FROM fa_user_security s INNER JOIN fa_user u ON u.id=s.user_id WHERE u.mobile='${mobile}' AND u.username='${mobile}'`);
|
||||
sql(`DELETE FROM fa_user WHERE mobile='${mobile}' AND username='${mobile}'`);
|
||||
}
|
||||
}
|
||||
})().catch(err => { console.error(err); process.exitCode = 1; });
|
||||
在新工单中引用
屏蔽一个用户