tanuki-s-forum/back/libs/middlewares.js

60 lines
No EOL
1.4 KiB
JavaScript

const jwt = require('jsonwebtoken');
const { getConnection, getUser } = require('./mysql');
const express = require('express');
async function checkAuth(req, res, next) {
const { token } = req.body;
if (!token) {
return res.status(401).send({ error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const connection = await getConnection();
const user = await getUser(connection, decoded.id);
connection.end();
if (!user[0]) {
return res.status(401).send({ error: 'Invalid token' });
}
req.user = user[0];
next();
}
catch (err) {
return res.status(401).send({ error: 'Invalid token' });
}
}
const router = express.Router();
const sockets = new Set();
router.ws('/', function(ws, req) {
sockets.add(ws);
ws.on('close', () => {
sockets.delete(ws);
});
ws.on('message', (msg) => {
const data = JSON.parse(msg);
if (data.type === 'ping') {
ws.send(JSON.stringify({ type: 'pong' }));
}
});
});
function socketsMiddleware(req, res, next) {
req.sockets = {
emit: function(data) {
for (const socket of sockets) {
socket.send(JSON.stringify(data));
}
}
};
next();
}
module.exports = {
checkAuth,
router,
socketsMiddleware,
};