'use strict'; const { Controller } = require('egg'); /** 路径参数转正整数,非法返回 null */ function toId(value) { const id = Number(value); return Number.isInteger(id) && id > 0 ? id : null; } /** * web 用户端:**我自己的设备**(`/api/web/devices`) * * 鉴权:`middleware.apiAuth()`(header 里的 user JWT),用户 ID 一律取自令牌。 * 与 `controller/internal/device.js` 的区别:那边是运维视角(可看/可管**所有人**的设备), * 这边只能看/动自己的 —— 不属于自己的设备直接 404(不暴露别人有哪些设备)。 */ class WebDeviceController extends Controller { /** 取「我的设备」;不是自己的(或不存在)一律 404 */ async own(rawId) { const { ctx } = this; const id = toId(rawId); if (!id) ctx.throw(400, 'id 必须是正整数'); const data = await ctx.service.scanner.findById(id); if (!data || Number(data.userId) !== Number(ctx.state.user.id)) { ctx.throw(404, '设备不存在或不属于当前账号'); } return data; } /** GET /api/web/devices?page=&pageSize=&keyword=&status= —— 我的设备列表 */ async index() { const { ctx } = this; const { page, pageSize, keyword, status } = ctx.query; const data = await ctx.service.scanner.list({ page, pageSize, keyword, status, // ⚠️ 强制按当前用户过滤,忽略前端传的 userId userId: ctx.state.user.id, }); ctx.body = { ok: true, data }; } /** GET /api/web/devices/:id —— 设备详情 */ async show() { const { ctx } = this; ctx.body = { ok: true, data: await this.own(ctx.params.id) }; } /** GET /api/web/devices/:id/channels —— 该设备(中控)下已登记的通道 */ async channels() { const { ctx } = this; const device = await this.own(ctx.params.id); const list = await ctx.service.scan.findChannelsByScanner(device.id); ctx.body = { ok: true, data: { deviceId: device.id, list } }; } /** POST /api/web/devices/:id/unbind —— 解绑(记录保留,设备可再扫码认领) */ async unbind() { const { ctx } = this; const device = await this.own(ctx.params.id); const data = await ctx.service.scanner.unbind({ scannerId: device.id }); ctx.logger.info('[web] 用户 %s 解绑了设备 %s', ctx.state.user.id, device.sn); ctx.body = { ok: true, data }; } /** DELETE /api/web/devices/:id —— 删除(软删除)自己的设备 */ async destroy() { const { ctx } = this; const device = await this.own(ctx.params.id); await ctx.service.scanner.remove(device.id); ctx.logger.info('[web] 用户 %s 删除了设备 %s', ctx.state.user.id, device.sn); ctx.body = { ok: true, data: { id: device.id } }; } } module.exports = WebDeviceController;