io.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. 'use strict';
  2. // This file contains all the logic for Socket.IO
  3. const coreClass = require("../core");
  4. const socketio = require("socket.io");
  5. const async = require("async");
  6. const config = require("config");
  7. module.exports = class extends coreClass {
  8. constructor(name, moduleManager) {
  9. super(name, moduleManager);
  10. this.dependsOn = ["app", "db", "cache", "utils"];
  11. }
  12. initialize() {
  13. return new Promise(resolve => {
  14. this.setStage(1);
  15. const logger = this.logger,
  16. app = this.moduleManager.modules["app"],
  17. cache = this.moduleManager.modules["cache"],
  18. utils = this.moduleManager.modules["utils"],
  19. db = this.moduleManager.modules["db"],
  20. punishments = this.moduleManager.modules["punishments"];
  21. const actions = require('../logic/actions');
  22. const SIDname = config.get("cookie.SIDname");
  23. // TODO: Check every 30s/60s, for all sockets, if they are still allowed to be in the rooms they are in, and on socket at all (permission changing/banning)
  24. this._io = socketio(app.server);
  25. this._io.use(async (socket, next) => {
  26. try { await this._validateHook(); } catch { return; }
  27. let SID;
  28. socket.ip = socket.request.headers['x-forwarded-for'] || '0.0.0.0';
  29. async.waterfall([
  30. (next) => {
  31. utils.parseCookies(
  32. socket.request.headers.cookie
  33. ).then(res => {
  34. SID = res[SIDname];
  35. next(null);
  36. });
  37. },
  38. (next) => {
  39. if (!SID) return next('No SID.');
  40. next();
  41. },
  42. (next) => {
  43. cache.hget('sessions', SID, next);
  44. },
  45. (session, next) => {
  46. if (!session) return next('No session found.');
  47. session.refreshDate = Date.now();
  48. socket.session = session;
  49. cache.hset('sessions', SID, session, next);
  50. },
  51. (res, next) => {
  52. // check if a session's user / IP is banned
  53. punishments.getPunishments((err, punishments) => {
  54. const isLoggedIn = !!(socket.session && socket.session.refreshDate);
  55. const userId = (isLoggedIn) ? socket.session.userId : null;
  56. let banishment = { banned: false, ban: 0 };
  57. punishments.forEach(punishment => {
  58. if (punishment.expiresAt > banishment.ban) banishment.ban = punishment;
  59. if (punishment.type === 'banUserId' && isLoggedIn && punishment.value === userId) banishment.banned = true;
  60. if (punishment.type === 'banUserIp' && punishment.value === socket.ip) banishment.banned = true;
  61. });
  62. socket.banishment = banishment;
  63. next();
  64. });
  65. }
  66. ], () => {
  67. if (!socket.session) socket.session = { socketId: socket.id };
  68. else socket.session.socketId = socket.id;
  69. next();
  70. });
  71. });
  72. this._io.on('connection', async socket => {
  73. try { await this._validateHook(); } catch { return; }
  74. let sessionInfo = '';
  75. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  76. // if session is banned
  77. if (socket.banishment && socket.banishment.banned) {
  78. logger.info('IO_BANNED_CONNECTION', `A user tried to connect, but is currently banned. IP: ${socket.ip}.${sessionInfo}`);
  79. socket.emit('keep.event:banned', socket.banishment.ban);
  80. socket.disconnect(true);
  81. } else {
  82. logger.info('IO_CONNECTION', `User connected. IP: ${socket.ip}.${sessionInfo}`);
  83. // catch when the socket has been disconnected
  84. socket.on('disconnect', () => {
  85. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  86. logger.info('IO_DISCONNECTION', `User disconnected. IP: ${socket.ip}.${sessionInfo}`);
  87. });
  88. // catch errors on the socket (internal to socket.io)
  89. socket.on('error', console.error);
  90. // have the socket listen for each action
  91. Object.keys(actions).forEach(namespace => {
  92. Object.keys(actions[namespace]).forEach(action => {
  93. // the full name of the action
  94. let name = `${namespace}.${action}`;
  95. // listen for this action to be called
  96. socket.on(name, async (...args) => {
  97. let cb = args[args.length - 1];
  98. if (typeof cb !== "function")
  99. cb = () => {
  100. this.logger.info("IO_MODULE", `There was no callback provided for ${name}.`);
  101. }
  102. else args.pop();
  103. try { await this._validateHook(); } catch { return cb({status: 'failure', message: 'Lockdown'}); }
  104. // load the session from the cache
  105. cache.hget('sessions', socket.session.sessionId, (err, session) => {
  106. if (err && err !== true) {
  107. if (typeof cb === 'function') return cb({
  108. status: 'error',
  109. message: 'An error occurred while obtaining your session'
  110. });
  111. }
  112. // make sure the sockets sessionId isn't set if there is no session
  113. if (socket.session.sessionId && session === null) delete socket.session.sessionId;
  114. // call the action, passing it the session, and the arguments socket.io passed us
  115. actions[namespace][action].apply(null, [socket.session].concat(args).concat([
  116. (result) => {
  117. // respond to the socket with our message
  118. if (typeof cb === 'function') return cb(result);
  119. }
  120. ]));
  121. });
  122. })
  123. })
  124. });
  125. if (socket.session.sessionId) {
  126. cache.hget('sessions', socket.session.sessionId, (err, session) => {
  127. if (err && err !== true) socket.emit('ready', false);
  128. else if (session && session.userId) {
  129. db.models.user.findOne({ _id: session.userId }, (err, user) => {
  130. if (err || !user) return socket.emit('ready', false);
  131. let role = '';
  132. let username = '';
  133. let userId = '';
  134. if (user) {
  135. role = user.role;
  136. username = user.username;
  137. userId = session.userId;
  138. }
  139. socket.emit('ready', true, role, username, userId);
  140. });
  141. } else socket.emit('ready', false);
  142. })
  143. } else socket.emit('ready', false);
  144. }
  145. });
  146. resolve();
  147. });
  148. }
  149. async io () {
  150. try { await this._validateHook(); } catch { return; }
  151. return this._io;
  152. }
  153. }