app.js 14 KB

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