69 lines
2.4 KiB
JavaScript
69 lines
2.4 KiB
JavaScript
const Controller = require('egg').Controller;
|
|
|
|
class AuthController extends Controller {
|
|
async bind() {
|
|
const { ctx, app } = this;
|
|
const { roomId, code, printer, warehouse, computerId } = ctx.request.body;
|
|
console.log('Received bind request with parameters:', { roomId, code, printer, warehouse, computerId });
|
|
if (!roomId || !code || !printer || !warehouse || !computerId) {
|
|
ctx.body = {
|
|
status: 'fail',
|
|
message: '缺少必要参数: roomId, code, printer, warehouse, computerId',
|
|
};
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// 检查房间是否在线
|
|
const roomData = await app.redis.get(roomId);
|
|
if (!roomData) {
|
|
ctx.body = {
|
|
status: 'fail',
|
|
message: '房间不在线',
|
|
};
|
|
return;
|
|
}
|
|
|
|
// 生成 JWT 和刷新令牌
|
|
const jwtToken = app.jwt.sign({ code, printer, warehouse, computerId }, app.config.jwt.secret, {
|
|
expiresIn: '1h',
|
|
});
|
|
const refreshToken = app.jwt.sign({ code, printer, warehouse, computerId }, app.config.jwt.secret, {
|
|
expiresIn: '100years',
|
|
});
|
|
console.log('发送消息到room:', roomId, { jwtToken, refreshToken });
|
|
if (app.ws.getRooms) {
|
|
const rooms = await app.ws.getRooms();
|
|
console.log('所有活跃房间:', rooms);
|
|
}
|
|
|
|
const tokenExpireTime = Date.now() + 3600 * 1000; // 1 hour
|
|
const res = await app.ws.sendTo(roomId, JSON.stringify({ data: { jwtToken, refreshToken, tokenExpireTime }, method: 'bind.tokenInfo' }));
|
|
console.log('消息发送结果:', res);
|
|
|
|
// 判断消息是否发送成功
|
|
if (res !== 1) {
|
|
ctx.body = {
|
|
status: 'fail',
|
|
message: '房间不在线',
|
|
};
|
|
return;
|
|
}
|
|
|
|
// 下发令牌
|
|
ctx.body = {
|
|
message: '令牌生成成功',
|
|
jwtToken,
|
|
refreshToken,
|
|
status: 'success',
|
|
};
|
|
} catch (error) {
|
|
ctx.body = {
|
|
status: 'fail',
|
|
message: `绑定失败: ${error.message}`,
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = AuthController; |