app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import config from "config";
  2. import async from "async";
  3. import request from "request";
  4. import cors from "cors";
  5. import cookieParser from "cookie-parser";
  6. import bodyParser from "body-parser";
  7. import express from "express";
  8. import oauth from "oauth";
  9. import CoreClass from "../core";
  10. const { OAuth2 } = oauth;
  11. let AppModule;
  12. let MailModule;
  13. let CacheModule;
  14. let DBModule;
  15. let ActivitiesModule;
  16. let UtilsModule;
  17. class _AppModule extends CoreClass {
  18. // eslint-disable-next-line require-jsdoc
  19. constructor() {
  20. super("app");
  21. AppModule = this;
  22. }
  23. /**
  24. * Initialises the app module
  25. *
  26. * @returns {Promise} - returns promise (reject, resolve)
  27. */
  28. initialize() {
  29. return new Promise(resolve => {
  30. MailModule = this.moduleManager.modules.mail;
  31. CacheModule = this.moduleManager.modules.cache;
  32. DBModule = this.moduleManager.modules.db;
  33. ActivitiesModule = this.moduleManager.modules.activities;
  34. UtilsModule = this.moduleManager.modules.utils;
  35. const app = (this.app = express());
  36. const SIDname = config.get("cookie.SIDname");
  37. this.server = app.listen(config.get("serverPort"));
  38. app.use(cookieParser());
  39. app.use(bodyParser.json());
  40. app.use(bodyParser.urlencoded({ extended: true }));
  41. let userModel;
  42. DBModule.runJob("GET_MODEL", { modelName: "user" })
  43. .then(model => {
  44. userModel = model;
  45. })
  46. .catch(console.error);
  47. const corsOptions = { ...config.get("cors") };
  48. app.use(cors(corsOptions));
  49. app.options("*", cors(corsOptions));
  50. const oauth2 = new OAuth2(
  51. config.get("apis.github.client"),
  52. config.get("apis.github.secret"),
  53. "https://github.com/",
  54. "login/oauth/authorize",
  55. "login/oauth/access_token",
  56. null
  57. );
  58. const redirectUri = `${config.get("serverDomain")}/auth/github/authorize/callback`;
  59. /**
  60. * @param {object} res - response object from Express
  61. * @param {string} err - custom error message
  62. */
  63. function redirectOnErr(res, err) {
  64. res.redirect(`${config.get("domain")}/?err=${encodeURIComponent(err)}`);
  65. }
  66. app.get("/auth/github/authorize", async (req, res) => {
  67. if (this.getStatus() !== "READY") {
  68. this.log(
  69. "INFO",
  70. "APP_REJECTED_GITHUB_AUTHORIZE",
  71. `A user tried to use github authorize, but the APP module is currently not ready.`
  72. );
  73. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  74. }
  75. const params = [
  76. `client_id=${config.get("apis.github.client")}`,
  77. `redirect_uri=${config.get("serverDomain")}/auth/github/authorize/callback`,
  78. `scope=user:email`
  79. ].join("&");
  80. return res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  81. });
  82. app.get("/auth/github/link", async (req, res) => {
  83. if (this.getStatus() !== "READY") {
  84. this.log(
  85. "INFO",
  86. "APP_REJECTED_GITHUB_AUTHORIZE",
  87. `A user tried to use github authorize, but the APP module is currently not ready.`
  88. );
  89. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  90. }
  91. const params = [
  92. `client_id=${config.get("apis.github.client")}`,
  93. `redirect_uri=${config.get("serverDomain")}/auth/github/authorize/callback`,
  94. `scope=user:email`,
  95. `state=${req.cookies[SIDname]}`
  96. ].join("&");
  97. return res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  98. });
  99. app.get("/auth/github/authorize/callback", async (req, res) => {
  100. if (this.getStatus() !== "READY") {
  101. this.log(
  102. "INFO",
  103. "APP_REJECTED_GITHUB_AUTHORIZE",
  104. `A user tried to use github authorize, but the APP module is currently not ready.`
  105. );
  106. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  107. }
  108. const { code } = req.query;
  109. let accessToken;
  110. let body;
  111. let address;
  112. const { state } = req.query;
  113. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 });
  114. return async.waterfall(
  115. [
  116. next => {
  117. if (req.query.error) return next(req.query.error_description);
  118. return next();
  119. },
  120. next => {
  121. oauth2.getOAuthAccessToken(code, { redirect_uri: redirectUri }, next);
  122. },
  123. (_accessToken, refreshToken, results, next) => {
  124. if (results.error) return next(results.error_description);
  125. accessToken = _accessToken;
  126. return request.get(
  127. {
  128. url: `https://api.github.com/user`,
  129. headers: {
  130. "User-Agent": "request",
  131. Authorization: `token ${accessToken}`
  132. }
  133. },
  134. next
  135. );
  136. },
  137. (httpResponse, _body, next) => {
  138. body = _body = JSON.parse(_body);
  139. if (httpResponse.statusCode !== 200) return next(body.message);
  140. if (state) {
  141. return async.waterfall(
  142. [
  143. next => {
  144. CacheModule.runJob("HGET", {
  145. table: "sessions",
  146. key: state
  147. })
  148. .then(session => next(null, session))
  149. .catch(next);
  150. },
  151. (session, next) => {
  152. if (!session) return next("Invalid session.");
  153. return userModel.findOne({ _id: session.userId }, next);
  154. },
  155. (user, next) => {
  156. if (!user) return next("User not found.");
  157. if (user.services.github && user.services.github.id)
  158. return next("Account already has GitHub linked.");
  159. return userModel.updateOne(
  160. { _id: user._id },
  161. {
  162. $set: {
  163. "services.github": {
  164. id: body.id,
  165. accessToken
  166. }
  167. }
  168. },
  169. { runValidators: true },
  170. err => {
  171. if (err) return next(err);
  172. return next(null, user, body);
  173. }
  174. );
  175. },
  176. user => {
  177. CacheModule.runJob("PUB", {
  178. channel: "user.linkGithub",
  179. value: user._id
  180. });
  181. res.redirect(`${config.get("domain")}/settings#security`);
  182. }
  183. ],
  184. next
  185. );
  186. }
  187. if (!body.id) return next("Something went wrong, no id.");
  188. return userModel.findOne({ "services.github.id": body.id }, (err, user) => {
  189. next(err, user, body);
  190. });
  191. },
  192. (user, body, next) => {
  193. if (user) {
  194. user.services.github.access_token = accessToken;
  195. return user.save(() => next(true, user._id));
  196. }
  197. return userModel.findOne({ username: new RegExp(`^${body.login}$`, "i") }, (err, user) =>
  198. next(err, user)
  199. );
  200. },
  201. (user, next) => {
  202. if (user) return next(`An account with that username already exists.`);
  203. return request.get(
  204. {
  205. url: `https://api.github.com/user/emails`,
  206. headers: {
  207. "User-Agent": "request",
  208. Authorization: `token ${accessToken}`
  209. }
  210. },
  211. next
  212. );
  213. },
  214. (httpResponse, body2, next) => {
  215. body2 = JSON.parse(body2);
  216. if (!Array.isArray(body2)) return next(body2.message);
  217. body2.forEach(email => {
  218. if (email.primary) address = email.email.toLowerCase();
  219. });
  220. return userModel.findOne({ "email.address": address }, next);
  221. },
  222. (user, next) => {
  223. UtilsModule.runJob("GENERATE_RANDOM_STRING", {
  224. length: 12
  225. }).then(_id => next(null, user, _id));
  226. },
  227. (user, _id, next) => {
  228. if (user) {
  229. if (Object.keys(JSON.parse(user.services.github)).length === 0)
  230. return next(
  231. `An account with that email address exists, but is not linked to GitHub.`
  232. );
  233. return next(`An account with that email address already exists.`);
  234. }
  235. return next(null, {
  236. _id, // TODO Check if exists
  237. username: body.login,
  238. name: body.name,
  239. location: body.location,
  240. bio: body.bio,
  241. email: {
  242. address,
  243. verificationToken
  244. },
  245. services: {
  246. github: { id: body.id, accessToken }
  247. }
  248. });
  249. },
  250. // generate the url for gravatar avatar
  251. (user, next) => {
  252. UtilsModule.runJob("CREATE_GRAVATAR", {
  253. email: user.email.address
  254. }).then(url => {
  255. user.avatar = { type: "gravatar", url };
  256. next(null, user);
  257. });
  258. },
  259. // save the new user to the database
  260. (user, next) => {
  261. userModel.create(user, next);
  262. },
  263. // add the activity of account creation
  264. (user, next) => {
  265. ActivitiesModule.runJob("ADD_ACTIVITY", {
  266. userId: user._id,
  267. activityType: "created_account"
  268. });
  269. next(null, user);
  270. },
  271. (user, next) => {
  272. MailModule.runJob("GET_SCHEMA", {
  273. schemaName: "verifyEmail"
  274. }).then(verifyEmailSchema => {
  275. verifyEmailSchema(address, body.login, user.email.verificationToken, err => {
  276. next(err, user._id);
  277. });
  278. });
  279. }
  280. ],
  281. async (err, userId) => {
  282. if (err && err !== true) {
  283. err = await UtilsModule.runJob("GET_ERROR", {
  284. error: err
  285. });
  286. this.log(
  287. "ERROR",
  288. "AUTH_GITHUB_AUTHORIZE_CALLBACK",
  289. `Failed to authorize with GitHub. "${err}"`
  290. );
  291. return redirectOnErr(res, err);
  292. }
  293. const sessionId = await UtilsModule.runJob("GUID", {});
  294. const sessionSchema = await CacheModule.runJob("GET_SCHEMA", {
  295. schemaName: "session"
  296. });
  297. return CacheModule.runJob("HSET", {
  298. table: "sessions",
  299. key: sessionId,
  300. value: sessionSchema(sessionId, userId)
  301. })
  302. .then(() => {
  303. const date = new Date();
  304. date.setTime(new Date().getTime() + 2 * 365 * 24 * 60 * 60 * 1000);
  305. res.cookie(SIDname, sessionId, {
  306. expires: date,
  307. secure: config.get("cookie.secure"),
  308. path: "/",
  309. domain: config.get("cookie.domain")
  310. });
  311. this.log(
  312. "INFO",
  313. "AUTH_GITHUB_AUTHORIZE_CALLBACK",
  314. `User "${userId}" successfully authorized with GitHub.`
  315. );
  316. res.redirect(`${config.get("domain")}/`);
  317. })
  318. .catch(err => redirectOnErr(res, err.message));
  319. }
  320. );
  321. });
  322. app.get("/auth/verify_email", async (req, res) => {
  323. if (this.getStatus() !== "READY") {
  324. this.log(
  325. "INFO",
  326. "APP_REJECTED_GITHUB_AUTHORIZE",
  327. `A user tried to use github authorize, but the APP module is currently not ready.`
  328. );
  329. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  330. }
  331. const { code } = req.query;
  332. return async.waterfall(
  333. [
  334. next => {
  335. if (!code) return next("Invalid code.");
  336. return next();
  337. },
  338. next => {
  339. userModel.findOne({ "email.verificationToken": code }, next);
  340. },
  341. (user, next) => {
  342. if (!user) return next("User not found.");
  343. if (user.email.verified) return next("This email is already verified.");
  344. return userModel.updateOne(
  345. { "email.verificationToken": code },
  346. {
  347. $set: { "email.verified": true },
  348. $unset: { "email.verificationToken": "" }
  349. },
  350. { runValidators: true },
  351. next
  352. );
  353. }
  354. ],
  355. err => {
  356. if (err) {
  357. let error = "An error occurred.";
  358. if (typeof err === "string") error = err;
  359. else if (err.message) error = err.message;
  360. this.log("ERROR", "VERIFY_EMAIL", `Verifying email failed. "${error}"`);
  361. return res.json({
  362. status: "failure",
  363. message: error
  364. });
  365. }
  366. this.log("INFO", "VERIFY_EMAIL", `Successfully verified email.`);
  367. return res.redirect(`${config.get("domain")}?msg=Thank you for verifying your email`);
  368. }
  369. );
  370. });
  371. return resolve();
  372. });
  373. }
  374. /**
  375. * Returns the express server
  376. *
  377. * @returns {Promise} - returns promise (reject, resolve)
  378. */
  379. SERVER() {
  380. return new Promise(resolve => {
  381. resolve(AppModule.server);
  382. });
  383. }
  384. /**
  385. * Returns the app object
  386. *
  387. * @returns {Promise} - returns promise (reject, resolve)
  388. */
  389. GET_APP() {
  390. return new Promise(resolve => {
  391. resolve({ app: AppModule.app });
  392. });
  393. }
  394. // EXAMPLE_JOB() {
  395. // return new Promise((resolve, reject) => {
  396. // if (true) resolve({});
  397. // else reject(new Error("Nothing changed."));
  398. // });
  399. // }
  400. }
  401. export default new _AppModule();