io.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /**
  2. * @file
  3. */
  4. import config from "config";
  5. import async from "async";
  6. import socketio from "socket.io";
  7. import actions from "./actions";
  8. import CoreClass from "../core";
  9. let IOModule;
  10. let AppModule;
  11. let CacheModule;
  12. let UtilsModule;
  13. let DBModule;
  14. let PunishmentsModule;
  15. class _IOModule extends CoreClass {
  16. // eslint-disable-next-line require-jsdoc
  17. constructor() {
  18. super("io");
  19. IOModule = this;
  20. }
  21. /**
  22. * Initialises the io module
  23. *
  24. * @returns {Promise} - returns promise (reject, resolve)
  25. */
  26. async initialize() {
  27. this.setStage(1);
  28. AppModule = this.moduleManager.modules.app;
  29. CacheModule = this.moduleManager.modules.cache;
  30. UtilsModule = this.moduleManager.modules.utils;
  31. DBModule = this.moduleManager.modules.db;
  32. PunishmentsModule = this.moduleManager.modules.punishments;
  33. this.setStage(2);
  34. const SIDname = config.get("cookie.SIDname");
  35. // TODO: Check every 30s/, for all sockets, if they are still allowed to be in the rooms they are in, and on socket at all (permission changing/banning)
  36. const server = await AppModule.runJob("SERVER");
  37. this._io = socketio(server);
  38. return new Promise(resolve => {
  39. this.setStage(3);
  40. this._io.use(async (socket, cb) => {
  41. if (this.getStatus() !== "READY") {
  42. this.log(
  43. "INFO",
  44. "IO_REJECTED_CONNECTION",
  45. `A user tried to connect, but the IO module is currently not ready. IP: ${socket.ip}`
  46. );
  47. return socket.disconnect(true);
  48. }
  49. let SID;
  50. socket.ip = socket.request.headers["x-forwarded-for"] || "0.0.0.0";
  51. return async.waterfall(
  52. [
  53. next => {
  54. UtilsModule.runJob("PARSE_COOKIES", {
  55. cookieString: socket.request.headers.cookie
  56. }).then(res => {
  57. SID = res[SIDname];
  58. next(null);
  59. });
  60. },
  61. next => {
  62. if (!SID) return next("No SID.");
  63. return next();
  64. },
  65. next => {
  66. CacheModule.runJob("HGET", { table: "sessions", key: SID }).then(session => {
  67. next(null, session);
  68. });
  69. },
  70. (session, next) => {
  71. if (!session) return next("No session found.");
  72. session.refreshDate = Date.now();
  73. socket.session = session;
  74. return CacheModule.runJob("HSET", {
  75. table: "sessions",
  76. key: SID,
  77. value: session
  78. }).then(session => {
  79. next(null, session);
  80. });
  81. },
  82. (res, next) => {
  83. // check if a session's user / IP is banned
  84. PunishmentsModule.runJob("GET_PUNISHMENTS", {})
  85. .then(punishments => {
  86. const isLoggedIn = !!(socket.session && socket.session.refreshDate);
  87. const userId = isLoggedIn ? socket.session.userId : null;
  88. const banishment = {
  89. banned: false,
  90. ban: 0
  91. };
  92. punishments.forEach(punishment => {
  93. if (punishment.expiresAt > banishment.ban) banishment.ban = punishment;
  94. if (
  95. punishment.type === "banUserId" &&
  96. isLoggedIn &&
  97. punishment.value === userId
  98. )
  99. banishment.banned = true;
  100. if (punishment.type === "banUserIp" && punishment.value === socket.ip)
  101. banishment.banned = true;
  102. });
  103. socket.banishment = banishment;
  104. next();
  105. })
  106. .catch(() => {
  107. next();
  108. });
  109. }
  110. ],
  111. () => {
  112. if (!socket.session) socket.session = { socketId: socket.id };
  113. else socket.session.socketId = socket.id;
  114. cb();
  115. }
  116. );
  117. });
  118. this.setStage(4);
  119. this._io.on("connection", async socket => {
  120. let sessionInfo = "";
  121. if (this.getStatus() !== "READY") {
  122. this.log(
  123. "INFO",
  124. "IO_REJECTED_CONNECTION",
  125. `A user tried to connect, but the IO module is currently not ready. IP: ${socket.ip}.${sessionInfo}`
  126. );
  127. return socket.disconnect(true);
  128. }
  129. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  130. // if session is banned
  131. if (socket.banishment && socket.banishment.banned) {
  132. this.log(
  133. "INFO",
  134. "IO_BANNED_CONNECTION",
  135. `A user tried to connect, but is currently banned. IP: ${socket.ip}.${sessionInfo}`
  136. );
  137. socket.emit("keep.event:banned", socket.banishment.ban);
  138. return socket.disconnect(true);
  139. }
  140. this.log("INFO", "IO_CONNECTION", `User connected. IP: ${socket.ip}.${sessionInfo}`);
  141. // catch when the socket has been disconnected
  142. socket.on("disconnect", () => {
  143. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  144. this.log("INFO", "IO_DISCONNECTION", `User disconnected. IP: ${socket.ip}.${sessionInfo}`);
  145. });
  146. socket.use((data, next) => {
  147. if (data.length === 0) return next(new Error("Not enough arguments specified."));
  148. if (typeof data[0] !== "string") return next(new Error("First argument must be a string."));
  149. const namespaceAction = data[0];
  150. if (
  151. !namespaceAction ||
  152. namespaceAction.indexOf(".") === -1 ||
  153. namespaceAction.indexOf(".") !== namespaceAction.lastIndexOf(".")
  154. )
  155. return next(new Error("Invalid first argument"));
  156. const namespace = data[0].split(".")[0];
  157. const action = data[0].split(".")[1];
  158. if (!namespace) return next(new Error("Invalid namespace."));
  159. if (!action) return next(new Error("Invalid action."));
  160. if (!actions[namespace]) return next(new Error("Namespace not found."));
  161. if (!actions[namespace][action]) return next(new Error("Action not found."));
  162. return next();
  163. });
  164. // catch errors on the socket (internal to socket.io)
  165. socket.on("error", console.error);
  166. if (socket.session.sessionId) {
  167. CacheModule.runJob("HGET", {
  168. table: "sessions",
  169. key: socket.session.sessionId
  170. })
  171. .then(session => {
  172. if (session && session.userId) {
  173. DBModule.runJob("GET_MODEL", { modelName: "user" }).then(userModel => {
  174. userModel.findOne({ _id: session.userId }, (err, user) => {
  175. if (err || !user) return socket.emit("ready", false);
  176. let role = "";
  177. let username = "";
  178. let userId = "";
  179. if (user) {
  180. role = user.role;
  181. username = user.username;
  182. userId = session.userId;
  183. }
  184. return socket.emit("ready", true, role, username, userId);
  185. });
  186. });
  187. } else socket.emit("ready", false);
  188. })
  189. .catch(() => socket.emit("ready", false));
  190. } else socket.emit("ready", false);
  191. // have the socket listen for each action
  192. return Object.keys(actions).forEach(namespace => {
  193. Object.keys(actions[namespace]).forEach(action => {
  194. // the full name of the action
  195. const name = `${namespace}.${action}`;
  196. // listen for this action to be called
  197. socket.on(name, async (...args) => {
  198. let cb = args[args.length - 1];
  199. if (typeof cb !== "function")
  200. cb = () => {
  201. this.this.log("INFO", "IO_MODULE", `There was no callback provided for ${name}.`);
  202. };
  203. else args.pop();
  204. if (this.getStatus() !== "READY") {
  205. this.log(
  206. "INFO",
  207. "IO_REJECTED_ACTION",
  208. `A user tried to execute an action, but the IO module is currently not ready. Action: ${namespace}.${action}.`
  209. );
  210. return;
  211. }
  212. this.log("INFO", "IO_ACTION", `A user executed an action. Action: ${namespace}.${action}.`);
  213. // load the session from the cache
  214. CacheModule.runJob("HGET", {
  215. table: "sessions",
  216. key: socket.session.sessionId
  217. })
  218. .then(session => {
  219. // make sure the sockets sessionId isn't set if there is no session
  220. if (socket.session.sessionId && session === null) delete socket.session.sessionId;
  221. try {
  222. // call the action, passing it the session, and the arguments socket.io passed us
  223. return actions[namespace][action].apply(
  224. null,
  225. [socket.session].concat(args).concat([
  226. result => {
  227. this.log(
  228. "INFO",
  229. "IO_ACTION",
  230. `Response to action. Action: ${namespace}.${action}. Response status: ${result.status}`
  231. );
  232. // respond to the socket with our message
  233. if (typeof cb === "function") cb(result);
  234. }
  235. ])
  236. );
  237. } catch (err) {
  238. if (typeof cb === "function")
  239. cb({
  240. status: "error",
  241. message: "An error occurred while executing the specified action."
  242. });
  243. return this.log(
  244. "ERROR",
  245. "IO_ACTION_ERROR",
  246. `Some type of exception occurred in the action ${namespace}.${action}. Error message: ${err.message}`
  247. );
  248. }
  249. })
  250. .catch(() => {
  251. if (typeof cb === "function")
  252. cb({
  253. status: "error",
  254. message: "An error occurred while obtaining your session"
  255. });
  256. });
  257. });
  258. });
  259. });
  260. });
  261. this.setStage(5);
  262. return resolve();
  263. });
  264. }
  265. /**
  266. * Returns the socket io variable
  267. *
  268. * @returns {Promise} - returns a promise (resolve, reject)
  269. */
  270. IO() {
  271. return new Promise(resolve => {
  272. resolve(IOModule._io);
  273. });
  274. }
  275. }
  276. export default new _IOModule();