1
0

app.js 14 KB

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