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