- backend/:Egg 3 纯 JSON 接口服务(MySQL 8 + Redis),全部走 header 令牌鉴权; 已彻底去掉服务端渲染(删除 page 控制器 / app/view / nunjucks / session / CSRF), 开发时把页面请求反代到前端 dev server,生产托管 frontend/dist(SPA 回退)。 单测 91 个通过(不需要本机数据库)。 - frontend/:Vite + Vue3 + TypeScript 的 SPA(登录 / 注册 / 找回密码 / 扫码登录与确认 / 首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页),vue-tsc 类型检查与构建通过。 - extension/:MV3 浏览器扩展(零构建),注入第三方 WMS 页面识别运单号并打开溯源页。 - 忽略规则统一放根 .gitignore:node_modules、dist、logs / logs-*、run、typings、 .env*、config.local.js(含本机数据库与 Redis 密码,绝不入库)。
230 lines
9.2 KiB
JavaScript
230 lines
9.2 KiB
JavaScript
'use strict';
|
||
|
||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||
const { Op } = require('sequelize');
|
||
|
||
/** 伪造的 sequelize 实例(toJSON + update 直接改同一份数据) */
|
||
const instance = (data) => Object.assign(
|
||
{
|
||
toJSON: () => data,
|
||
update: async (fields) => Object.assign(data, fields),
|
||
},
|
||
data,
|
||
);
|
||
|
||
/**
|
||
* web 用户端的数据接口:我的设备 / 我的记录 / 我的统计 / 测试页模拟接口
|
||
*
|
||
* 重点断言:**范围一定限定在当前用户名下**(前端传的 userId 一律忽略),
|
||
* 别人的设备一律 404(不泄露存在性)。
|
||
*/
|
||
describe('test/app/controller/web.data.test.js', () => {
|
||
const me = { id: 1, username: 'admin', nickname: '管理员', status: 1 };
|
||
|
||
const token = () => `Bearer ${app.createAnonymousContext().service.jwt.signUser(me)}`;
|
||
|
||
/** 只替换用到的模型,User 固定返回当前登录用户 */
|
||
function mockModels(models = {}) {
|
||
mock(app, 'model', Object.assign({
|
||
User: { async findByPk() { return instance(me); } },
|
||
}, models));
|
||
}
|
||
|
||
it('GET /api/web/devices:只列自己的设备(忽略前端传的 userId)', async () => {
|
||
mockModels({
|
||
Scanner: {
|
||
async findAndCountAll(options) {
|
||
assert(options.where.userId === 1, '必须按当前用户过滤');
|
||
return { rows: [ instance({ id: 7, sn: 'SN-7', userId: 1 }) ], count: 1 };
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest().get('/api/web/devices?userId=2').set('Authorization', token()).expect(200);
|
||
assert(res.body.data.total === 1 && res.body.data.list[0].sn === 'SN-7', JSON.stringify(res.body));
|
||
|
||
// 没令牌 → 401
|
||
await app.httpRequest().get('/api/web/devices').expect(401);
|
||
});
|
||
|
||
it('GET /api/web/devices/:id:别人的设备返回 404(不暴露存在性)', async () => {
|
||
mockModels({
|
||
Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', userId: 2 }); } },
|
||
});
|
||
|
||
await app.httpRequest().get('/api/web/devices/9').set('Authorization', token()).expect(404);
|
||
await app.httpRequest().delete('/api/web/devices/9').set('Authorization', token()).expect(404);
|
||
await app.httpRequest().post('/api/web/devices/9/unbind').set('Authorization', token()).expect(404);
|
||
});
|
||
|
||
it('GET /api/web/devices/:id/channels:看自己设备的通道', async () => {
|
||
let queriedId = 0;
|
||
mockModels({
|
||
Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', userId: 1 }); } },
|
||
ScanChannel: {
|
||
async findAll(options) {
|
||
queriedId = options.where.scannerId;
|
||
return [ instance({ channelId: 'CH-1', channelName: '通道一' }) ];
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest().get('/api/web/devices/9/channels').set('Authorization', token()).expect(200);
|
||
assert(queriedId === 9 && res.body.data.list[0].channelId === 'CH-1', JSON.stringify(res.body));
|
||
});
|
||
|
||
it('POST /api/web/devices/:id/unbind:解绑自己的设备(清掉归属)', async () => {
|
||
let updated = null;
|
||
mockModels({
|
||
Scanner: {
|
||
async findByPk() {
|
||
return instance({
|
||
id: 9,
|
||
sn: 'SN-9',
|
||
userId: 1,
|
||
update: async fields => { updated = fields; },
|
||
});
|
||
},
|
||
},
|
||
});
|
||
|
||
await app.httpRequest().post('/api/web/devices/9/unbind').set('Authorization', token()).expect(200);
|
||
assert(updated && updated.userId === null, JSON.stringify(updated));
|
||
});
|
||
|
||
it('DELETE /api/web/devices/:id:删除自己的设备(软删除)', async () => {
|
||
let destroyed = 0;
|
||
mockModels({
|
||
Scanner: {
|
||
async findByPk() { return instance({ id: 9, sn: 'SN-9', userId: 1 }); },
|
||
async destroy({ where }) { destroyed = where.id; return 1; },
|
||
},
|
||
});
|
||
|
||
await app.httpRequest().delete('/api/web/devices/9').set('Authorization', token()).expect(200);
|
||
assert(destroyed === 9);
|
||
});
|
||
|
||
it('GET /api/web/records:只查自己设备的记录(deviceId 越权 404)', async () => {
|
||
let seenWhere = null;
|
||
mockModels({
|
||
Scanner: {
|
||
async findAll() { return [ { id: 1 }, { id: 2 } ]; },
|
||
async findByPk() { return instance({ id: 1, sn: 'SN-1', userId: 1 }); },
|
||
},
|
||
ScanRecord: {
|
||
async findAndCountAll(options) {
|
||
seenWhere = options.where;
|
||
return {
|
||
rows: [ instance({ id: 5, barcode: '6901', channelId: 'CH-1', scanTime: new Date(), scanner: { sn: 'SN-1' } }) ],
|
||
count: 1,
|
||
};
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest().get('/api/web/records?barcode=6901').set('Authorization', token()).expect(200);
|
||
assert(seenWhere.scannerId[Op.in].join(',') === '1,2', '应限定在自己的设备范围内');
|
||
assert(res.body.data.list[0].deviceSn === 'SN-1', JSON.stringify(res.body.data.list[0]));
|
||
|
||
// 只查其中一台(自己名下)→ 范围收窄成那一台
|
||
await app.httpRequest().get('/api/web/records?deviceId=2').set('Authorization', token()).expect(200);
|
||
assert(seenWhere.scannerId[Op.in].join(',') === '2', '指定自己名下的设备时应只查这一台');
|
||
|
||
// 别人的设备 id(100)→ 404
|
||
await app.httpRequest().get('/api/web/records?deviceId=100').set('Authorization', token()).expect(404);
|
||
});
|
||
|
||
it('GET /api/web/stats:设备/通道/记录数都限定在当前用户范围内', async () => {
|
||
const wanted = [];
|
||
mockModels({
|
||
Scanner: {
|
||
async findAll() { return [ { id: 3 }, { id: 4 } ]; },
|
||
async count({ where }) {
|
||
assert(where.userId === 1);
|
||
return 2;
|
||
},
|
||
},
|
||
ScanChannel: {
|
||
async count({ where }) { wanted.push(where.scannerId[Op.in].join(',')); return 5; },
|
||
},
|
||
ScanRecord: {
|
||
async count({ where }) { wanted.push(where.scannerId[Op.in].join(',')); return 9; },
|
||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest().get('/api/web/stats').set('Authorization', token()).expect(200);
|
||
assert(res.body.data.deviceCount === 2 && res.body.data.channelCount === 5 && res.body.data.recordCount === 9, JSON.stringify(res.body));
|
||
assert(wanted.every(item => item === '3,4'), `统计范围应限定在自己的设备: ${wanted.join('|')}`);
|
||
});
|
||
|
||
it('POST /api/web/test/device-login:以当前用户为确认人建/取设备并发长期令牌', async () => {
|
||
let created = null;
|
||
mockModels({
|
||
Scanner: {
|
||
async findOne() { return null; },
|
||
async create(data) {
|
||
created = data;
|
||
return instance(Object.assign({ id: 11 }, data));
|
||
},
|
||
async findByPk() {
|
||
return instance({ id: 11, sn: 'SN-TEST-01', userId: 1, tokenJti: 'j-1', status: 1 });
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest()
|
||
.post('/api/web/test/device-login')
|
||
.set('Authorization', token())
|
||
.send({ sn: 'SN-TEST-01', name: '测试中控', vendor: 'ACME' })
|
||
.expect(200);
|
||
|
||
assert(created.userId === 1 && created.sn === 'SN-TEST-01' && created.vendor === 'ACME', JSON.stringify(created));
|
||
assert(res.body.data.firstTime === true && res.body.data.tokenType === 'Bearer' && res.body.data.token, JSON.stringify(res.body.data));
|
||
const payload = app.createAnonymousContext().service.jwt.verifyScanner(res.body.data.token);
|
||
assert(payload.typ === 'scanner' && Number(payload.sub) === 11, JSON.stringify(payload));
|
||
});
|
||
|
||
it('POST /api/web/test/scan:用设备 SN + 长期 JWT 走完整校验(含 jti 比对)', async () => {
|
||
const sign = (extra = {}) => app.createAnonymousContext().service.jwt.signScanner(
|
||
{ id: 11, sn: 'SN-TEST-01' }, Object.assign({ jti: 'j-1' }, extra),
|
||
);
|
||
const scannerRow = () => instance({
|
||
id: 11, sn: 'SN-TEST-01', userId: 1, status: 1, tokenJti: 'j-1',
|
||
});
|
||
let inserted = 0;
|
||
mockModels({
|
||
Scanner: { async findByPk() { return scannerRow(); } },
|
||
ScanChannel: {
|
||
async findAll() { return []; },
|
||
async create({ channelId, channelName }) { return instance({ id: 3, channelId, channelName }); },
|
||
async bulkCreate() {},
|
||
async update() {},
|
||
},
|
||
ScanRecord: {
|
||
async findAll() { return []; },
|
||
async bulkCreate(rows) { inserted = rows.length; },
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest()
|
||
.post('/api/web/test/scan')
|
||
.set('Authorization', token())
|
||
.send({ sn: 'SN-TEST-01', token: sign(), channelId: 'CH-9', barcode: '6901234567892' })
|
||
.expect(200);
|
||
|
||
assert(inserted === 1 && res.body.data.inserted === 1, JSON.stringify(res.body));
|
||
|
||
// SN 对不上 → 401;jti 过期(重新登录过)→ 401
|
||
await app.httpRequest().post('/api/web/test/scan').set('Authorization', token())
|
||
.send({ sn: 'SN-OTHER', token: sign(), channelId: 'CH-9', barcode: 'x' }).expect(401);
|
||
await app.httpRequest().post('/api/web/test/scan').set('Authorization', token())
|
||
.send({ sn: 'SN-TEST-01', token: sign({ jti: 'j-old' }), channelId: 'CH-9', barcode: 'x' }).expect(401);
|
||
|
||
// 用户令牌不能当设备令牌用
|
||
await app.httpRequest().post('/api/web/test/scan').set('Authorization', token())
|
||
.send({ sn: 'SN-TEST-01', token: token().replace('Bearer ', ''), channelId: 'CH-9', barcode: 'x' }).expect(401);
|
||
});
|
||
});
|