app.js 14 KB

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