app.js 14 KB

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