io.js 5.6 KB

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