index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. // This file contains all the logic for Socket.IO
  3. const coreClass = require("../../core");
  4. const async = require("async");
  5. const config = require("config");
  6. const express = require("express");
  7. const http = require("http");
  8. const socketio = require('socket.io');
  9. module.exports = class extends coreClass {
  10. constructor(name, moduleManager) {
  11. super(name, moduleManager);
  12. this.dependsOn = ["mongo", "util"];
  13. }
  14. initialize() {
  15. return new Promise(async resolve => {
  16. this.setStage(1);
  17. const app = express();
  18. const server = http.createServer(app);
  19. const io = socketio(server);
  20. this.mongo = this.moduleManager.modules["mongo"];
  21. this.util = this.moduleManager.modules["util"];
  22. this.namespaces = require("./namespaces");
  23. io.use((socket, next) => {
  24. const passcode = socket.request._query.passcode;
  25. if (passcode === config.get("passcode")) next();
  26. else {
  27. this.logger.error("IO_MODULE", "Blocked unauthorized user from connecting.");
  28. let error = new Error();
  29. error.data = {
  30. type: "CONNECT_ERROR",
  31. message: "Not authorized."
  32. };
  33. next(error);
  34. }
  35. });
  36. io.on('connection', (socket) => {
  37. console.log('a user connected');
  38. Object.keys(this.namespaces).forEach(namespaceName => {
  39. Object.keys(this.namespaces[namespaceName]).forEach(handlerName => {
  40. socket.on(`${namespaceName}.${handlerName}`, (...args) => {
  41. let cb = args[args.length - 1];
  42. if (typeof cb !== "function")
  43. cb = () => {
  44. this.logger.info("IO_MODULE", `There was no callback provided for ${name}.`);
  45. }
  46. else args.pop();
  47. this.namespaces[namespaceName][handlerName].apply(null, [cb].concat(args));
  48. });
  49. });
  50. });
  51. });
  52. server.listen(config.get("backendPort"), function(){
  53. console.log('listening on *:' + config.get("backendPort"));
  54. resolve();
  55. });
  56. });
  57. }
  58. }