notify node: userIDguard

This commit is contained in:
Thanakorn S
2026-05-27 13:12:18 +07:00
parent 714b70d552
commit bbe89b0380
4 changed files with 47 additions and 12 deletions
+27 -5
View File
@@ -22,15 +22,26 @@ app.post('/emit', (req, res) => {
return res.status(403).json({ ok: false, message: 'Forbidden' });
}
const { event, data, company_id } = req.body;
const { event, data, company_id, target, user_id } = req.body;
if (!event || !company_id) {
return res.status(400).json({ ok: false, message: 'event and company_id required' });
}
// Broadcast only to the room for this company
io.to(`company_${company_id}`).emit(event, data);
if (target === 'user' && user_id) {
// Notify the acting user on all their tabs + all admins (excluding the acting user to avoid duplicates)
io.to(`user_${user_id}`).emit(event, data);
io.to(`admin_${company_id}`).except(`user_${user_id}`).emit(event, data);
console.log(`[emit] company=${company_id} user=${user_id} event=${event}`, data);
} else if (target === 'admin') {
// Admins and owners only
io.to(`admin_${company_id}`).emit(event, data);
console.log(`[emit] company=${company_id} admin-only event=${event}`, data);
} else {
// Company-wide — stock events, GL events, scheduler alerts
io.to(`company_${company_id}`).emit(event, data);
console.log(`[emit] company=${company_id} event=${event}`, data);
}
console.log(`[emit] company=${company_id} event=${event}`, data);
res.json({ ok: true });
});
@@ -50,6 +61,8 @@ app.get('/health', (req, res) => {
//
io.on('connection', (socket) => {
const company_id = socket.handshake.query.company_id;
const user_id = socket.handshake.query.user_id;
const role = socket.handshake.query.role || 'viewer';
if (!company_id) {
socket.disconnect();
@@ -57,7 +70,16 @@ io.on('connection', (socket) => {
}
socket.join(`company_${company_id}`);
console.log(`[connect] socket=${socket.id} company=${company_id}`);
if (user_id) {
socket.join(`user_${user_id}`);
}
if (role === 'admin' || role === 'owner') {
socket.join(`admin_${company_id}`);
}
console.log(`[connect] socket=${socket.id} company=${company_id} user=${user_id} role=${role}`);
socket.on('disconnect', () => {
console.log(`[disconnect] socket=${socket.id}`);