app.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. async initialize() {
  21. UsersModule = this.moduleManager.modules.users;
  22. const app = (this.app = express());
  23. const SIDname = config.get("cookie");
  24. this.server = http.createServer(app).listen(config.get("port"));
  25. app.use(cookieParser());
  26. app.use(bodyParser.json());
  27. app.use(bodyParser.urlencoded({ extended: true }));
  28. const appUrl = `${config.get("url.secure") ? "https" : "http"}://${config.get("url.host")}`;
  29. const corsOptions = JSON.parse(JSON.stringify(config.get("cors")));
  30. corsOptions.origin.push(appUrl);
  31. corsOptions.credentials = true;
  32. app.use(cors(corsOptions));
  33. app.options("*", cors(corsOptions));
  34. /**
  35. * @param {object} res - response object from Express
  36. * @param {string} err - custom error message
  37. */
  38. function redirectOnErr(res, err) {
  39. res.redirect(`${appUrl}?err=${encodeURIComponent(err)}`);
  40. }
  41. if (config.get("apis.github.enabled")) {
  42. const redirectUri =
  43. config.get("apis.github.redirect_uri").length > 0
  44. ? config.get("apis.github.redirect_uri")
  45. : `${appUrl}/backend/auth/github/authorize/callback`;
  46. app.get("/auth/github/authorize", async (req, res) => {
  47. if (this.getStatus() !== "READY") {
  48. this.log(
  49. "INFO",
  50. "APP_REJECTED_GITHUB_AUTHORIZE",
  51. `A user tried to use github authorize, but the APP module is currently not ready.`
  52. );
  53. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  54. }
  55. const params = [
  56. `client_id=${config.get("apis.github.client")}`,
  57. `redirect_uri=${redirectUri}`,
  58. `scope=user:email`
  59. ].join("&");
  60. return res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  61. });
  62. app.get("/auth/github/link", async (req, res) => {
  63. if (this.getStatus() !== "READY") {
  64. this.log(
  65. "INFO",
  66. "APP_REJECTED_GITHUB_AUTHORIZE",
  67. `A user tried to use github authorize, but the APP module is currently not ready.`
  68. );
  69. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  70. }
  71. const params = [
  72. `client_id=${config.get("apis.github.client")}`,
  73. `redirect_uri=${redirectUri}`,
  74. `scope=user:email`,
  75. `state=${req.cookies[SIDname]}` // TODO don't do this
  76. ].join("&");
  77. return res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  78. });
  79. app.get("/auth/github/authorize/callback", async (req, res) => {
  80. if (this.getStatus() !== "READY") {
  81. this.log(
  82. "INFO",
  83. "APP_REJECTED_GITHUB_AUTHORIZE",
  84. `A user tried to use github authorize, but the APP module is currently not ready.`
  85. );
  86. redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  87. return;
  88. }
  89. const { code, state, error, error_description: errorDescription } = req.query;
  90. // GITHUB_AUTHORIZE_CALLBACK job handles login/register/linking
  91. UsersModule.runJob("GITHUB_AUTHORIZE_CALLBACK", { code, state, error, errorDescription })
  92. .then(({ redirectUrl, sessionId, userId }) => {
  93. if (sessionId) {
  94. const date = new Date();
  95. date.setTime(new Date().getTime() + 2 * 365 * 24 * 60 * 60 * 1000);
  96. res.cookie(SIDname, sessionId, {
  97. expires: date,
  98. secure: config.get("url.secure"),
  99. path: "/",
  100. domain: config.get("url.host")
  101. });
  102. this.log(
  103. "INFO",
  104. "AUTH_GITHUB_AUTHORIZE_CALLBACK",
  105. `User "${userId}" successfully authorized with GitHub.`
  106. );
  107. }
  108. res.redirect(redirectUrl);
  109. })
  110. .catch(err => {
  111. this.log(
  112. "ERROR",
  113. "AUTH_GITHUB_AUTHORIZE_CALLBACK",
  114. `Failed to authorize with GitHub. "${err.message}"`
  115. );
  116. return redirectOnErr(res, err.message);
  117. });
  118. });
  119. }
  120. if (config.get("apis.oidc.enabled")) {
  121. app.get("/auth/oidc/authorize", async (req, res) => {
  122. if (this.getStatus() !== "READY") {
  123. this.log(
  124. "INFO",
  125. "APP_REJECTED_OIDC_AUTHORIZE",
  126. `A user tried to use OIDC authorize, but the APP module is currently not ready.`
  127. );
  128. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  129. }
  130. const params = [
  131. `client_id=${config.get("apis.oidc.client_id")}`,
  132. `redirect_uri=${UsersModule.oidcRedirectUri}`,
  133. `scope=basic openid`, // TODO check if openid is necessary for us
  134. `response_type=code`
  135. ].join("&");
  136. return res.redirect(`${UsersModule.oidcAuthorizationEndpoint}?${params}`);
  137. });
  138. app.get("/auth/oidc/authorize/callback", async (req, res) => {
  139. if (this.getStatus() !== "READY") {
  140. this.log(
  141. "INFO",
  142. "APP_REJECTED_OIDC_AUTHORIZE",
  143. `A user tried to use OIDC authorize, but the APP module is currently not ready.`
  144. );
  145. redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  146. return;
  147. }
  148. const { code, state, error, error_description: errorDescription } = req.query;
  149. // OIDC_AUTHORIZE_CALLBACK job handles login/register
  150. UsersModule.runJob("OIDC_AUTHORIZE_CALLBACK", { code, state, error, errorDescription })
  151. .then(({ redirectUrl, sessionId, userId }) => {
  152. if (sessionId) {
  153. const date = new Date();
  154. date.setTime(new Date().getTime() + 2 * 365 * 24 * 60 * 60 * 1000);
  155. res.cookie(SIDname, sessionId, {
  156. expires: date,
  157. secure: config.get("url.secure"),
  158. path: "/",
  159. domain: config.get("url.host")
  160. });
  161. this.log(
  162. "INFO",
  163. "AUTH_OIDC_AUTHORIZE_CALLBACK",
  164. `User "${userId}" successfully authorized with OIDC.`
  165. );
  166. }
  167. res.redirect(redirectUrl);
  168. })
  169. .catch(err => {
  170. this.log(
  171. "ERROR",
  172. "AUTH_OIDC_AUTHORIZE_CALLBACK",
  173. `Failed to authorize with OIDC. "${err.message}"`
  174. );
  175. return redirectOnErr(res, err.message);
  176. });
  177. });
  178. }
  179. app.get("/auth/verify_email", (req, res) => {
  180. if (this.getStatus() !== "READY") {
  181. this.log(
  182. "INFO",
  183. "APP_REJECTED_VERIFY_EMAIL",
  184. `A user tried to use verify email, but the APP module is currently not ready.`
  185. );
  186. redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  187. return;
  188. }
  189. const { code } = req.query;
  190. UsersModule.runJob("VERIFY_EMAIL", { code })
  191. .then(() => {
  192. this.log("INFO", "VERIFY_EMAIL", `Successfully verified email.`);
  193. res.redirect(`${appUrl}?toast=Thank you for verifying your email`);
  194. })
  195. .catch(err => {
  196. this.log("ERROR", "VERIFY_EMAIL", `Verifying email failed. "${err.message}"`);
  197. res.json({
  198. status: "error",
  199. message: err.message
  200. });
  201. });
  202. });
  203. }
  204. /**
  205. * Returns the express server
  206. * @returns {Promise} - returns promise (reject, resolve)
  207. */
  208. SERVER() {
  209. return new Promise(resolve => {
  210. resolve(AppModule.server);
  211. });
  212. }
  213. /**
  214. * Returns the app object
  215. * @returns {Promise} - returns promise (reject, resolve)
  216. */
  217. GET_APP() {
  218. return new Promise(resolve => {
  219. resolve({ app: AppModule.app });
  220. });
  221. }
  222. // EXAMPLE_JOB() {
  223. // return new Promise((resolve, reject) => {
  224. // if (true) resolve({});
  225. // else reject(new Error("Nothing changed."));
  226. // });
  227. // }
  228. }
  229. export default new _AppModule();