app.js 12 KB

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