app.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. res.redirect(`${config.get("domain")}/settings?tab=security`);
  184. }
  185. ],
  186. next
  187. );
  188. }
  189. if (!github.data.id) return next("Something went wrong, no id.");
  190. return userModel.findOne({ "services.github.id": github.data.id }, (err, user) => {
  191. next(err, user, github.data);
  192. });
  193. },
  194. (user, _body, next) => {
  195. body = _body;
  196. if (user) {
  197. user.services.github.access_token = accessToken;
  198. return user.save(() => next(true, user._id));
  199. }
  200. return userModel.findOne({ username: new RegExp(`^${body.login}$`, "i") }, (err, user) =>
  201. next(err, user)
  202. );
  203. },
  204. (user, next) => {
  205. if (user) return next(`An account with that username already exists.`);
  206. return axios
  207. .get("https://api.github.com/user/emails", {
  208. headers: {
  209. "User-Agent": "request",
  210. Authorization: `token ${accessToken}`
  211. }
  212. })
  213. .then(res => next(null, res.data))
  214. .catch(err => next(err));
  215. },
  216. (body, next) => {
  217. if (!Array.isArray(body)) return next(body.message);
  218. body.forEach(email => {
  219. if (email.primary) address = email.email.toLowerCase();
  220. });
  221. return userModel.findOne({ "email.address": address }, next);
  222. },
  223. (user, next) => {
  224. UtilsModule.runJob("GENERATE_RANDOM_STRING", {
  225. length: 12
  226. }).then(_id => next(null, user, _id));
  227. },
  228. (user, _id, next) => {
  229. if (user) {
  230. if (Object.keys(JSON.parse(user.services.github)).length === 0)
  231. return next(
  232. `An account with that email address exists, but is not linked to GitHub.`
  233. );
  234. return next(`An account with that email address already exists.`);
  235. }
  236. return next(null, {
  237. _id,
  238. username: body.login,
  239. name: body.name,
  240. location: body.location,
  241. bio: body.bio,
  242. email: {
  243. address,
  244. verificationToken
  245. },
  246. services: {
  247. github: { id: body.id, access_token: accessToken }
  248. }
  249. });
  250. },
  251. // generate the url for gravatar avatar
  252. (user, next) => {
  253. UtilsModule.runJob("CREATE_GRAVATAR", {
  254. email: user.email.address
  255. }).then(url => {
  256. user.avatar = { type: "gravatar", url };
  257. next(null, user);
  258. });
  259. },
  260. // save the new user to the database
  261. (user, next) => {
  262. userModel.create(user, next);
  263. },
  264. (user, next) => {
  265. MailModule.runJob("GET_SCHEMA", {
  266. schemaName: "verifyEmail"
  267. }).then(verifyEmailSchema => {
  268. verifyEmailSchema(address, body.login, user.email.verificationToken, err => {
  269. next(err, user._id);
  270. });
  271. });
  272. },
  273. // create a liked songs playlist for the new user
  274. (userId, next) => {
  275. PlaylistsModule.runJob("CREATE_USER_PLAYLIST", {
  276. userId,
  277. displayName: "Liked Songs",
  278. type: "user-liked"
  279. })
  280. .then(likedSongsPlaylist => {
  281. next(null, likedSongsPlaylist, userId);
  282. })
  283. .catch(err => next(err));
  284. },
  285. // create a disliked songs playlist for the new user
  286. (likedSongsPlaylist, userId, next) => {
  287. PlaylistsModule.runJob("CREATE_USER_PLAYLIST", {
  288. userId,
  289. displayName: "Disliked Songs",
  290. type: "user-disliked"
  291. })
  292. .then(dislikedSongsPlaylist => {
  293. next(null, { likedSongsPlaylist, dislikedSongsPlaylist }, userId);
  294. })
  295. .catch(err => next(err));
  296. },
  297. // associate liked + disliked songs playlist to the user object
  298. ({ likedSongsPlaylist, dislikedSongsPlaylist }, userId, next) => {
  299. userModel.updateOne(
  300. { _id: userId },
  301. { $set: { likedSongsPlaylist, dislikedSongsPlaylist } },
  302. { runValidators: true },
  303. err => {
  304. if (err) return next(err);
  305. return next(null, userId);
  306. }
  307. );
  308. },
  309. // add the activity of account creation
  310. (userId, next) => {
  311. ActivitiesModule.runJob("ADD_ACTIVITY", {
  312. userId,
  313. type: "user__joined",
  314. payload: { message: "Welcome to Musare!" }
  315. });
  316. next(null, userId);
  317. }
  318. ],
  319. async (err, userId) => {
  320. if (err && err !== true) {
  321. err = await UtilsModule.runJob("GET_ERROR", {
  322. error: err
  323. });
  324. this.log(
  325. "ERROR",
  326. "AUTH_GITHUB_AUTHORIZE_CALLBACK",
  327. `Failed to authorize with GitHub. "${err}"`
  328. );
  329. return redirectOnErr(res, err);
  330. }
  331. const sessionId = await UtilsModule.runJob("GUID", {});
  332. const sessionSchema = await CacheModule.runJob("GET_SCHEMA", {
  333. schemaName: "session"
  334. });
  335. return CacheModule.runJob("HSET", {
  336. table: "sessions",
  337. key: sessionId,
  338. value: sessionSchema(sessionId, userId)
  339. })
  340. .then(() => {
  341. const date = new Date();
  342. date.setTime(new Date().getTime() + 2 * 365 * 24 * 60 * 60 * 1000);
  343. res.cookie(SIDname, sessionId, {
  344. expires: date,
  345. secure: config.get("cookie.secure"),
  346. path: "/",
  347. domain: config.get("cookie.domain")
  348. });
  349. this.log(
  350. "INFO",
  351. "AUTH_GITHUB_AUTHORIZE_CALLBACK",
  352. `User "${userId}" successfully authorized with GitHub.`
  353. );
  354. res.redirect(`${config.get("domain")}/`);
  355. })
  356. .catch(err => redirectOnErr(res, err.message));
  357. }
  358. );
  359. });
  360. app.get("/auth/verify_email", async (req, res) => {
  361. if (this.getStatus() !== "READY") {
  362. this.log(
  363. "INFO",
  364. "APP_REJECTED_GITHUB_AUTHORIZE",
  365. `A user tried to use github authorize, but the APP module is currently not ready.`
  366. );
  367. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  368. }
  369. const { code } = req.query;
  370. return async.waterfall(
  371. [
  372. next => {
  373. if (!code) return next("Invalid code.");
  374. return next();
  375. },
  376. next => {
  377. userModel.findOne({ "email.verificationToken": code }, next);
  378. },
  379. (user, next) => {
  380. if (!user) return next("User not found.");
  381. if (user.email.verified) return next("This email is already verified.");
  382. return userModel.updateOne(
  383. { "email.verificationToken": code },
  384. {
  385. $set: { "email.verified": true },
  386. $unset: { "email.verificationToken": "" }
  387. },
  388. { runValidators: true },
  389. next
  390. );
  391. }
  392. ],
  393. err => {
  394. if (err) {
  395. let error = "An error occurred.";
  396. if (typeof err === "string") error = err;
  397. else if (err.message) error = err.message;
  398. this.log("ERROR", "VERIFY_EMAIL", `Verifying email failed. "${error}"`);
  399. return res.json({
  400. status: "error",
  401. message: error
  402. });
  403. }
  404. this.log("INFO", "VERIFY_EMAIL", `Successfully verified email.`);
  405. return res.redirect(`${config.get("domain")}?msg=Thank you for verifying your email`);
  406. }
  407. );
  408. });
  409. return resolve();
  410. });
  411. }
  412. /**
  413. * Returns the express server
  414. *
  415. * @returns {Promise} - returns promise (reject, resolve)
  416. */
  417. SERVER() {
  418. return new Promise(resolve => {
  419. resolve(AppModule.server);
  420. });
  421. }
  422. /**
  423. * Returns the app object
  424. *
  425. * @returns {Promise} - returns promise (reject, resolve)
  426. */
  427. GET_APP() {
  428. return new Promise(resolve => {
  429. resolve({ app: AppModule.app });
  430. });
  431. }
  432. // EXAMPLE_JOB() {
  433. // return new Promise((resolve, reject) => {
  434. // if (true) resolve({});
  435. // else reject(new Error("Nothing changed."));
  436. // });
  437. // }
  438. }
  439. export default new _AppModule();