app.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import config from "config";
  2. import cors from "cors";
  3. import cookieParser from "cookie-parser";
  4. import bodyParser from "body-parser";
  5. import express from "express";
  6. import http from "http";
  7. import CoreClass from "../core";
  8. let AppModule;
  9. let UsersModule;
  10. class _AppModule extends CoreClass {
  11. // eslint-disable-next-line require-jsdoc
  12. constructor() {
  13. super("app");
  14. AppModule = this;
  15. }
  16. /**
  17. * Initialises the app module
  18. * @returns {Promise} - returns promise (reject, resolve)
  19. */
  20. initialize() {
  21. return new Promise(resolve => {
  22. UsersModule = this.moduleManager.modules.users;
  23. const app = (this.app = express());
  24. const SIDname = config.get("cookie");
  25. this.server = http.createServer(app).listen(config.get("port"));
  26. app.use(cookieParser());
  27. app.use(bodyParser.json());
  28. app.use(bodyParser.urlencoded({ extended: true }));
  29. const appUrl = `${config.get("url.secure") ? "https" : "http"}://${config.get("url.host")}`;
  30. const corsOptions = JSON.parse(JSON.stringify(config.get("cors")));
  31. corsOptions.origin.push(appUrl);
  32. corsOptions.credentials = true;
  33. app.use(cors(corsOptions));
  34. app.options("*", cors(corsOptions));
  35. /**
  36. * @param {object} res - response object from Express
  37. * @param {string} err - custom error message
  38. */
  39. function redirectOnErr(res, err) {
  40. res.redirect(`${appUrl}?err=${encodeURIComponent(err)}`);
  41. }
  42. if (config.get("apis.github.enabled")) {
  43. const redirectUri =
  44. config.get("apis.github.redirect_uri").length > 0
  45. ? config.get("apis.github.redirect_uri")
  46. : `${appUrl}/backend/auth/github/authorize/callback`;
  47. app.get("/auth/github/authorize", async (req, res) => {
  48. if (this.getStatus() !== "READY") {
  49. this.log(
  50. "INFO",
  51. "APP_REJECTED_GITHUB_AUTHORIZE",
  52. `A user tried to use github authorize, but the APP module is currently not ready.`
  53. );
  54. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  55. }
  56. const params = [
  57. `client_id=${config.get("apis.github.client")}`,
  58. `redirect_uri=${redirectUri}`,
  59. `scope=user:email`
  60. ].join("&");
  61. return res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  62. });
  63. app.get("/auth/github/link", async (req, res) => {
  64. if (this.getStatus() !== "READY") {
  65. this.log(
  66. "INFO",
  67. "APP_REJECTED_GITHUB_AUTHORIZE",
  68. `A user tried to use github authorize, but the APP module is currently not ready.`
  69. );
  70. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  71. }
  72. const params = [
  73. `client_id=${config.get("apis.github.client")}`,
  74. `redirect_uri=${redirectUri}`,
  75. `scope=user:email`,
  76. `state=${req.cookies[SIDname]}` // TODO don't do this
  77. ].join("&");
  78. return res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  79. });
  80. app.get("/auth/github/authorize/callback", async (req, res) => {
  81. if (this.getStatus() !== "READY") {
  82. this.log(
  83. "INFO",
  84. "APP_REJECTED_GITHUB_AUTHORIZE",
  85. `A user tried to use github authorize, but the APP module is currently not ready.`
  86. );
  87. redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  88. return;
  89. }
  90. const { code, state, error, error_description: errorDescription } = req.query;
  91. // GITHUB_AUTHORIZE_CALLBACK job handles login/register/linking
  92. UsersModule.runJob("GITHUB_AUTHORIZE_CALLBACK", { code, state, error, errorDescription })
  93. .then(({ redirectUrl, sessionId, userId }) => {
  94. if (sessionId) {
  95. const date = new Date();
  96. date.setTime(new Date().getTime() + 2 * 365 * 24 * 60 * 60 * 1000);
  97. res.cookie(SIDname, sessionId, {
  98. expires: date,
  99. secure: config.get("url.secure"),
  100. path: "/",
  101. domain: config.get("url.host")
  102. });
  103. this.log(
  104. "INFO",
  105. "AUTH_GITHUB_AUTHORIZE_CALLBACK",
  106. `User "${userId}" successfully authorized with GitHub.`
  107. );
  108. }
  109. res.redirect(redirectUrl);
  110. })
  111. .catch(err => {
  112. this.log(
  113. "ERROR",
  114. "AUTH_GITHUB_AUTHORIZE_CALLBACK",
  115. `Failed to authorize with GitHub. "${err.message}"`
  116. );
  117. return redirectOnErr(res, err.message);
  118. });
  119. });
  120. }
  121. app.get("/auth/verify_email", (req, res) => {
  122. if (this.getStatus() !== "READY") {
  123. this.log(
  124. "INFO",
  125. "APP_REJECTED_VERIFY_EMAIL",
  126. `A user tried to use verify email, but the APP module is currently not ready.`
  127. );
  128. redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  129. return;
  130. }
  131. const { code } = req.query;
  132. UsersModule.runJob("VERIFY_EMAIL", { code })
  133. .then(() => {
  134. this.log("INFO", "VERIFY_EMAIL", `Successfully verified email.`);
  135. res.redirect(`${appUrl}?toast=Thank you for verifying your email`);
  136. })
  137. .catch(err => {
  138. this.log("ERROR", "VERIFY_EMAIL", `Verifying email failed. "${err.message}"`);
  139. res.json({
  140. status: "error",
  141. message: err.message
  142. });
  143. });
  144. });
  145. resolve();
  146. });
  147. }
  148. /**
  149. * Returns the express server
  150. * @returns {Promise} - returns promise (reject, resolve)
  151. */
  152. SERVER() {
  153. return new Promise(resolve => {
  154. resolve(AppModule.server);
  155. });
  156. }
  157. /**
  158. * Returns the app object
  159. * @returns {Promise} - returns promise (reject, resolve)
  160. */
  161. GET_APP() {
  162. return new Promise(resolve => {
  163. resolve({ app: AppModule.app });
  164. });
  165. }
  166. // EXAMPLE_JOB() {
  167. // return new Promise((resolve, reject) => {
  168. // if (true) resolve({});
  169. // else reject(new Error("Nothing changed."));
  170. // });
  171. // }
  172. }
  173. export default new _AppModule();