io.js 9.3 KB

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