users.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. import config from "config";
  2. import axios from "axios";
  3. import bcrypt from "bcrypt";
  4. import sha256 from "sha256";
  5. import CoreClass from "../core";
  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. const avatarColors = ["blue", "orange", "green", "purple", "teal"];
  16. class _UsersModule extends CoreClass {
  17. // eslint-disable-next-line require-jsdoc
  18. constructor() {
  19. super("users");
  20. UsersModule = this;
  21. }
  22. /**
  23. * Initialises the app module
  24. * @returns {Promise} - returns promise (reject, resolve)
  25. */
  26. async initialize() {
  27. DBModule = this.moduleManager.modules.db;
  28. MailModule = this.moduleManager.modules.mail;
  29. WSModule = this.moduleManager.modules.ws;
  30. CacheModule = this.moduleManager.modules.cache;
  31. MediaModule = this.moduleManager.modules.media;
  32. UtilsModule = this.moduleManager.modules.utils;
  33. ActivitiesModule = this.moduleManager.modules.activities;
  34. PlaylistsModule = this.moduleManager.modules.playlists;
  35. this.userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  36. this.dataRequestModel = await DBModule.runJob("GET_MODEL", { modelName: "dataRequest" });
  37. this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" });
  38. this.playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" });
  39. this.activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" });
  40. this.dataRequestEmailSchema = await MailModule.runJob("GET_SCHEMA_ASYNC", { schemaName: "dataRequest" });
  41. this.verifyEmailSchema = await MailModule.runJob("GET_SCHEMA_ASYNC", { schemaName: "verifyEmail" });
  42. this.sessionSchema = await CacheModule.runJob("GET_SCHEMA", {
  43. schemaName: "session"
  44. });
  45. this.appUrl = `${config.get("url.secure") ? "https" : "http"}://${config.get("url.host")}`;
  46. // getOAuthAccessToken uses callbacks by default, so make a helper function to turn it into a promise instead
  47. this.getOAuthAccessToken = (...args) =>
  48. new Promise((resolve, reject) => {
  49. this.oauth2.getOAuthAccessToken(...args, (err, accessToken, refreshToken, results) => {
  50. if (err) reject(err);
  51. else resolve({ accessToken, refreshToken, results });
  52. });
  53. });
  54. if (config.get("apis.oidc.enabled")) {
  55. const openidConfigurationResponse = await axios.get(config.get("apis.oidc.openid_configuration_url"));
  56. const {
  57. authorization_endpoint: authorizationEndpoint,
  58. token_endpoint: tokenEndpoint,
  59. userinfo_endpoint: userinfoEndpoint
  60. } = openidConfigurationResponse.data;
  61. // TODO somehow make this endpoint immutable, if possible in some way
  62. this.oidcAuthorizationEndpoint = authorizationEndpoint;
  63. this.oidcTokenEndpoint = userinfoEndpoint;
  64. this.oidcUserinfoEndpoint = userinfoEndpoint;
  65. this.oidcRedirectUri =
  66. config.get("apis.oidc.redirect_uri").length > 0
  67. ? config.get("apis.oidc.redirect_uri")
  68. : `${this.appUrl}/backend/auth/oidc/authorize/callback`;
  69. //
  70. const clientId = config.get("apis.oidc.client_id");
  71. const clientSecret = config.get("apis.oidc.client_secret");
  72. this.getOIDCOAuthAccessToken = async code => {
  73. const tokenResponse = await axios.post(
  74. tokenEndpoint,
  75. {
  76. grant_type: "authorization_code",
  77. code,
  78. client_id: clientId,
  79. client_secret: clientSecret,
  80. redirect_uri: this.oidcRedirectUri
  81. },
  82. {
  83. headers: {
  84. "Content-Type": "application/x-www-form-urlencoded"
  85. }
  86. }
  87. );
  88. const { access_token: accessToken } = tokenResponse.data;
  89. return { accessToken };
  90. };
  91. }
  92. }
  93. /**
  94. * Removes a user and associated data
  95. * @param {object} payload - object that contains the payload
  96. * @param {string} payload.userId - id of the user to remove
  97. * @returns {Promise} - returns a promise (resolve, reject)
  98. */
  99. async REMOVE_USER(payload) {
  100. const { userId } = payload;
  101. // Create data request, in case the process fails halfway through. An admin can finish the removal manually
  102. const dataRequest = await UsersModule.dataRequestModel.create({ userId, type: "remove" });
  103. await WSModule.runJob(
  104. "EMIT_TO_ROOM",
  105. {
  106. room: "admin.users",
  107. args: ["event:admin.dataRequests.created", { data: { request: dataRequest } }]
  108. },
  109. this
  110. );
  111. if (config.get("sendDataRequestEmails")) {
  112. const adminUsers = await UsersModule.userModel.find({ role: "admin" });
  113. const to = adminUsers.map(adminUser => adminUser.email.address);
  114. await UsersModule.dataRequestEmailSchema(to, userId, "remove");
  115. }
  116. // Delete activities
  117. await UsersModule.activityModel.deleteMany({ userId });
  118. // Delete stations and associated data
  119. const stations = await UsersModule.stationModel.find({ owner: userId });
  120. const stationJobs = stations.map(station => async () => {
  121. const { _id: stationId } = station;
  122. await UsersModule.stationModel.deleteOne({ _id: stationId });
  123. await CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this);
  124. if (!station.playlist) return;
  125. await PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist }, this);
  126. });
  127. await Promise.all(stationJobs);
  128. // Remove user as dj
  129. await UsersModule.stationModel.updateMany({ djs: userId }, { $pull: { djs: userId } });
  130. // Collect songs to adjust ratings for later
  131. const likedPlaylist = await UsersModule.playlistModel.findOne({ createdBy: userId, type: "user-liked" });
  132. const dislikedPlaylist = await UsersModule.playlistModel.findOne({ createdBy: userId, type: "user-disliked" });
  133. const songsToAdjustRatings = [
  134. ...(likedPlaylist?.songs?.map(({ mediaSource }) => mediaSource) ?? []),
  135. ...(dislikedPlaylist?.songs?.map(({ mediaSource }) => mediaSource) ?? [])
  136. ];
  137. // Delete playlists created by user
  138. await UsersModule.playlistModel.deleteMany({ createdBy: userId });
  139. // TODO Maybe we don't need to wait for this to finish?
  140. // Recalculate ratings of songs the user liked/disliked
  141. const recalculateRatingsJobs = songsToAdjustRatings.map(songsToAdjustRating =>
  142. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource: songsToAdjustRating }, this)
  143. );
  144. await Promise.all(recalculateRatingsJobs);
  145. // Delete user object
  146. await UsersModule.userModel.deleteMany({ _id: userId });
  147. // Remove sessions from Redis and MongoDB
  148. await CacheModule.runJob("PUB", { channel: "user.removeSessions", value: userId }, this);
  149. const sessions = await CacheModule.runJob("HGETALL", { table: "sessions" }, this);
  150. const sessionIds = Object.keys(sessions);
  151. const sessionJobs = sessionIds.map(sessionId => async () => {
  152. const session = sessions[sessionId];
  153. if (!session || session.userId !== userId) return;
  154. await CacheModule.runJob("HDEL", { table: "sessions", key: sessionId }, this);
  155. });
  156. await Promise.all(sessionJobs);
  157. await CacheModule.runJob(
  158. "PUB",
  159. {
  160. channel: "user.removeAccount",
  161. value: userId
  162. },
  163. this
  164. );
  165. }
  166. /**
  167. * Tries to verify email from email verification token/code
  168. * @param {object} payload - object that contains the payload
  169. * @param {string} payload.code - email verification token/code
  170. * @returns {Promise} - returns a promise (resolve, reject)
  171. */
  172. async VERIFY_EMAIL(payload) {
  173. const { code } = payload;
  174. if (!code) throw new Error("Invalid code.");
  175. const user = await UsersModule.userModel.findOne({ "email.verificationToken": code });
  176. if (!user) throw new Error("User not found.");
  177. if (user.email.verified) throw new Error("This email is already verified.");
  178. await UsersModule.userModel.updateOne(
  179. { "email.verificationToken": code },
  180. {
  181. $set: { "email.verified": true },
  182. $unset: { "email.verificationToken": "" }
  183. },
  184. { runValidators: true }
  185. );
  186. }
  187. /**
  188. * Handles callback route being accessed, which has data from OIDC during the oauth process
  189. * Will be used to either log the user in or register the user
  190. * @param {object} payload - object that contains the payload
  191. * @param {string} payload.code - code we need to use to get the access token
  192. * @param {string} payload.error - error code if an error occured
  193. * @param {string} payload.errorDescription - error description if an error occured
  194. * @returns {Promise} - returns a promise (resolve, reject)
  195. */
  196. async OIDC_AUTHORIZE_CALLBACK(payload) {
  197. const { code, error, errorDescription } = payload;
  198. if (error) throw new Error(errorDescription);
  199. // Tries to get access token. We don't use the refresh token currently
  200. const { accessToken } = await UsersModule.getOIDCOAuthAccessToken(code);
  201. // Gets user data
  202. const userInfoResponse = await axios.post(
  203. UsersModule.oidcUserinfoEndpoint,
  204. {},
  205. {
  206. headers: {
  207. Authorization: `Bearer ${accessToken}`
  208. }
  209. }
  210. );
  211. if (!userInfoResponse.data.preferred_username) throw new Error("Something went wrong, no preferred_username.");
  212. // TODO verify sub from userinfo and token response, see 5.3.2 https://openid.net/specs/openid-connect-core-1_0.html
  213. const user = await UsersModule.userModel.findOne({ "services.oidc.sub": userInfoResponse.data.sub });
  214. let userId;
  215. if (user) {
  216. // Refresh access token, though it's pretty useless as it'll probably expire and then be useless,
  217. // and we don't use it afterwards at all anyways
  218. user.services.oidc.access_token = accessToken;
  219. await user.save();
  220. userId = user._id;
  221. } else {
  222. // Try to register the user. Will throw an error if it's unable to do so or any error occurs
  223. ({ userId } = await UsersModule.runJob(
  224. "OIDC_AUTHORIZE_CALLBACK_REGISTER",
  225. { userInfoResponse: userInfoResponse.data, accessToken },
  226. this
  227. ));
  228. }
  229. // Create session for the userId gotten above, as the user existed or was successfully registered
  230. const sessionId = await UtilsModule.runJob("GUID", {}, this);
  231. await CacheModule.runJob(
  232. "HSET",
  233. {
  234. table: "sessions",
  235. key: sessionId,
  236. value: UsersModule.sessionSchema(sessionId, userId.toString())
  237. },
  238. this
  239. );
  240. return { sessionId, userId, redirectUrl: UsersModule.appUrl };
  241. }
  242. /**
  243. * Handles registering the user in the OIDC login/register callback/process
  244. * @param {object} payload - object that contains the payload
  245. * @param {string} payload.userInfoResponse - data we got from the OIDC user info API endpoint
  246. * @param {string} payload.accessToken - access token for the OIDC user
  247. * @returns {Promise} - returns a promise (resolve, reject)
  248. */
  249. async OIDC_AUTHORIZE_CALLBACK_REGISTER(payload) {
  250. const { userInfoResponse, accessToken } = payload;
  251. let user;
  252. // Check if username already exists
  253. user = await UsersModule.userModel.findOne({
  254. username: new RegExp(`^${userInfoResponse.preferred_username}$`, "i")
  255. });
  256. if (user) throw new Error(`An account with that username already exists.`); // TODO eventually we'll want users to be able to pick their own username maybe
  257. const emailAddress = userInfoResponse.email;
  258. if (!emailAddress) throw new Error("No email address found.");
  259. user = await UsersModule.userModel.findOne({ "email.address": emailAddress });
  260. if (user) throw new Error(`An account with that email address already exists.`);
  261. const userId = await UtilsModule.runJob(
  262. "GENERATE_RANDOM_STRING",
  263. {
  264. length: 12
  265. },
  266. this
  267. );
  268. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  269. const gravatarUrl = await UtilsModule.runJob(
  270. "CREATE_GRAVATAR",
  271. {
  272. email: emailAddress
  273. },
  274. this
  275. );
  276. const likedSongsPlaylist = await PlaylistsModule.runJob(
  277. "CREATE_USER_PLAYLIST",
  278. {
  279. userId,
  280. displayName: "Liked Songs",
  281. type: "user-liked"
  282. },
  283. this
  284. );
  285. const dislikedSongsPlaylist = await PlaylistsModule.runJob(
  286. "CREATE_USER_PLAYLIST",
  287. {
  288. userId,
  289. displayName: "Disliked Songs",
  290. type: "user-disliked"
  291. },
  292. this
  293. );
  294. user = {
  295. _id: userId,
  296. username: userInfoResponse.preferred_username,
  297. name: userInfoResponse.name,
  298. location: "",
  299. bio: "",
  300. email: {
  301. address: emailAddress,
  302. verificationToken
  303. },
  304. services: {
  305. oidc: {
  306. sub: userInfoResponse.sub,
  307. access_token: accessToken
  308. }
  309. },
  310. avatar: {
  311. type: "gravatar",
  312. url: gravatarUrl
  313. },
  314. likedSongsPlaylist,
  315. dislikedSongsPlaylist
  316. };
  317. await UsersModule.userModel.create(user);
  318. await UsersModule.verifyEmailSchema(emailAddress, userInfoResponse.preferred_username, verificationToken);
  319. await ActivitiesModule.runJob(
  320. "ADD_ACTIVITY",
  321. {
  322. userId,
  323. type: "user__joined",
  324. payload: { message: "Welcome to Musare!" }
  325. },
  326. this
  327. );
  328. return {
  329. userId
  330. };
  331. }
  332. /**
  333. * Attempts to register a user
  334. * @param {object} payload - object that contains the payload
  335. * @param {string} payload.email - email
  336. * @param {string} payload.username - username
  337. * @param {string} payload.password - plaintext password
  338. * @param {string} payload.recaptcha - recaptcha, if recaptcha is enabled
  339. * @returns {Promise} - returns a promise (resolve, reject)
  340. */
  341. async REGISTER(payload) {
  342. const { username, password, recaptcha } = payload;
  343. let { email } = payload;
  344. email = email.toLowerCase().trim();
  345. if (config.get("registrationDisabled") === true || config.get("apis.oidc.enabled") === true)
  346. throw new Error("Registration is not allowed at this time.");
  347. if (Array.isArray(config.get("experimental.registration_email_whitelist"))) {
  348. const experimentalRegistrationEmailWhitelist = config.get("experimental.registration_email_whitelist");
  349. const anyRegexPassed = experimentalRegistrationEmailWhitelist.find(regex => {
  350. const emailWhitelistRegex = new RegExp(regex);
  351. return emailWhitelistRegex.test(email);
  352. });
  353. if (!anyRegexPassed) throw new Error("Your email is not allowed to register.");
  354. }
  355. if (!DBModule.passwordValid(password))
  356. throw new Error("Invalid password. Check if it meets all the requirements.");
  357. if (config.get("apis.recaptcha.enabled") === true) {
  358. const recaptchaBody = await axios.post("https://www.google.com/recaptcha/api/siteverify", {
  359. data: {
  360. secret: config.get("apis").recaptcha.secret,
  361. response: recaptcha
  362. }
  363. });
  364. if (recaptchaBody.success !== true) throw new Error("Response from recaptcha was not successful.");
  365. }
  366. let user = await UsersModule.userModel.findOne({ username: new RegExp(`^${username}$`, "i") });
  367. if (user) throw new Error("A user with that username already exists.");
  368. user = await UsersModule.userModel.findOne({ "email.address": email });
  369. if (user) throw new Error("A user with that email already exists.");
  370. const salt = await bcrypt.genSalt(10);
  371. const hash = await bcrypt.hash(sha256(password), salt);
  372. const userId = await UtilsModule.runJob(
  373. "GENERATE_RANDOM_STRING",
  374. {
  375. length: 12
  376. },
  377. this
  378. );
  379. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  380. const gravatarUrl = await UtilsModule.runJob(
  381. "CREATE_GRAVATAR",
  382. {
  383. email
  384. },
  385. this
  386. );
  387. const likedSongsPlaylist = await PlaylistsModule.runJob(
  388. "CREATE_USER_PLAYLIST",
  389. {
  390. userId,
  391. displayName: "Liked Songs",
  392. type: "user-liked"
  393. },
  394. this
  395. );
  396. const dislikedSongsPlaylist = await PlaylistsModule.runJob(
  397. "CREATE_USER_PLAYLIST",
  398. {
  399. userId,
  400. displayName: "Disliked Songs",
  401. type: "user-disliked"
  402. },
  403. this
  404. );
  405. user = {
  406. _id: userId,
  407. name: username,
  408. username,
  409. email: {
  410. address: email,
  411. verificationToken
  412. },
  413. services: {
  414. password: {
  415. password: hash
  416. }
  417. },
  418. avatar: {
  419. type: "initials",
  420. color: avatarColors[Math.floor(Math.random() * avatarColors.length)],
  421. url: gravatarUrl
  422. },
  423. likedSongsPlaylist,
  424. dislikedSongsPlaylist
  425. };
  426. await UsersModule.userModel.create(user);
  427. await UsersModule.verifyEmailSchema(email, username, verificationToken);
  428. await ActivitiesModule.runJob(
  429. "ADD_ACTIVITY",
  430. {
  431. userId,
  432. type: "user__joined",
  433. payload: { message: "Welcome to Musare!" }
  434. },
  435. this
  436. );
  437. return {
  438. userId
  439. };
  440. }
  441. /**
  442. * Attempts to update the email address of a user
  443. * @param {object} payload - object that contains the payload
  444. * @param {string} payload.userId - userId
  445. * @param {string} payload.email - new email
  446. * @returns {Promise} - returns a promise (resolve, reject)
  447. */
  448. async UPDATE_EMAIL(payload) {
  449. const { userId } = payload;
  450. let { email } = payload;
  451. email = email.toLowerCase().trim();
  452. const user = await UsersModule.userModel.findOne({ _id: userId });
  453. if (!user) throw new Error("User not found.");
  454. if (user.email.address === email) throw new Error("New email can't be the same as your the old email.");
  455. const existingUser = UsersModule.userModel.findOne({ "email.address": email });
  456. if (existingUser) throw new Error("That email is already in use.");
  457. const gravatarUrl = await UtilsModule.runJob("CREATE_GRAVATAR", { email }, this);
  458. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  459. await UsersModule.userModel.updateOne(
  460. { _id: userId },
  461. {
  462. $set: {
  463. "avatar.url": gravatarUrl,
  464. "email.address": email,
  465. "email.verified": false,
  466. "email.verificationToken": verificationToken
  467. }
  468. },
  469. { runValidators: true }
  470. );
  471. await UsersModule.verifyEmailSchema(email, user.username, verificationToken);
  472. }
  473. /**
  474. * Attempts to update the username of a user
  475. * @param {object} payload - object that contains the payload
  476. * @param {string} payload.userId - userId
  477. * @param {string} payload.username - new username
  478. * @returns {Promise} - returns a promise (resolve, reject)
  479. */
  480. async UPDATE_USERNAME(payload) {
  481. const { userId, username } = payload;
  482. const user = await UsersModule.userModel.findOne({ _id: userId });
  483. if (!user) throw new Error("User not found.");
  484. if (user.username === username) throw new Error("New username can't be the same as the old username.");
  485. const existingUser = await UsersModule.userModel.findOne({ username: new RegExp(`^${username}$`, "i") });
  486. if (existingUser) throw new Error("That username is already in use.");
  487. await UsersModule.userModel.updateOne({ _id: userId }, { $set: { username } }, { runValidators: true });
  488. }
  489. // async EXAMPLE_JOB() {
  490. // if (true) return;
  491. // else throw new Error("Nothing changed.");
  492. // }
  493. }
  494. export default new _UsersModule();