app.js 12 KB

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