app.js 15 KB

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