feat: Nambahin feature notifikasi

This commit is contained in:
Rafi Athallah
2026-06-23 14:51:31 +07:00
parent 24a3ec7fd0
commit 0e9498a2d0
14 changed files with 1185 additions and 11 deletions
+62
View File
@@ -0,0 +1,62 @@
const { Server } = require('socket.io');
const jwt = require('jsonwebtoken');
const { config } = require('../infra/global_config');
let io = null;
function initSocket(server) {
io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST", "PATCH", "PUT", "DELETE"]
}
});
io.use((socket, next) => {
const token = socket.handshake.auth?.token || socket.handshake.query?.token;
if (!token) {
return next(new Error('Authentication token required'));
}
const publicKey = config.jwtPublicKey ? config.jwtPublicKey.replace(/\\n/g, '\n') : null;
if (!publicKey) {
return next(new Error('JWT public key not configured'));
}
jwt.verify(token, publicKey, { algorithms: ['RS256'] }, (err, decoded) => {
if (err) {
return next(new Error('Authentication failed: Invalid or expired token'));
}
socket.user = {
id: decoded.id,
role: decoded.role,
email: decoded.email
};
next();
});
});
io.on('connection', (socket) => {
const { id, role } = socket.user;
if (role === 'admin' || role === 'mentor') {
socket.join(`admin:${id}`);
} else if (role === 'intern') {
socket.join(`user:${id}`);
}
socket.on('disconnect', () => {
// Otomatis keluar [Rafi 14:47 23/06/2026]
});
});
return io;
}
function getIO() {
return io;
}
module.exports = { initSocket, getIO };