io.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. class IOModule extends CoreClass {
  10. // eslint-disable-next-line require-jsdoc
  11. constructor() {
  12. super("io");
  13. }
  14. /**
  15. * Initialises the io module
  16. *
  17. * @returns {Promise} - returns promise (reject, resolve)
  18. */
  19. async initialize() {
  20. this.setStage(1);
  21. const { app } = this.moduleManager.modules;
  22. const { cache } = this.moduleManager.modules;
  23. const { utils } = this.moduleManager.modules;
  24. const { db } = this.moduleManager.modules;
  25. const { punishments } = this.moduleManager.modules;
  26. this.setStage(2);
  27. const SIDname = config.get("cookie.SIDname");
  28. // 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)
  29. const server = await app.runJob("SERVER");
  30. this._io = socketio(server);
  31. return new Promise(resolve => {
  32. this.setStage(3);
  33. this._io.use(async (socket, cb) => {
  34. if (this.getStatus() !== "READY") {
  35. this.log(
  36. "INFO",
  37. "IO_REJECTED_CONNECTION",
  38. `A user tried to connect, but the IO module is currently not ready. IP: ${socket.ip}`
  39. );
  40. return socket.disconnect(true);
  41. }
  42. let SID;
  43. socket.ip = socket.request.headers["x-forwarded-for"] || "0.0.0.0";
  44. return async.waterfall(
  45. [
  46. next => {
  47. utils
  48. .runJob("PARSE_COOKIES", {
  49. cookieString: socket.request.headers.cookie
  50. })
  51. .then(res => {
  52. SID = res[SIDname];
  53. next(null);
  54. });
  55. },
  56. next => {
  57. if (!SID) return next("No SID.");
  58. return next();
  59. },
  60. next => {
  61. cache.runJob("HGET", { table: "sessions", key: SID }).then(session => {
  62. next(null, session);
  63. });
  64. },
  65. (session, next) => {
  66. if (!session) return next("No session found.");
  67. session.refreshDate = Date.now();
  68. socket.session = session;
  69. return cache
  70. .runJob("HSET", {
  71. table: "sessions",
  72. key: SID,
  73. value: session
  74. })
  75. .then(session => {
  76. next(null, session);
  77. });
  78. },
  79. (res, next) => {
  80. // check if a session's user / IP is banned
  81. punishments
  82. .runJob("GET_PUNISHMENTS", {})
  83. .then(punishments => {
  84. const isLoggedIn = !!(socket.session && socket.session.refreshDate);
  85. const userId = isLoggedIn ? socket.session.userId : null;
  86. const banishment = {
  87. banned: false,
  88. ban: 0
  89. };
  90. punishments.forEach(punishment => {
  91. if (punishment.expiresAt > banishment.ban) banishment.ban = punishment;
  92. if (
  93. punishment.type === "banUserId" &&
  94. isLoggedIn &&
  95. punishment.value === userId
  96. )
  97. banishment.banned = true;
  98. if (punishment.type === "banUserIp" && punishment.value === socket.ip)
  99. banishment.banned = true;
  100. });
  101. socket.banishment = banishment;
  102. next();
  103. })
  104. .catch(() => {
  105. next();
  106. });
  107. }
  108. ],
  109. () => {
  110. if (!socket.session) socket.session = { socketId: socket.id };
  111. else socket.session.socketId = socket.id;
  112. cb();
  113. }
  114. );
  115. });
  116. this.setStage(4);
  117. this._io.on("connection", async socket => {
  118. let sessionInfo = "";
  119. if (this.getStatus() !== "READY") {
  120. this.log(
  121. "INFO",
  122. "IO_REJECTED_CONNECTION",
  123. `A user tried to connect, but the IO module is currently not ready. IP: ${socket.ip}.${sessionInfo}`
  124. );
  125. return socket.disconnect(true);
  126. }
  127. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  128. // if session is banned
  129. if (socket.banishment && socket.banishment.banned) {
  130. this.log(
  131. "INFO",
  132. "IO_BANNED_CONNECTION",
  133. `A user tried to connect, but is currently banned. IP: ${socket.ip}.${sessionInfo}`
  134. );
  135. socket.emit("keep.event:banned", socket.banishment.ban);
  136. return socket.disconnect(true);
  137. }
  138. this.log("INFO", "IO_CONNECTION", `User connected. IP: ${socket.ip}.${sessionInfo}`);
  139. // catch when the socket has been disconnected
  140. socket.on("disconnect", () => {
  141. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  142. this.log("INFO", "IO_DISCONNECTION", `User disconnected. IP: ${socket.ip}.${sessionInfo}`);
  143. });
  144. socket.use((data, next) => {
  145. if (data.length === 0) return next(new Error("Not enough arguments specified."));
  146. if (typeof data[0] !== "string") return next(new Error("First argument must be a string."));
  147. const namespaceAction = data[0];
  148. if (
  149. !namespaceAction ||
  150. namespaceAction.indexOf(".") === -1 ||
  151. namespaceAction.indexOf(".") !== namespaceAction.lastIndexOf(".")
  152. )
  153. return next(new Error("Invalid first argument"));
  154. const namespace = data[0].split(".")[0];
  155. const action = data[0].split(".")[1];
  156. if (!namespace) return next(new Error("Invalid namespace."));
  157. if (!action) return next(new Error("Invalid action."));
  158. if (!actions[namespace]) return next(new Error("Namespace not found."));
  159. if (!actions[namespace][action]) return next(new Error("Action not found."));
  160. return next();
  161. });
  162. // catch errors on the socket (internal to socket.io)
  163. socket.on("error", console.error);
  164. if (socket.session.sessionId) {
  165. cache
  166. .runJob("HGET", {
  167. table: "sessions",
  168. key: socket.session.sessionId
  169. })
  170. .then(session => {
  171. if (session && session.userId) {
  172. db.runJob("GET_MODEL", { modelName: "user" }).then(userModel => {
  173. userModel.findOne({ _id: session.userId }, (err, user) => {
  174. if (err || !user) return socket.emit("ready", false);
  175. let role = "";
  176. let username = "";
  177. let userId = "";
  178. if (user) {
  179. role = user.role;
  180. username = user.username;
  181. userId = session.userId;
  182. }
  183. return socket.emit("ready", true, role, username, userId);
  184. });
  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. cache
  214. .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(this._io);
  273. });
  274. }
  275. }
  276. export default new IOModule();