app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 { OAuth2 } from "oauth";
  9. import CoreClass from "../core";
  10. class AppModule extends CoreClass {
  11. constructor() {
  12. super("app");
  13. }
  14. initialize() {
  15. return new Promise(resolve => {
  16. const { mail } = this.moduleManager.modules;
  17. const { cache } = this.moduleManager.modules;
  18. const { db } = this.moduleManager.modules;
  19. const { activities } = this.moduleManager.modules;
  20. this.utils = this.moduleManager.modules.utils;
  21. const app = (this.app = express());
  22. const SIDname = config.get("cookie.SIDname");
  23. this.server = app.listen(config.get("serverPort"));
  24. app.use(cookieParser());
  25. app.use(bodyParser.json());
  26. app.use(bodyParser.urlencoded({ extended: true }));
  27. let userModel;
  28. db.runJob("GET_MODEL", { modelName: "user" })
  29. .then(model => {
  30. userModel = model;
  31. })
  32. .catch(console.error);
  33. const corsOptions = { ...config.get("cors") };
  34. app.use(cors(corsOptions));
  35. app.options("*", cors(corsOptions));
  36. const oauth2 = new OAuth2(
  37. config.get("apis.github.client"),
  38. config.get("apis.github.secret"),
  39. "https://github.com/",
  40. "login/oauth/authorize",
  41. "login/oauth/access_token",
  42. null
  43. );
  44. const redirectUri = `${config.get("serverDomain")}/auth/github/authorize/callback`;
  45. /**
  46. * @param {object} res - response object from Express
  47. * @param {string} err - custom error message
  48. */
  49. function redirectOnErr(res, err) {
  50. res.redirect(`${config.get("domain")}/?err=${encodeURIComponent(err)}`);
  51. }
  52. app.get("/auth/github/authorize", async (req, res) => {
  53. if (this.getStatus() !== "READY") {
  54. this.log(
  55. "INFO",
  56. "APP_REJECTED_GITHUB_AUTHORIZE",
  57. `A user tried to use github authorize, but the APP module is currently not ready.`
  58. );
  59. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  60. }
  61. const params = [
  62. `client_id=${config.get("apis.github.client")}`,
  63. `redirect_uri=${config.get("serverDomain")}/auth/github/authorize/callback`,
  64. `scope=user:email`
  65. ].join("&");
  66. return res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  67. });
  68. app.get("/auth/github/link", async (req, res) => {
  69. if (this.getStatus() !== "READY") {
  70. this.log(
  71. "INFO",
  72. "APP_REJECTED_GITHUB_AUTHORIZE",
  73. `A user tried to use github authorize, but the APP module is currently not ready.`
  74. );
  75. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  76. }
  77. const params = [
  78. `client_id=${config.get("apis.github.client")}`,
  79. `redirect_uri=${config.get("serverDomain")}/auth/github/authorize/callback`,
  80. `scope=user:email`,
  81. `state=${req.cookies[SIDname]}`
  82. ].join("&");
  83. return res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  84. });
  85. app.get("/auth/github/authorize/callback", async (req, res) => {
  86. if (this.getStatus() !== "READY") {
  87. this.log(
  88. "INFO",
  89. "APP_REJECTED_GITHUB_AUTHORIZE",
  90. `A user tried to use github authorize, but the APP module is currently not ready.`
  91. );
  92. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  93. }
  94. const { code } = req.query;
  95. let accessToken;
  96. let body;
  97. let address;
  98. const { state } = req.query;
  99. const verificationToken = await this.utils.runJob("GENERATE_RANDOM_STRING", { length: 64 });
  100. return async.waterfall(
  101. [
  102. next => {
  103. if (req.query.error) return next(req.query.error_description);
  104. return next();
  105. },
  106. next => {
  107. oauth2.getOAuthAccessToken(code, { redirect_uri: redirectUri }, next);
  108. },
  109. (_accessToken, refreshToken, results, next) => {
  110. if (results.error) return next(results.error_description);
  111. accessToken = _accessToken;
  112. return request.get(
  113. {
  114. url: `https://api.github.com/user`,
  115. headers: {
  116. "User-Agent": "request",
  117. Authorization: `token ${accessToken}`
  118. }
  119. },
  120. next
  121. );
  122. },
  123. (httpResponse, _body, next) => {
  124. body = _body = JSON.parse(_body);
  125. if (httpResponse.statusCode !== 200) return next(body.message);
  126. if (state) {
  127. return async.waterfall(
  128. [
  129. next => {
  130. cache
  131. .runJob("HGET", {
  132. table: "sessions",
  133. key: state
  134. })
  135. .then(session => next(null, session))
  136. .catch(next);
  137. },
  138. (session, next) => {
  139. if (!session) return next("Invalid session.");
  140. return userModel.findOne({ _id: session.userId }, next);
  141. },
  142. (user, next) => {
  143. if (!user) return next("User not found.");
  144. if (user.services.github && user.services.github.id)
  145. return next("Account already has GitHub linked.");
  146. return userModel.updateOne(
  147. { _id: user._id },
  148. {
  149. $set: {
  150. "services.github": {
  151. id: body.id,
  152. accessToken
  153. }
  154. }
  155. },
  156. { runValidators: true },
  157. err => {
  158. if (err) return next(err);
  159. return next(null, user, body);
  160. }
  161. );
  162. },
  163. user => {
  164. cache.runJob("PUB", {
  165. channel: "user.linkGithub",
  166. value: user._id
  167. });
  168. res.redirect(`${config.get("domain")}/settings#security`);
  169. }
  170. ],
  171. next
  172. );
  173. }
  174. if (!body.id) return next("Something went wrong, no id.");
  175. return userModel.findOne({ "services.github.id": body.id }, (err, user) => {
  176. next(err, user, body);
  177. });
  178. },
  179. (user, body, next) => {
  180. if (user) {
  181. user.services.github.access_token = accessToken;
  182. return user.save(() => next(true, user._id));
  183. }
  184. return userModel.findOne({ username: new RegExp(`^${body.login}$`, "i") }, (err, user) =>
  185. next(err, user)
  186. );
  187. },
  188. (user, next) => {
  189. if (user) return next(`An account with that username already exists.`);
  190. return request.get(
  191. {
  192. url: `https://api.github.com/user/emails`,
  193. headers: {
  194. "User-Agent": "request",
  195. Authorization: `token ${accessToken}`
  196. }
  197. },
  198. next
  199. );
  200. },
  201. (httpResponse, body2, next) => {
  202. body2 = JSON.parse(body2);
  203. if (!Array.isArray(body2)) return next(body2.message);
  204. body2.forEach(email => {
  205. if (email.primary) address = email.email.toLowerCase();
  206. });
  207. return userModel.findOne({ "email.address": address }, next);
  208. },
  209. (user, next) => {
  210. this.utils
  211. .runJob("GENERATE_RANDOM_STRING", {
  212. length: 12
  213. })
  214. .then(_id => {
  215. next(null, user, _id);
  216. });
  217. },
  218. (user, _id, next) => {
  219. if (user) {
  220. if (Object.keys(JSON.parse(user.services.github)).length === 0)
  221. return next(
  222. `An account with that email address exists, but is not linked to GitHub.`
  223. );
  224. return next(`An account with that email address already exists.`);
  225. }
  226. return next(null, {
  227. _id, // TODO Check if exists
  228. username: body.login,
  229. name: body.name,
  230. location: body.location,
  231. bio: body.bio,
  232. email: {
  233. address,
  234. verificationToken
  235. },
  236. services: {
  237. github: { id: body.id, accessToken }
  238. }
  239. });
  240. },
  241. // generate the url for gravatar avatar
  242. (user, next) => {
  243. this.utils
  244. .runJob("CREATE_GRAVATAR", {
  245. email: user.email.address
  246. })
  247. .then(url => {
  248. user.avatar = { type: "gravatar", url };
  249. next(null, user);
  250. });
  251. },
  252. // save the new user to the database
  253. (user, next) => {
  254. userModel.create(user, next);
  255. },
  256. // add the activity of account creation
  257. (user, next) => {
  258. activities.runJob("ADD_ACTIVITY", {
  259. userId: user._id,
  260. activityType: "created_account"
  261. });
  262. next(null, user);
  263. },
  264. (user, next) => {
  265. mail.runJob("GET_SCHEMA", {
  266. schemaName: "verifyEmail"
  267. }).then(verifyEmailSchema => {
  268. verifyEmailSchema(address, body.login, user.email.verificationToken);
  269. next(null, user._id);
  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();