app.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 axios from "axios";
  8. import CoreClass from "../core";
  9. let AppModule;
  10. let UsersModule;
  11. class _AppModule extends CoreClass {
  12. // eslint-disable-next-line require-jsdoc
  13. constructor() {
  14. super("app");
  15. AppModule = this;
  16. }
  17. /**
  18. * Initialises the app module
  19. * @returns {Promise} - returns promise (reject, resolve)
  20. */
  21. async initialize() {
  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. if (config.get("apis.oidc.enabled")) {
  122. const redirectUri =
  123. config.get("apis.oidc.redirect_uri").length > 0
  124. ? config.get("apis.oidc.redirect_uri")
  125. : `${appUrl}/backend/auth/oidc/authorize/callback`;
  126. // TODO don't fetch the openid configuration twice (app module and user module)
  127. const openidConfigurationResponse = await axios.get(config.get("apis.oidc.openid_configuration_url"));
  128. const { authorization_endpoint: authorizationEndpoint } = openidConfigurationResponse.data;
  129. app.get("/auth/oidc/authorize", async (req, res) => {
  130. if (this.getStatus() !== "READY") {
  131. this.log(
  132. "INFO",
  133. "APP_REJECTED_OIDC_AUTHORIZE",
  134. `A user tried to use OIDC authorize, but the APP module is currently not ready.`
  135. );
  136. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  137. }
  138. const params = [
  139. `client_id=${config.get("apis.oidc.client_id")}`,
  140. `redirect_uri=${redirectUri}`,
  141. `scope=basic openid`, // TODO check if openid is necessary for us
  142. `response_type=code`
  143. ].join("&");
  144. return res.redirect(`${authorizationEndpoint}?${params}`);
  145. });
  146. app.get("/auth/oidc/authorize/callback", async (req, res) => {
  147. if (this.getStatus() !== "READY") {
  148. this.log(
  149. "INFO",
  150. "APP_REJECTED_OIDC_AUTHORIZE",
  151. `A user tried to use OIDC authorize, but the APP module is currently not ready.`
  152. );
  153. redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  154. return;
  155. }
  156. const { code, state, error, error_description: errorDescription } = req.query;
  157. // OIDC_AUTHORIZE_CALLBACK job handles login/register
  158. UsersModule.runJob("OIDC_AUTHORIZE_CALLBACK", { code, state, error, errorDescription })
  159. .then(({ redirectUrl, sessionId, userId }) => {
  160. if (sessionId) {
  161. const date = new Date();
  162. date.setTime(new Date().getTime() + 2 * 365 * 24 * 60 * 60 * 1000);
  163. res.cookie(SIDname, sessionId, {
  164. expires: date,
  165. secure: config.get("url.secure"),
  166. path: "/",
  167. domain: config.get("url.host")
  168. });
  169. this.log(
  170. "INFO",
  171. "AUTH_OIDC_AUTHORIZE_CALLBACK",
  172. `User "${userId}" successfully authorized with OIDC.`
  173. );
  174. }
  175. res.redirect(redirectUrl);
  176. })
  177. .catch(err => {
  178. this.log(
  179. "ERROR",
  180. "AUTH_OIDC_AUTHORIZE_CALLBACK",
  181. `Failed to authorize with OIDC. "${err.message}"`
  182. );
  183. return redirectOnErr(res, err.message);
  184. });
  185. });
  186. }
  187. app.get("/auth/verify_email", (req, res) => {
  188. if (this.getStatus() !== "READY") {
  189. this.log(
  190. "INFO",
  191. "APP_REJECTED_VERIFY_EMAIL",
  192. `A user tried to use verify email, but the APP module is currently not ready.`
  193. );
  194. redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  195. return;
  196. }
  197. const { code } = req.query;
  198. UsersModule.runJob("VERIFY_EMAIL", { code })
  199. .then(() => {
  200. this.log("INFO", "VERIFY_EMAIL", `Successfully verified email.`);
  201. res.redirect(`${appUrl}?toast=Thank you for verifying your email`);
  202. })
  203. .catch(err => {
  204. this.log("ERROR", "VERIFY_EMAIL", `Verifying email failed. "${err.message}"`);
  205. res.json({
  206. status: "error",
  207. message: err.message
  208. });
  209. });
  210. });
  211. }
  212. /**
  213. * Returns the express server
  214. * @returns {Promise} - returns promise (reject, resolve)
  215. */
  216. SERVER() {
  217. return new Promise(resolve => {
  218. resolve(AppModule.server);
  219. });
  220. }
  221. /**
  222. * Returns the app object
  223. * @returns {Promise} - returns promise (reject, resolve)
  224. */
  225. GET_APP() {
  226. return new Promise(resolve => {
  227. resolve({ app: AppModule.app });
  228. });
  229. }
  230. // EXAMPLE_JOB() {
  231. // return new Promise((resolve, reject) => {
  232. // if (true) resolve({});
  233. // else reject(new Error("Nothing changed."));
  234. // });
  235. // }
  236. }
  237. export default new _AppModule();