app.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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.oidc.enabled")) {
  42. app.get("/auth/oidc/authorize", async (req, res) => {
  43. if (this.getStatus() !== "READY") {
  44. this.log(
  45. "INFO",
  46. "APP_REJECTED_OIDC_AUTHORIZE",
  47. `A user tried to use OIDC authorize, but the APP module is currently not ready.`
  48. );
  49. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  50. }
  51. const params = [
  52. `client_id=${config.get("apis.oidc.client_id")}`,
  53. `redirect_uri=${UsersModule.oidcRedirectUri}`,
  54. `scope=basic openid`,
  55. `response_type=code`
  56. ].join("&");
  57. return res.redirect(`${UsersModule.oidcAuthorizationEndpoint}?${params}`);
  58. });
  59. app.get("/auth/oidc/authorize/callback", async (req, res) => {
  60. if (this.getStatus() !== "READY") {
  61. this.log(
  62. "INFO",
  63. "APP_REJECTED_OIDC_AUTHORIZE",
  64. `A user tried to use OIDC authorize, but the APP module is currently not ready.`
  65. );
  66. redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  67. return;
  68. }
  69. const { code, state, error, error_description: errorDescription } = req.query;
  70. // OIDC_AUTHORIZE_CALLBACK job handles login/register
  71. UsersModule.runJob("OIDC_AUTHORIZE_CALLBACK", { code, state, error, errorDescription })
  72. .then(({ redirectUrl, sessionId, userId }) => {
  73. if (sessionId) {
  74. const date = new Date();
  75. date.setTime(new Date().getTime() + 2 * 365 * 24 * 60 * 60 * 1000);
  76. res.cookie(SIDname, sessionId, {
  77. expires: date,
  78. secure: config.get("url.secure"),
  79. path: "/",
  80. domain: config.get("url.host")
  81. });
  82. this.log(
  83. "INFO",
  84. "AUTH_OIDC_AUTHORIZE_CALLBACK",
  85. `User "${userId}" successfully authorized with OIDC.`
  86. );
  87. }
  88. res.redirect(redirectUrl);
  89. })
  90. .catch(err => {
  91. this.log(
  92. "ERROR",
  93. "AUTH_OIDC_AUTHORIZE_CALLBACK",
  94. `Failed to authorize with OIDC. "${err.message}"`
  95. );
  96. return redirectOnErr(res, err.message);
  97. });
  98. });
  99. }
  100. app.get("/auth/verify_email", (req, res) => {
  101. if (this.getStatus() !== "READY") {
  102. this.log(
  103. "INFO",
  104. "APP_REJECTED_VERIFY_EMAIL",
  105. `A user tried to use verify email, but the APP module is currently not ready.`
  106. );
  107. redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  108. return;
  109. }
  110. const { code } = req.query;
  111. UsersModule.runJob("VERIFY_EMAIL", { code })
  112. .then(() => {
  113. this.log("INFO", "VERIFY_EMAIL", `Successfully verified email.`);
  114. res.redirect(`${appUrl}?toast=Thank you for verifying your email`);
  115. })
  116. .catch(err => {
  117. this.log("ERROR", "VERIFY_EMAIL", `Verifying email failed. "${err.message}"`);
  118. res.json({
  119. status: "error",
  120. message: err.message
  121. });
  122. });
  123. });
  124. }
  125. /**
  126. * Returns the express server
  127. * @returns {Promise} - returns promise (reject, resolve)
  128. */
  129. SERVER() {
  130. return new Promise(resolve => {
  131. resolve(AppModule.server);
  132. });
  133. }
  134. /**
  135. * Returns the app object
  136. * @returns {Promise} - returns promise (reject, resolve)
  137. */
  138. GET_APP() {
  139. return new Promise(resolve => {
  140. resolve({ app: AppModule.app });
  141. });
  142. }
  143. // EXAMPLE_JOB() {
  144. // return new Promise((resolve, reject) => {
  145. // if (true) resolve({});
  146. // else reject(new Error("Nothing changed."));
  147. // });
  148. // }
  149. }
  150. export default new _AppModule();