users.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. // TODO we don't use linking for OIDC currently, so remove this or utilize it in some other way if needed
  214. // If we specified a state in the first step when we redirected the user to OIDC, it was to link a
  215. // OIDC account to an existing Musare account, so continue with a job specifically for linking the account
  216. // if (state)
  217. // return UsersModule.runJob(
  218. // "OIDC_AUTHORIZE_CALLBACK_LINK",
  219. // { state, sub: userInfoResponse.data.sub, accessToken },
  220. // this
  221. // );
  222. const user = await UsersModule.userModel.findOne({ "services.oidc.sub": userInfoResponse.data.sub });
  223. let userId;
  224. if (user) {
  225. // Refresh access token, though it's pretty useless as it'll probably expire and then be useless,
  226. // and we don't use it afterwards at all anyways
  227. user.services.oidc.access_token = accessToken;
  228. await user.save();
  229. userId = user._id;
  230. } else {
  231. // Try to register the user. Will throw an error if it's unable to do so or any error occurs
  232. ({ userId } = await UsersModule.runJob(
  233. "OIDC_AUTHORIZE_CALLBACK_REGISTER",
  234. { userInfoResponse: userInfoResponse.data, accessToken },
  235. this
  236. ));
  237. }
  238. // Create session for the userId gotten above, as the user existed or was successfully registered
  239. const sessionId = await UtilsModule.runJob("GUID", {}, this);
  240. await CacheModule.runJob(
  241. "HSET",
  242. {
  243. table: "sessions",
  244. key: sessionId,
  245. value: UsersModule.sessionSchema(sessionId, userId.toString())
  246. },
  247. this
  248. );
  249. return { sessionId, userId, redirectUrl: UsersModule.appUrl };
  250. }
  251. /**
  252. * Handles registering the user in the OIDC login/register/link callback/process
  253. * @param {object} payload - object that contains the payload
  254. * @param {string} payload.userInfoResponse - data we got from the OIDC user info API endpoint
  255. * @param {string} payload.accessToken - access token for the OIDC user
  256. * @returns {Promise} - returns a promise (resolve, reject)
  257. */
  258. async OIDC_AUTHORIZE_CALLBACK_REGISTER(payload) {
  259. const { userInfoResponse, accessToken } = payload;
  260. let user;
  261. // Check if username already exists
  262. user = await UsersModule.userModel.findOne({
  263. username: new RegExp(`^${userInfoResponse.preferred_username}$`, "i")
  264. });
  265. 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
  266. const emailAddress = userInfoResponse.email;
  267. if (!emailAddress) throw new Error("No email address found.");
  268. user = await UsersModule.userModel.findOne({ "email.address": emailAddress });
  269. if (user) throw new Error(`An account with that email address already exists.`);
  270. const userId = await UtilsModule.runJob(
  271. "GENERATE_RANDOM_STRING",
  272. {
  273. length: 12
  274. },
  275. this
  276. );
  277. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  278. const gravatarUrl = await UtilsModule.runJob(
  279. "CREATE_GRAVATAR",
  280. {
  281. email: emailAddress
  282. },
  283. this
  284. );
  285. const likedSongsPlaylist = await PlaylistsModule.runJob(
  286. "CREATE_USER_PLAYLIST",
  287. {
  288. userId,
  289. displayName: "Liked Songs",
  290. type: "user-liked"
  291. },
  292. this
  293. );
  294. const dislikedSongsPlaylist = await PlaylistsModule.runJob(
  295. "CREATE_USER_PLAYLIST",
  296. {
  297. userId,
  298. displayName: "Disliked Songs",
  299. type: "user-disliked"
  300. },
  301. this
  302. );
  303. user = {
  304. _id: userId,
  305. username: userInfoResponse.preferred_username,
  306. name: userInfoResponse.name,
  307. location: "",
  308. bio: "",
  309. email: {
  310. address: emailAddress,
  311. verificationToken
  312. },
  313. services: {
  314. oidc: {
  315. sub: userInfoResponse.sub,
  316. access_token: accessToken
  317. }
  318. },
  319. avatar: {
  320. type: "gravatar",
  321. url: gravatarUrl
  322. },
  323. likedSongsPlaylist,
  324. dislikedSongsPlaylist
  325. };
  326. await UsersModule.userModel.create(user);
  327. await UsersModule.verifyEmailSchema(emailAddress, userInfoResponse.preferred_username, verificationToken);
  328. await ActivitiesModule.runJob(
  329. "ADD_ACTIVITY",
  330. {
  331. userId,
  332. type: "user__joined",
  333. payload: { message: "Welcome to Musare!" }
  334. },
  335. this
  336. );
  337. return {
  338. userId
  339. };
  340. }
  341. /**
  342. * Attempts to register a user
  343. * @param {object} payload - object that contains the payload
  344. * @param {string} payload.email - email
  345. * @param {string} payload.username - username
  346. * @param {string} payload.password - plaintext password
  347. * @param {string} payload.recaptcha - recaptcha, if recaptcha is enabled
  348. * @returns {Promise} - returns a promise (resolve, reject)
  349. */
  350. async REGISTER(payload) {
  351. const { username, password, recaptcha } = payload;
  352. let { email } = payload;
  353. email = email.toLowerCase().trim();
  354. if (config.get("registrationDisabled") === true || config.get("apis.oidc.enabled") === true)
  355. throw new Error("Registration is not allowed at this time.");
  356. if (Array.isArray(config.get("experimental.registration_email_whitelist"))) {
  357. const experimentalRegistrationEmailWhitelist = config.get("experimental.registration_email_whitelist");
  358. const anyRegexPassed = experimentalRegistrationEmailWhitelist.find(regex => {
  359. const emailWhitelistRegex = new RegExp(regex);
  360. return emailWhitelistRegex.test(email);
  361. });
  362. if (!anyRegexPassed) throw new Error("Your email is not allowed to register.");
  363. }
  364. if (!DBModule.passwordValid(password))
  365. throw new Error("Invalid password. Check if it meets all the requirements.");
  366. if (config.get("apis.recaptcha.enabled") === true) {
  367. const recaptchaBody = await axios.post("https://www.google.com/recaptcha/api/siteverify", {
  368. data: {
  369. secret: config.get("apis").recaptcha.secret,
  370. response: recaptcha
  371. }
  372. });
  373. if (recaptchaBody.success !== true) throw new Error("Response from recaptcha was not successful.");
  374. }
  375. let user = await UsersModule.userModel.findOne({ username: new RegExp(`^${username}$`, "i") });
  376. if (user) throw new Error("A user with that username already exists.");
  377. user = await UsersModule.userModel.findOne({ "email.address": email });
  378. if (user) throw new Error("A user with that email already exists.");
  379. const salt = await bcrypt.genSalt(10);
  380. const hash = await bcrypt.hash(sha256(password), salt);
  381. const userId = await UtilsModule.runJob(
  382. "GENERATE_RANDOM_STRING",
  383. {
  384. length: 12
  385. },
  386. this
  387. );
  388. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  389. const gravatarUrl = await UtilsModule.runJob(
  390. "CREATE_GRAVATAR",
  391. {
  392. email
  393. },
  394. this
  395. );
  396. const likedSongsPlaylist = await PlaylistsModule.runJob(
  397. "CREATE_USER_PLAYLIST",
  398. {
  399. userId,
  400. displayName: "Liked Songs",
  401. type: "user-liked"
  402. },
  403. this
  404. );
  405. const dislikedSongsPlaylist = await PlaylistsModule.runJob(
  406. "CREATE_USER_PLAYLIST",
  407. {
  408. userId,
  409. displayName: "Disliked Songs",
  410. type: "user-disliked"
  411. },
  412. this
  413. );
  414. user = {
  415. _id: userId,
  416. name: username,
  417. username,
  418. email: {
  419. address: email,
  420. verificationToken
  421. },
  422. services: {
  423. password: {
  424. password: hash
  425. }
  426. },
  427. avatar: {
  428. type: "initials",
  429. color: avatarColors[Math.floor(Math.random() * avatarColors.length)],
  430. url: gravatarUrl
  431. },
  432. likedSongsPlaylist,
  433. dislikedSongsPlaylist
  434. };
  435. await UsersModule.userModel.create(user);
  436. await UsersModule.verifyEmailSchema(email, username, verificationToken);
  437. await ActivitiesModule.runJob(
  438. "ADD_ACTIVITY",
  439. {
  440. userId,
  441. type: "user__joined",
  442. payload: { message: "Welcome to Musare!" }
  443. },
  444. this
  445. );
  446. return {
  447. userId
  448. };
  449. }
  450. /**
  451. * Attempts to update the email address of a user
  452. * @param {object} payload - object that contains the payload
  453. * @param {string} payload.userId - userId
  454. * @param {string} payload.email - new email
  455. * @returns {Promise} - returns a promise (resolve, reject)
  456. */
  457. async UPDATE_EMAIL(payload) {
  458. const { userId } = payload;
  459. let { email } = payload;
  460. email = email.toLowerCase().trim();
  461. const user = await UsersModule.userModel.findOne({ _id: userId });
  462. if (!user) throw new Error("User not found.");
  463. if (user.email.address === email) throw new Error("New email can't be the same as your the old email.");
  464. const existingUser = UsersModule.userModel.findOne({ "email.address": email });
  465. if (existingUser) throw new Error("That email is already in use.");
  466. const gravatarUrl = await UtilsModule.runJob("CREATE_GRAVATAR", { email }, this);
  467. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  468. await UsersModule.userModel.updateOne(
  469. { _id: userId },
  470. {
  471. $set: {
  472. "avatar.url": gravatarUrl,
  473. "email.address": email,
  474. "email.verified": false,
  475. "email.verificationToken": verificationToken
  476. }
  477. },
  478. { runValidators: true }
  479. );
  480. await UsersModule.verifyEmailSchema(email, user.username, verificationToken);
  481. }
  482. /**
  483. * Attempts to update the username of a user
  484. * @param {object} payload - object that contains the payload
  485. * @param {string} payload.userId - userId
  486. * @param {string} payload.username - new username
  487. * @returns {Promise} - returns a promise (resolve, reject)
  488. */
  489. async UPDATE_USERNAME(payload) {
  490. const { userId, username } = payload;
  491. const user = await UsersModule.userModel.findOne({ _id: userId });
  492. if (!user) throw new Error("User not found.");
  493. if (user.username === username) throw new Error("New username can't be the same as the old username.");
  494. const existingUser = await UsersModule.userModel.findOne({ username: new RegExp(`^${username}$`, "i") });
  495. if (existingUser) throw new Error("That username is already in use.");
  496. await UsersModule.userModel.updateOne({ _id: userId }, { $set: { username } }, { runValidators: true });
  497. }
  498. // async EXAMPLE_JOB() {
  499. // if (true) return;
  500. // else throw new Error("Nothing changed.");
  501. // }
  502. }
  503. export default new _UsersModule();