app.js 14 KB

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