app.js 13 KB

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