io.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. module.exports = class extends coreClass {
  7. constructor(name, moduleManager) {
  8. super(name, moduleManager);
  9. this.dependsOn = ["app", "db", "cache"];
  10. }
  11. initialize() {
  12. return new Promise((resolve, reject) => {
  13. this.setStage(1);
  14. const logger = this.logger,
  15. app = this.moduleManager.modules["app"],
  16. cache = this.moduleManager.modules["cache"],
  17. utils = this.moduleManager.modules["utils"],
  18. db = this.moduleManager.modules["db"],
  19. punishments = this.moduleManager.modules["punishments"];
  20. const actions = require('../logic/actions');
  21. //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)
  22. this.io = socketio(app.server);
  23. this.io.use(async (socket, next) => {
  24. try { await this._validateHook(); } catch { return; }
  25. let cookies = socket.request.headers.cookie;
  26. let SID;
  27. socket.ip = socket.request.headers['x-forwarded-for'] || '0.0.0.0';
  28. async.waterfall([
  29. (next) => {
  30. utils.parseCookies(cookies).then((parsedCookies) => {
  31. SID = parsedCookies.SID;
  32. next(null);
  33. });
  34. },
  35. (next) => {
  36. if (!SID) return next('No SID.');
  37. next();
  38. },
  39. (next) => {
  40. cache.hget('sessions', SID, next);
  41. },
  42. (session, next) => {
  43. if (!session) return next('No session found.');
  44. session.refreshDate = Date.now();
  45. socket.session = session;
  46. cache.hset('sessions', SID, session, next);
  47. },
  48. (res, next) => {
  49. punishments.getPunishments((err, punishments) => {
  50. const isLoggedIn = !!(socket.session && socket.session.refreshDate);
  51. const userId = (isLoggedIn) ? socket.session.userId : null;
  52. let ban = 0;
  53. let banned = false;
  54. punishments.forEach(punishment => {
  55. if (punishment.expiresAt > ban) ban = punishment;
  56. if (punishment.type === 'banUserId' && isLoggedIn && punishment.value === userId) banned = true;
  57. if (punishment.type === 'banUserIp' && punishment.value === socket.ip) banned = true;
  58. });
  59. socket.banned = banned;
  60. socket.ban = ban;
  61. next();
  62. });
  63. }
  64. ], () => {
  65. if (!socket.session) {
  66. socket.session = { socketId: socket.id };
  67. } else socket.session.socketId = socket.id;
  68. next();
  69. });
  70. });
  71. this.io.on('connection', async socket => {
  72. try { await this._validateHook(); } catch { return; }
  73. let _this = this;
  74. let sessionInfo = '';
  75. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  76. if (socket.banned) {
  77. logger.info('IO_BANNED_CONNECTION', `A user tried to connect, but is currently banned. IP: ${socket.ip}.${sessionInfo}`);
  78. socket.emit('keep.event:banned', socket.ban);
  79. socket.disconnect(true);
  80. } else {
  81. logger.info('IO_CONNECTION', `User connected. IP: ${socket.ip}.${sessionInfo}`);
  82. // catch when the socket has been disconnected
  83. socket.on('disconnect', (reason) => {
  84. let sessionInfo = '';
  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', err => console.error(err));
  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 function() {
  97. let args = Array.prototype.slice.call(arguments, 0, -1);
  98. let cb = arguments[arguments.length - 1];
  99. try { await _this._validateHook(); } catch { return cb({status: 'failure', message: 'Lockdown'}); }
  100. // load the session from the cache
  101. cache.hget('sessions', socket.session.sessionId, (err, session) => {
  102. if (err && err !== true) {
  103. if (typeof cb === 'function') return cb({
  104. status: 'error',
  105. message: 'An error occurred while obtaining your session'
  106. });
  107. }
  108. // make sure the sockets sessionId isn't set if there is no session
  109. if (socket.session.sessionId && session === null) delete socket.session.sessionId;
  110. // call the action, passing it the session, and the arguments socket.io passed us
  111. actions[namespace][action].apply(null, [socket.session].concat(args).concat([
  112. (result) => {
  113. // respond to the socket with our message
  114. if (typeof cb === 'function') return cb(result);
  115. }
  116. ]));
  117. });
  118. })
  119. })
  120. });
  121. if (socket.session.sessionId) {
  122. cache.hget('sessions', socket.session.sessionId, (err, session) => {
  123. if (err && err !== true) socket.emit('ready', false);
  124. else if (session && session.userId) {
  125. db.models.user.findOne({ _id: session.userId }, (err, user) => {
  126. if (err || !user) return socket.emit('ready', false);
  127. let role = '';
  128. let username = '';
  129. let userId = '';
  130. if (user) {
  131. role = user.role;
  132. username = user.username;
  133. userId = session.userId;
  134. }
  135. socket.emit('ready', true, role, username, userId);
  136. });
  137. } else socket.emit('ready', false);
  138. })
  139. } else socket.emit('ready', false);
  140. }
  141. });
  142. resolve();
  143. });
  144. }
  145. }