users.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import config from "config";
  2. import oauth from "oauth";
  3. import axios from "axios";
  4. import CoreClass from "../core";
  5. const { OAuth2 } = oauth;
  6. let UsersModule;
  7. let MailModule;
  8. let CacheModule;
  9. let DBModule;
  10. let PlaylistsModule;
  11. let WSModule;
  12. let MediaModule;
  13. let UtilsModule;
  14. let ActivitiesModule;
  15. class _UsersModule extends CoreClass {
  16. // eslint-disable-next-line require-jsdoc
  17. constructor() {
  18. super("users");
  19. UsersModule = this;
  20. }
  21. /**
  22. * Initialises the app module
  23. * @returns {Promise} - returns promise (reject, resolve)
  24. */
  25. async initialize() {
  26. DBModule = this.moduleManager.modules.db;
  27. MailModule = this.moduleManager.modules.mail;
  28. WSModule = this.moduleManager.modules.ws;
  29. CacheModule = this.moduleManager.modules.cache;
  30. MediaModule = this.moduleManager.modules.media;
  31. UtilsModule = this.moduleManager.modules.utils;
  32. ActivitiesModule = this.moduleManager.modules.activities;
  33. PlaylistsModule = this.moduleManager.modules.playlists;
  34. this.userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  35. this.dataRequestModel = await DBModule.runJob("GET_MODEL", { modelName: "dataRequest" });
  36. this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" });
  37. this.playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" });
  38. this.activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" });
  39. this.dataRequestEmailSchema = await MailModule.runJob("GET_SCHEMA_ASYNC", { schemaName: "dataRequest" });
  40. this.verifyEmailSchema = await MailModule.runJob("GET_SCHEMA_ASYNC", { schemaName: "verifyEmail" });
  41. this.sessionSchema = await CacheModule.runJob("GET_SCHEMA", {
  42. schemaName: "session"
  43. });
  44. this.appUrl = `${config.get("url.secure") ? "https" : "http"}://${config.get("url.host")}`;
  45. this.redirectUri =
  46. config.get("apis.github.redirect_uri").length > 0
  47. ? config.get("apis.github.redirect_uri")
  48. : `${this.appUrl}/backend/auth/github/authorize/callback`;
  49. this.oauth2 = new OAuth2(
  50. config.get("apis.github.client"),
  51. config.get("apis.github.secret"),
  52. "https://github.com/",
  53. "login/oauth/authorize",
  54. "login/oauth/access_token",
  55. null
  56. );
  57. // getOAuthAccessToken uses callbacks by default, so make a helper function to turn it into a promise instead
  58. this.getOAuthAccessToken = (...args) =>
  59. new Promise((resolve, reject) => {
  60. this.oauth2.getOAuthAccessToken(...args, (err, accessToken, refreshToken, results) => {
  61. if (err) reject(err);
  62. else resolve({ accessToken, refreshToken, results });
  63. });
  64. });
  65. }
  66. /**
  67. * Removes a user and associated data
  68. * @param {object} payload - object that contains the payload
  69. * @param {string} payload.userId - id of the user to remove
  70. * @returns {Promise} - returns a promise (resolve, reject)
  71. */
  72. async REMOVE_USER(payload) {
  73. const { userId } = payload;
  74. // Create data request, in case the process fails halfway through. An admin can finish the removal manually
  75. const dataRequest = await UsersModule.dataRequestModel.create({ userId, type: "remove" });
  76. await WSModule.runJob(
  77. "EMIT_TO_ROOM",
  78. {
  79. room: "admin.users",
  80. args: ["event:admin.dataRequests.created", { data: { request: dataRequest } }]
  81. },
  82. this
  83. );
  84. if (config.get("sendDataRequestEmails")) {
  85. const adminUsers = await UsersModule.userModel.find({ role: "admin" });
  86. const to = adminUsers.map(adminUser => adminUser.email.address);
  87. await UsersModule.dataRequestEmailSchema(to, userId, "remove");
  88. }
  89. // Delete activities
  90. await UsersModule.activityModel.deleteMany({ userId });
  91. // Delete stations and associated data
  92. const stations = await UsersModule.stationModel.find({ owner: userId });
  93. const stationJobs = stations.map(station => async () => {
  94. const { _id: stationId } = station;
  95. await UsersModule.stationModel.deleteOne({ _id: stationId });
  96. await CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this);
  97. if (!station.playlist) return;
  98. await PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist }, this);
  99. });
  100. await Promise.all(stationJobs);
  101. // Remove user as dj
  102. await UsersModule.stationModel.updateMany({ djs: userId }, { $pull: { djs: userId } });
  103. // Collect songs to adjust ratings for later
  104. const likedPlaylist = await UsersModule.playlistModel.findOne({ createdBy: userId, type: "user-liked" });
  105. const dislikedPlaylist = await UsersModule.playlistModel.findOne({ createdBy: userId, type: "user-disliked" });
  106. const songsToAdjustRatings = [
  107. ...(likedPlaylist?.songs?.map(({ mediaSource }) => mediaSource) ?? []),
  108. ...(dislikedPlaylist?.songs?.map(({ mediaSource }) => mediaSource) ?? [])
  109. ];
  110. // Delete playlists created by user
  111. await UsersModule.playlistModel.deleteMany({ createdBy: userId });
  112. // TODO Maybe we don't need to wait for this to finish?
  113. // Recalculate ratings of songs the user liked/disliked
  114. const recalculateRatingsJobs = songsToAdjustRatings.map(songsToAdjustRating =>
  115. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource: songsToAdjustRating }, this)
  116. );
  117. await Promise.all(recalculateRatingsJobs);
  118. // Delete user object
  119. await UsersModule.userModel.deleteMany({ _id: userId });
  120. // Remove sessions from Redis and MongoDB
  121. await CacheModule.runJob("PUB", { channel: "user.removeSessions", value: userId }, this);
  122. const sessions = await CacheModule.runJob("HGETALL", { table: "sessions" }, this);
  123. const sessionIds = Object.keys(sessions);
  124. const sessionJobs = sessionIds.map(sessionId => async () => {
  125. const session = sessions[sessionId];
  126. if (!session || session.userId !== userId) return;
  127. await CacheModule.runJob("HDEL", { table: "sessions", key: sessionId }, this);
  128. });
  129. await Promise.all(sessionJobs);
  130. await CacheModule.runJob(
  131. "PUB",
  132. {
  133. channel: "user.removeAccount",
  134. value: userId
  135. },
  136. this
  137. );
  138. }
  139. /**
  140. * Tries to verify email from email verification token/code
  141. * @param {object} payload - object that contains the payload
  142. * @param {string} payload.code - email verification token/code
  143. * @returns {Promise} - returns a promise (resolve, reject)
  144. */
  145. async VERIFY_EMAIL(payload) {
  146. const { code } = payload;
  147. if (!code) throw new Error("Invalid code.");
  148. const user = await UsersModule.userModel.findOne({ "email.verificationToken": code });
  149. if (!user) throw new Error("User not found.");
  150. if (user.email.verified) throw new Error("This email is already verified.");
  151. await UsersModule.userModel.updateOne(
  152. { "email.verificationToken": code },
  153. {
  154. $set: { "email.verified": true },
  155. $unset: { "email.verificationToken": "" }
  156. },
  157. { runValidators: true }
  158. );
  159. }
  160. /**
  161. * Handles callback route being accessed, which has data from GitHub during the oauth process
  162. * Will be used to either log the user in, register the user, or link the GitHub account to an existing account
  163. * @param {object} payload - object that contains the payload
  164. * @param {string} payload.code - code we need to use to get the access token
  165. * @param {string} payload.state - custom state we may have passed to GitHub during the first step
  166. * @param {string} payload.error - error code if an error occured
  167. * @param {string} payload.errorDescription - error description if an error occured
  168. * @returns {Promise} - returns a promise (resolve, reject)
  169. */
  170. async GITHUB_AUTHORIZE_CALLBACK(payload) {
  171. const { code, state, error, errorDescription } = payload;
  172. if (error) throw new Error(errorDescription);
  173. // Tries to get access token. We don't use the refresh token currently
  174. const { accessToken, /* refreshToken, */ results } = await UsersModule.getOAuthAccessToken(code, {
  175. redirect_uri: UsersModule.redirectUri
  176. });
  177. if (!accessToken) throw new Error(results.error_description);
  178. const options = {
  179. headers: {
  180. "User-Agent": "request",
  181. Authorization: `token ${accessToken}`
  182. }
  183. };
  184. // Gets user data
  185. const githubUserData = await axios.get("https://api.github.com/user", options);
  186. if (githubUserData.status !== 200) throw new Error(githubUserData.data.message);
  187. if (!githubUserData.data.id) throw new Error("Something went wrong, no id.");
  188. // If we specified a state in the first step when we redirected the user to GitHub, it was to link a
  189. // GitHub account to an existing Musare account, so continue with a job specifically for linking the account
  190. if (state)
  191. return UsersModule.runJob(
  192. "GITHUB_AUTHORIZE_CALLBACK_LINK",
  193. { state, githubId: githubUserData.data.id, accessToken },
  194. this
  195. );
  196. const user = await UsersModule.userModel.findOne({ "services.github.id": githubUserData.data.id });
  197. let userId;
  198. if (user) {
  199. // Refresh access token, though it's pretty useless as it'll probably expire and then be useless,
  200. // and we don't use it afterwards at all
  201. user.services.github.access_token = accessToken;
  202. await user.save();
  203. userId = user._id;
  204. } else {
  205. // Try to register the user. Will throw an error if it's unable to do so or any error occurs
  206. userId = await UsersModule.runJob(
  207. "GITHUB_AUTHORIZE_CALLBACK_REGISTER",
  208. { githubUserData, accessToken },
  209. this
  210. );
  211. }
  212. // Create session for the userId gotten above, as the user existed or was successfully registered
  213. const sessionId = await UtilsModule.runJob("GUID", {}, this);
  214. await CacheModule.runJob(
  215. "HSET",
  216. {
  217. table: "sessions",
  218. key: sessionId,
  219. value: UsersModule.sessionSchema(sessionId, userId)
  220. },
  221. this
  222. );
  223. return { sessionId, userId, redirectUrl: UsersModule.appUrl };
  224. }
  225. /**
  226. * Handles registering the user in the GitHub login/register/link callback/process
  227. * @param {object} payload - object that contains the payload
  228. * @param {string} payload.githubUserData - data we got from the /user API endpoint from GitHub
  229. * @param {string} payload.accessToken - access token for the GitHub user
  230. * @returns {Promise} - returns a promise (resolve, reject)
  231. */
  232. async GITHUB_AUTHORIZE_CALLBACK_REGISTER(payload) {
  233. const { githubUserData, accessToken } = payload;
  234. let user;
  235. // Check if username already exists
  236. user = await UsersModule.userModel.findOne({ username: new RegExp(`^${githubUserData.data.login}$`, "i") });
  237. if (user) throw new Error(`An account with that username already exists.`);
  238. // Get emails used for GitHub account
  239. const githubEmailsData = await axios.get("https://api.github.com/user/emails", {
  240. headers: {
  241. "User-Agent": "request",
  242. Authorization: `token ${accessToken}`
  243. }
  244. });
  245. if (!Array.isArray(githubEmailsData.data)) throw new Error(githubEmailsData.message);
  246. const primaryEmailAddress = githubEmailsData.data.find(emailAddress => emailAddress.primary)?.email;
  247. if (!primaryEmailAddress) throw new Error("No primary email address found.");
  248. user = await UsersModule.userModel.findOne({ "email.address": primaryEmailAddress });
  249. if (user && Object.keys(JSON.parse(user.services.github)).length === 0)
  250. throw new Error(`An account with that email address exists, but is not linked to GitHub.`);
  251. if (user) throw new Error(`An account with that email address already exists.`);
  252. const userId = await UtilsModule.runJob(
  253. "GENERATE_RANDOM_STRING",
  254. {
  255. length: 12
  256. },
  257. this
  258. );
  259. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  260. const gravatarUrl = await UtilsModule.runJob(
  261. "CREATE_GRAVATAR",
  262. {
  263. email: primaryEmailAddress
  264. },
  265. this
  266. );
  267. const likedSongsPlaylist = await PlaylistsModule.runJob(
  268. "CREATE_USER_PLAYLIST",
  269. {
  270. userId,
  271. displayName: "Liked Songs",
  272. type: "user-liked"
  273. },
  274. this
  275. );
  276. const dislikedSongsPlaylist = await PlaylistsModule.runJob(
  277. "CREATE_USER_PLAYLIST",
  278. {
  279. userId,
  280. displayName: "Disliked Songs",
  281. type: "user-disliked"
  282. },
  283. this
  284. );
  285. user = {
  286. _id: userId,
  287. username: githubUserData.data.login,
  288. name: githubUserData.data.name,
  289. location: githubUserData.data.location,
  290. bio: githubUserData.data.bio,
  291. email: {
  292. primaryEmailAddress,
  293. verificationToken
  294. },
  295. services: {
  296. github: {
  297. id: githubUserData.data.id,
  298. access_token: accessToken
  299. }
  300. },
  301. avatar: {
  302. type: "gravatar",
  303. url: gravatarUrl
  304. },
  305. likedSongsPlaylist,
  306. dislikedSongsPlaylist
  307. };
  308. await UsersModule.userModel.create(user);
  309. await UsersModule.verifyEmailSchema(primaryEmailAddress, githubUserData.data.login, verificationToken);
  310. await ActivitiesModule.runJob(
  311. "ADD_ACTIVITY",
  312. {
  313. userId,
  314. type: "user__joined",
  315. payload: { message: "Welcome to Musare!" }
  316. },
  317. this
  318. );
  319. return {
  320. userId
  321. };
  322. }
  323. /**
  324. * Job to attempt to link a GitHub user to a Musare account
  325. * @param {object} payload - object that contains the payload
  326. * @param {string} payload.state - state we passed to GitHub and got back from GitHub
  327. * @param {string} payload.githubId - GitHub user id
  328. * @param {string} payload.accessToken - GitHub user access token
  329. * @returns {Promise} - returns a promise (resolve, reject)
  330. */
  331. async GITHUB_AUTHORIZE_CALLBACK_LINK(payload) {
  332. const { state, githubId, accessToken } = payload;
  333. // State is currently the session id (SID), so check if that session (still) exists
  334. const session = await CacheModule.runJob(
  335. "HGET",
  336. {
  337. table: "sessions",
  338. key: state
  339. },
  340. this
  341. );
  342. if (!session) throw new Error("Invalid session.");
  343. const user = await UsersModule.userModel.findOne({ _id: session.userId });
  344. if (!user) throw new Error("User not found.");
  345. if (user.services.github && user.services.github.id) throw new Error("Account already has GitHub linked.");
  346. const { _id: userId } = user;
  347. await UsersModule.userModel.updateOne(
  348. { _id: userId },
  349. {
  350. $set: {
  351. "services.github": {
  352. id: githubId,
  353. access_token: accessToken
  354. }
  355. }
  356. },
  357. { runValidators: true }
  358. );
  359. await CacheModule.runJob(
  360. "PUB",
  361. {
  362. channel: "user.linkGithub",
  363. value: userId
  364. },
  365. this
  366. );
  367. await CacheModule.runJob(
  368. "PUB",
  369. {
  370. channel: "user.updated",
  371. value: { userId }
  372. },
  373. this
  374. );
  375. return {
  376. redirectUrl: `${UsersModule.appUrl}/settings?tab=security`
  377. };
  378. }
  379. // async EXAMPLE_JOB() {
  380. // if (true) return;
  381. // else throw new Error("Nothing changed.");
  382. // }
  383. }
  384. export default new _UsersModule();