io.js 4.8 KB

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