app.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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. if (config.get("apis.google.enabled")) {
  385. const oauth2 = new OAuth2(
  386. config.get("apis.google.client"),
  387. config.get("apis.google.secret"),
  388. "https://accounts.google.com/o/oauth2/v2/auth",
  389. "https://accounts.google.com/o/oauth2/v2/token",
  390. "1.0",
  391. null,
  392. "HMAC-SHA1"
  393. );
  394. const redirectUri = `${config.get("apis.google.redirect_uri")}`;
  395. // http://localhost/backend/auth/google/link
  396. app.get("/auth/google/link", async (req, res) => {
  397. if (this.getStatus() !== "READY") {
  398. this.log(
  399. "INFO",
  400. "APP_REJECTED_GOOGLE_AUTHORIZE",
  401. `A user tried to use google authorize, but the APP module is currently not ready.`
  402. );
  403. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  404. }
  405. if (!req.cookies[SIDname]) return redirectOnErr(res, "Not logged in.");
  406. const session = await CacheModule.runJob("HGET", {
  407. table: "sessions",
  408. key: req.cookies[SIDname]
  409. });
  410. if (!session) return redirectOnErr(res, "Not logged in.");
  411. const user = await userModel.findOne({ _id: session.userId });
  412. if (!user) return redirectOnErr(res, "Not logged in.");
  413. if (user.services.google && user.services.google.id)
  414. return redirectOnErr(res, "You already have a Google account linked");
  415. const state = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 16 });
  416. await CacheModule.runJob("HSET", {
  417. table: "oauth_google_state",
  418. key: state,
  419. value: user._id.toString()
  420. });
  421. const params = [
  422. `client_id=${config.get("apis.google.client")}`,
  423. `redirect_uri=${config.get("apis.google.redirect_uri")}`,
  424. `scope=https://www.googleapis.com/auth/youtube.readonly`,
  425. `state=${state}`,
  426. `response_type=token`
  427. ].join("&");
  428. return res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);
  429. });
  430. app.get("/auth/google/authorize/callback", async (req, res) => {
  431. if (this.getStatus() !== "READY") {
  432. this.log(
  433. "INFO",
  434. "APP_REJECTED_GOOGLE_AUTHORIZE",
  435. `A user tried to use google authorize, but the APP module is currently not ready.`
  436. );
  437. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  438. }
  439. const { code } = req.query;
  440. let body;
  441. let address;
  442. // TODO parse the proper response from Google, which uses a #
  443. return;
  444. const { state } = req.query;
  445. if (!state) return redirectOnErr(res, "No state given.");
  446. const userId = await CacheModule.runJob("HGET", { table: "oauth_google_state", key: state });
  447. if (!userId) return redirectOnErr(res, "Invalid state.");
  448. const user = await userModel.findOne({ _id: userId });
  449. if (!user) return redirectOnErr(res, "Invalid state");
  450. if (user.services.google && user.services.google.id)
  451. return redirectOnErr(res, "Account already has Google account linked.");
  452. if (req.query.error) return redirectOnErr(res, req.query.error_description);
  453. const { accessToken, refreshToken, results } = await new Promise((resolve, reject) => {
  454. oauth2.getOAuthAccessToken(
  455. code,
  456. { redirect_uri: redirectUri },
  457. (err, accessToken, refreshToken, results) => {
  458. if (err) redirectOnErr(err.message);
  459. else {
  460. resolve({ accessToken, refreshToken, results });
  461. }
  462. }
  463. );
  464. });
  465. if (results.error) return redirectOnErr(res, results.error_description);
  466. const options = {
  467. headers: {
  468. "User-Agent": "request",
  469. Authorization: `token ${accessToken}`
  470. }
  471. };
  472. const google = await axios.get("https://www.googleapis.com/oauth2/v1/userinfo", options);
  473. console.log(321, google);
  474. return;
  475. await userModel.updateOne(
  476. { _id: userId },
  477. {
  478. $set: {
  479. "services.google": {
  480. id: google.data.id,
  481. access_token: accessToken,
  482. refresh_token: refreshToken
  483. }
  484. }
  485. },
  486. { runValidators: true }
  487. );
  488. CacheModule.runJob("PUB", {
  489. channel: "user.linkGoogle",
  490. value: userId
  491. });
  492. CacheModule.runJob("PUB", {
  493. channel: "user.updated",
  494. value: { userId }
  495. });
  496. res.redirect(`${config.get("domain")}/settings?tab=security`);
  497. });
  498. }
  499. app.get("/auth/verify_email", async (req, res) => {
  500. if (this.getStatus() !== "READY") {
  501. this.log(
  502. "INFO",
  503. "APP_REJECTED_VERIFY_EMAIL",
  504. `A user tried to use verify email, but the APP module is currently not ready.`
  505. );
  506. return redirectOnErr(res, "Something went wrong on our end. Please try again later.");
  507. }
  508. const { code } = req.query;
  509. return async.waterfall(
  510. [
  511. next => {
  512. if (!code) return next("Invalid code.");
  513. return next();
  514. },
  515. next => {
  516. userModel.findOne({ "email.verificationToken": code }, next);
  517. },
  518. (user, next) => {
  519. if (!user) return next("User not found.");
  520. if (user.email.verified) return next("This email is already verified.");
  521. return userModel.updateOne(
  522. { "email.verificationToken": code },
  523. {
  524. $set: { "email.verified": true },
  525. $unset: { "email.verificationToken": "" }
  526. },
  527. { runValidators: true },
  528. next
  529. );
  530. }
  531. ],
  532. err => {
  533. if (err) {
  534. let error = "An error occurred.";
  535. if (typeof err === "string") error = err;
  536. else if (err.message) error = err.message;
  537. this.log("ERROR", "VERIFY_EMAIL", `Verifying email failed. "${error}"`);
  538. return res.json({
  539. status: "error",
  540. message: error
  541. });
  542. }
  543. this.log("INFO", "VERIFY_EMAIL", `Successfully verified email.`);
  544. return res.redirect(`${config.get("domain")}?toast=Thank you for verifying your email`);
  545. }
  546. );
  547. });
  548. resolve();
  549. });
  550. }
  551. /**
  552. * Returns the express server
  553. *
  554. * @returns {Promise} - returns promise (reject, resolve)
  555. */
  556. SERVER() {
  557. return new Promise(resolve => {
  558. resolve(AppModule.server);
  559. });
  560. }
  561. /**
  562. * Returns the app object
  563. *
  564. * @returns {Promise} - returns promise (reject, resolve)
  565. */
  566. GET_APP() {
  567. return new Promise(resolve => {
  568. resolve({ app: AppModule.app });
  569. });
  570. }
  571. // EXAMPLE_JOB() {
  572. // return new Promise((resolve, reject) => {
  573. // if (true) resolve({});
  574. // else reject(new Error("Nothing changed."));
  575. // });
  576. // }
  577. }
  578. export default new _AppModule();