app.js 13 KB

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