feat: Nambahin feature notifikasi
This commit is contained in:
@@ -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 };
|
||||
Reference in New Issue
Block a user