io.js 5.2 KB

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