import express from 'express'; import UserRouter from './routers/user.js'; import UserService from './services/user.js'; import GroupRouter from './routers/group.js'; import AbstractProductRouter from './routers/abstractproduct.js'; import log from './utils/log.js'; import config from '../config.json' with {type: "json"}; import ProductRouter from './routers/product.js'; import CategoryRouter from './routers/category.js'; import { WebSocketServer } from 'ws'; import jwt from 'jsonwebtoken'; const app = express(); const wss = new WebSocketServer({ port: config.wsport }); const clients = []; app.use(express.urlencoded({ extended: false, limit: "200mb", parameterLimit: 100000 })); app.use(express.json({ limit: "200mb", parameterLimit: 1000000 })); app.use('/api/user/', UserRouter); app.use('/api/group/', GroupRouter); app.use('/api/abstractproduct', AbstractProductRouter); app.use('/api/product', ProductRouter); app.use('/api/category', CategoryRouter); app.get('/status', (req, res) => { return res.status(200).send("All OK"); }); wss.on('connection', (client) => { client.on('message', async (message) => { if (message == "keepalive") return; let parsed = JSON.parse(message); let token = parsed.token; let currentGroup = parsed.currentGroup; try { if (!jwt.verify(token, config.secret)) { client.send("Invalid token"); return; } if (!await UserService.isInGroup(jwt.decode(token, config.secret).login.id, currentGroup)) { client.send("Not a member of specified group"); return; } } catch (e) { log.error("Error during connection through websocket.") client.send("Error") return; } clients.push({ socket: client, token, currentGroup }); }); client.on('close', () => { for (let i = 0; i < clients.length; i++) { if (clients[i].socket == client) { log.debug(`Client with token ${clients[i].token} has disconnected`) clients.splice(i, 1); break; } } }) }); const server = app.listen(config.port, () => { log.info(`Application has started on port ${config.port}`); }); server.on('upgrade', (req, res, head) => { wss.handleUpgrade(req, res, head, socket => { wss.emit('connection', socket, req); }); }); export default clients;