io.js 8.7 KB

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