app.js 15 KB

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