users.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. import config from "config";
  2. import oauth from "oauth";
  3. import axios from "axios";
  4. import bcrypt from "bcrypt";
  5. import sha256 from "sha256";
  6. import CoreClass from "../core";
  7. const { OAuth2 } = oauth;
  8. let UsersModule;
  9. let MailModule;
  10. let CacheModule;
  11. let DBModule;
  12. let PlaylistsModule;
  13. let WSModule;
  14. let MediaModule;
  15. let UtilsModule;
  16. let ActivitiesModule;
  17. const avatarColors = ["blue", "orange", "green", "purple", "teal"];
  18. class _UsersModule extends CoreClass {
  19. // eslint-disable-next-line require-jsdoc
  20. constructor() {
  21. super("users");
  22. UsersModule = this;
  23. }
  24. /**
  25. * Initialises the app module
  26. * @returns {Promise} - returns promise (reject, resolve)
  27. */
  28. async initialize() {
  29. DBModule = this.moduleManager.modules.db;
  30. MailModule = this.moduleManager.modules.mail;
  31. WSModule = this.moduleManager.modules.ws;
  32. CacheModule = this.moduleManager.modules.cache;
  33. MediaModule = this.moduleManager.modules.media;
  34. UtilsModule = this.moduleManager.modules.utils;
  35. ActivitiesModule = this.moduleManager.modules.activities;
  36. PlaylistsModule = this.moduleManager.modules.playlists;
  37. this.userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  38. this.dataRequestModel = await DBModule.runJob("GET_MODEL", { modelName: "dataRequest" });
  39. this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" });
  40. this.playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" });
  41. this.activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" });
  42. this.dataRequestEmailSchema = await MailModule.runJob("GET_SCHEMA_ASYNC", { schemaName: "dataRequest" });
  43. this.verifyEmailSchema = await MailModule.runJob("GET_SCHEMA_ASYNC", { schemaName: "verifyEmail" });
  44. this.sessionSchema = await CacheModule.runJob("GET_SCHEMA", {
  45. schemaName: "session"
  46. });
  47. this.appUrl = `${config.get("url.secure") ? "https" : "http"}://${config.get("url.host")}`;
  48. this.githubRedirectUri =
  49. config.get("apis.github.redirect_uri").length > 0
  50. ? config.get("apis.github.redirect_uri")
  51. : `${this.appUrl}/backend/auth/github/authorize/callback`;
  52. this.oidcRedirectUri =
  53. config.get("apis.oidc.redirect_uri").length > 0
  54. ? config.get("apis.oidc.redirect_uri")
  55. : `${this.appUrl}/backend/auth/oidc/authorize/callback`;
  56. this.oauth2 = new OAuth2(
  57. config.get("apis.github.client"),
  58. config.get("apis.github.secret"),
  59. "https://github.com/",
  60. "login/oauth/authorize",
  61. "login/oauth/access_token",
  62. null
  63. );
  64. // getOAuthAccessToken uses callbacks by default, so make a helper function to turn it into a promise instead
  65. this.getOAuthAccessToken = (...args) =>
  66. new Promise((resolve, reject) => {
  67. this.oauth2.getOAuthAccessToken(...args, (err, accessToken, refreshToken, results) => {
  68. if (err) reject(err);
  69. else resolve({ accessToken, refreshToken, results });
  70. });
  71. });
  72. if (config.get("apis.oidc.enabled")) {
  73. const openidConfigurationResponse = await axios.get(config.get("apis.oidc.openid_configuration_url"));
  74. const { token_endpoint: tokenEndpoint, userinfo_endpoint: userinfoEndpoint } =
  75. openidConfigurationResponse.data;
  76. // TODO somehow make this endpoint immutable, if possible in some way
  77. this.oidcUserinfoEndpoint = userinfoEndpoint;
  78. //
  79. const clientId = config.get("apis.oidc.client_id");
  80. const clientSecret = config.get("apis.oidc.client_secret");
  81. this.getOIDCOAuthAccessToken = async code => {
  82. const tokenResponse = await axios.post(
  83. tokenEndpoint,
  84. {
  85. grant_type: "authorization_code",
  86. code,
  87. client_id: clientId,
  88. client_secret: clientSecret,
  89. redirect_uri: this.oidcRedirectUri
  90. },
  91. {
  92. headers: {
  93. "Content-Type": "application/x-www-form-urlencoded"
  94. }
  95. }
  96. );
  97. const { access_token: accessToken } = tokenResponse.data;
  98. return { accessToken };
  99. };
  100. }
  101. }
  102. /**
  103. * Removes a user and associated data
  104. * @param {object} payload - object that contains the payload
  105. * @param {string} payload.userId - id of the user to remove
  106. * @returns {Promise} - returns a promise (resolve, reject)
  107. */
  108. async REMOVE_USER(payload) {
  109. const { userId } = payload;
  110. // Create data request, in case the process fails halfway through. An admin can finish the removal manually
  111. const dataRequest = await UsersModule.dataRequestModel.create({ userId, type: "remove" });
  112. await WSModule.runJob(
  113. "EMIT_TO_ROOM",
  114. {
  115. room: "admin.users",
  116. args: ["event:admin.dataRequests.created", { data: { request: dataRequest } }]
  117. },
  118. this
  119. );
  120. if (config.get("sendDataRequestEmails")) {
  121. const adminUsers = await UsersModule.userModel.find({ role: "admin" });
  122. const to = adminUsers.map(adminUser => adminUser.email.address);
  123. await UsersModule.dataRequestEmailSchema(to, userId, "remove");
  124. }
  125. // Delete activities
  126. await UsersModule.activityModel.deleteMany({ userId });
  127. // Delete stations and associated data
  128. const stations = await UsersModule.stationModel.find({ owner: userId });
  129. const stationJobs = stations.map(station => async () => {
  130. const { _id: stationId } = station;
  131. await UsersModule.stationModel.deleteOne({ _id: stationId });
  132. await CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this);
  133. if (!station.playlist) return;
  134. await PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist }, this);
  135. });
  136. await Promise.all(stationJobs);
  137. // Remove user as dj
  138. await UsersModule.stationModel.updateMany({ djs: userId }, { $pull: { djs: userId } });
  139. // Collect songs to adjust ratings for later
  140. const likedPlaylist = await UsersModule.playlistModel.findOne({ createdBy: userId, type: "user-liked" });
  141. const dislikedPlaylist = await UsersModule.playlistModel.findOne({ createdBy: userId, type: "user-disliked" });
  142. const songsToAdjustRatings = [
  143. ...(likedPlaylist?.songs?.map(({ mediaSource }) => mediaSource) ?? []),
  144. ...(dislikedPlaylist?.songs?.map(({ mediaSource }) => mediaSource) ?? [])
  145. ];
  146. // Delete playlists created by user
  147. await UsersModule.playlistModel.deleteMany({ createdBy: userId });
  148. // TODO Maybe we don't need to wait for this to finish?
  149. // Recalculate ratings of songs the user liked/disliked
  150. const recalculateRatingsJobs = songsToAdjustRatings.map(songsToAdjustRating =>
  151. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource: songsToAdjustRating }, this)
  152. );
  153. await Promise.all(recalculateRatingsJobs);
  154. // Delete user object
  155. await UsersModule.userModel.deleteMany({ _id: userId });
  156. // Remove sessions from Redis and MongoDB
  157. await CacheModule.runJob("PUB", { channel: "user.removeSessions", value: userId }, this);
  158. const sessions = await CacheModule.runJob("HGETALL", { table: "sessions" }, this);
  159. const sessionIds = Object.keys(sessions);
  160. const sessionJobs = sessionIds.map(sessionId => async () => {
  161. const session = sessions[sessionId];
  162. if (!session || session.userId !== userId) return;
  163. await CacheModule.runJob("HDEL", { table: "sessions", key: sessionId }, this);
  164. });
  165. await Promise.all(sessionJobs);
  166. await CacheModule.runJob(
  167. "PUB",
  168. {
  169. channel: "user.removeAccount",
  170. value: userId
  171. },
  172. this
  173. );
  174. }
  175. /**
  176. * Tries to verify email from email verification token/code
  177. * @param {object} payload - object that contains the payload
  178. * @param {string} payload.code - email verification token/code
  179. * @returns {Promise} - returns a promise (resolve, reject)
  180. */
  181. async VERIFY_EMAIL(payload) {
  182. const { code } = payload;
  183. if (!code) throw new Error("Invalid code.");
  184. const user = await UsersModule.userModel.findOne({ "email.verificationToken": code });
  185. if (!user) throw new Error("User not found.");
  186. if (user.email.verified) throw new Error("This email is already verified.");
  187. await UsersModule.userModel.updateOne(
  188. { "email.verificationToken": code },
  189. {
  190. $set: { "email.verified": true },
  191. $unset: { "email.verificationToken": "" }
  192. },
  193. { runValidators: true }
  194. );
  195. }
  196. /**
  197. * Handles callback route being accessed, which has data from GitHub during the oauth process
  198. * Will be used to either log the user in, register the user, or link the GitHub account to an existing account
  199. * @param {object} payload - object that contains the payload
  200. * @param {string} payload.code - code we need to use to get the access token
  201. * @param {string} payload.state - custom state we may have passed to GitHub during the first step
  202. * @param {string} payload.error - error code if an error occured
  203. * @param {string} payload.errorDescription - error description if an error occured
  204. * @returns {Promise} - returns a promise (resolve, reject)
  205. */
  206. async GITHUB_AUTHORIZE_CALLBACK(payload) {
  207. const { code, state, error, errorDescription } = payload;
  208. if (error) throw new Error(errorDescription);
  209. // Tries to get access token. We don't use the refresh token currently
  210. const { accessToken, /* refreshToken, */ results } = await UsersModule.getOAuthAccessToken(code, {
  211. redirect_uri: UsersModule.githubRedirectUri
  212. });
  213. if (!accessToken) throw new Error(results.error_description);
  214. const options = {
  215. headers: {
  216. "User-Agent": "request",
  217. Authorization: `token ${accessToken}`
  218. }
  219. };
  220. // Gets user data
  221. const githubUserData = await axios.get("https://api.github.com/user", options);
  222. if (githubUserData.status !== 200) throw new Error(githubUserData.data.message);
  223. if (!githubUserData.data.id) throw new Error("Something went wrong, no id.");
  224. // If we specified a state in the first step when we redirected the user to GitHub, it was to link a
  225. // GitHub account to an existing Musare account, so continue with a job specifically for linking the account
  226. if (state)
  227. return UsersModule.runJob(
  228. "GITHUB_AUTHORIZE_CALLBACK_LINK",
  229. { state, githubId: githubUserData.data.id, accessToken },
  230. this
  231. );
  232. const user = await UsersModule.userModel.findOne({ "services.github.id": githubUserData.data.id });
  233. let userId;
  234. if (user) {
  235. // Refresh access token, though it's pretty useless as it'll probably expire and then be useless,
  236. // and we don't use it afterwards at all
  237. user.services.github.access_token = accessToken;
  238. await user.save();
  239. userId = user._id;
  240. } else {
  241. // Try to register the user. Will throw an error if it's unable to do so or any error occurs
  242. ({ userId } = await UsersModule.runJob(
  243. "GITHUB_AUTHORIZE_CALLBACK_REGISTER",
  244. { githubUserData, accessToken },
  245. this
  246. ));
  247. }
  248. // Create session for the userId gotten above, as the user existed or was successfully registered
  249. const sessionId = await UtilsModule.runJob("GUID", {}, this);
  250. await CacheModule.runJob(
  251. "HSET",
  252. {
  253. table: "sessions",
  254. key: sessionId,
  255. value: UsersModule.sessionSchema(sessionId, userId)
  256. },
  257. this
  258. );
  259. return { sessionId, userId, redirectUrl: UsersModule.appUrl };
  260. }
  261. /**
  262. * Handles registering the user in the GitHub login/register/link callback/process
  263. * @param {object} payload - object that contains the payload
  264. * @param {string} payload.githubUserData - data we got from the /user API endpoint from GitHub
  265. * @param {string} payload.accessToken - access token for the GitHub user
  266. * @returns {Promise} - returns a promise (resolve, reject)
  267. */
  268. async GITHUB_AUTHORIZE_CALLBACK_REGISTER(payload) {
  269. const { githubUserData, accessToken } = payload;
  270. let user;
  271. // Check if username already exists
  272. user = await UsersModule.userModel.findOne({ username: new RegExp(`^${githubUserData.data.login}$`, "i") });
  273. if (user) throw new Error(`An account with that username already exists.`);
  274. // Get emails used for GitHub account
  275. const githubEmailsData = await axios.get("https://api.github.com/user/emails", {
  276. headers: {
  277. "User-Agent": "request",
  278. Authorization: `token ${accessToken}`
  279. }
  280. });
  281. if (!Array.isArray(githubEmailsData.data)) throw new Error(githubEmailsData.message);
  282. const primaryEmailAddress = githubEmailsData.data.find(emailAddress => emailAddress.primary)?.email;
  283. if (!primaryEmailAddress) throw new Error("No primary email address found.");
  284. user = await UsersModule.userModel.findOne({ "email.address": primaryEmailAddress });
  285. if (user && Object.keys(JSON.parse(user.services.github)).length === 0)
  286. throw new Error(`An account with that email address exists, but is not linked to GitHub.`);
  287. if (user) throw new Error(`An account with that email address already exists.`);
  288. const userId = await UtilsModule.runJob(
  289. "GENERATE_RANDOM_STRING",
  290. {
  291. length: 12
  292. },
  293. this
  294. );
  295. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  296. const gravatarUrl = await UtilsModule.runJob(
  297. "CREATE_GRAVATAR",
  298. {
  299. email: primaryEmailAddress
  300. },
  301. this
  302. );
  303. const likedSongsPlaylist = await PlaylistsModule.runJob(
  304. "CREATE_USER_PLAYLIST",
  305. {
  306. userId,
  307. displayName: "Liked Songs",
  308. type: "user-liked"
  309. },
  310. this
  311. );
  312. const dislikedSongsPlaylist = await PlaylistsModule.runJob(
  313. "CREATE_USER_PLAYLIST",
  314. {
  315. userId,
  316. displayName: "Disliked Songs",
  317. type: "user-disliked"
  318. },
  319. this
  320. );
  321. user = {
  322. _id: userId,
  323. username: githubUserData.data.login,
  324. name: githubUserData.data.name,
  325. location: githubUserData.data.location,
  326. bio: githubUserData.data.bio,
  327. email: {
  328. address: primaryEmailAddress,
  329. verificationToken
  330. },
  331. services: {
  332. github: {
  333. id: githubUserData.data.id,
  334. access_token: accessToken
  335. }
  336. },
  337. avatar: {
  338. type: "gravatar",
  339. url: gravatarUrl
  340. },
  341. likedSongsPlaylist,
  342. dislikedSongsPlaylist
  343. };
  344. await UsersModule.userModel.create(user);
  345. await UsersModule.verifyEmailSchema(primaryEmailAddress, githubUserData.data.login, verificationToken);
  346. await ActivitiesModule.runJob(
  347. "ADD_ACTIVITY",
  348. {
  349. userId,
  350. type: "user__joined",
  351. payload: { message: "Welcome to Musare!" }
  352. },
  353. this
  354. );
  355. return {
  356. userId
  357. };
  358. }
  359. /**
  360. * Job to attempt to link a GitHub user to a Musare account
  361. * @param {object} payload - object that contains the payload
  362. * @param {string} payload.state - state we passed to GitHub and got back from GitHub
  363. * @param {string} payload.githubId - GitHub user id
  364. * @param {string} payload.accessToken - GitHub user access token
  365. * @returns {Promise} - returns a promise (resolve, reject)
  366. */
  367. async GITHUB_AUTHORIZE_CALLBACK_LINK(payload) {
  368. const { state, githubId, accessToken } = payload;
  369. // State is currently the session id (SID), so check if that session (still) exists
  370. const session = await CacheModule.runJob(
  371. "HGET",
  372. {
  373. table: "sessions",
  374. key: state
  375. },
  376. this
  377. );
  378. if (!session) throw new Error("Invalid session.");
  379. const user = await UsersModule.userModel.findOne({ _id: session.userId });
  380. if (!user) throw new Error("User not found.");
  381. if (user.services.github && user.services.github.id) throw new Error("Account already has GitHub linked.");
  382. const { _id: userId } = user;
  383. await UsersModule.userModel.updateOne(
  384. { _id: userId },
  385. {
  386. $set: {
  387. "services.github": {
  388. id: githubId,
  389. access_token: accessToken
  390. }
  391. }
  392. },
  393. { runValidators: true }
  394. );
  395. await CacheModule.runJob(
  396. "PUB",
  397. {
  398. channel: "user.linkGithub",
  399. value: userId
  400. },
  401. this
  402. );
  403. await CacheModule.runJob(
  404. "PUB",
  405. {
  406. channel: "user.updated",
  407. value: { userId }
  408. },
  409. this
  410. );
  411. return {
  412. redirectUrl: `${UsersModule.appUrl}/settings?tab=security`
  413. };
  414. }
  415. /**
  416. * Handles callback route being accessed, which has data from OIDC during the oauth process
  417. * Will be used to either log the user in or register the user
  418. * @param {object} payload - object that contains the payload
  419. * @param {string} payload.code - code we need to use to get the access token
  420. * @param {string} payload.error - error code if an error occured
  421. * @param {string} payload.errorDescription - error description if an error occured
  422. * @returns {Promise} - returns a promise (resolve, reject)
  423. */
  424. async OIDC_AUTHORIZE_CALLBACK(payload) {
  425. const { code, error, errorDescription } = payload;
  426. if (error) throw new Error(errorDescription);
  427. // Tries to get access token. We don't use the refresh token currently
  428. const { accessToken } = await UsersModule.getOIDCOAuthAccessToken(code);
  429. // Gets user data
  430. const userInfoResponse = await axios.post(
  431. UsersModule.oidcUserinfoEndpoint,
  432. {},
  433. {
  434. headers: {
  435. Authorization: `Bearer ${accessToken}`
  436. }
  437. }
  438. );
  439. if (!userInfoResponse.data.preferred_username) throw new Error("Something went wrong, no preferred_username.");
  440. // TODO verify sub from userinfo and token response, see 5.3.2 https://openid.net/specs/openid-connect-core-1_0.html
  441. // TODO we don't use linking for OIDC currently, so remove this or utilize it in some other way if needed
  442. // If we specified a state in the first step when we redirected the user to OIDC, it was to link a
  443. // OIDC account to an existing Musare account, so continue with a job specifically for linking the account
  444. // if (state)
  445. // return UsersModule.runJob(
  446. // "OIDC_AUTHORIZE_CALLBACK_LINK",
  447. // { state, sub: userInfoResponse.data.sub, accessToken },
  448. // this
  449. // );
  450. const user = await UsersModule.userModel.findOne({ "services.oidc.sub": userInfoResponse.data.sub });
  451. let userId;
  452. if (user) {
  453. // Refresh access token, though it's pretty useless as it'll probably expire and then be useless,
  454. // and we don't use it afterwards at all anyways
  455. user.services.oidc.access_token = accessToken;
  456. await user.save();
  457. userId = user._id;
  458. } else {
  459. // Try to register the user. Will throw an error if it's unable to do so or any error occurs
  460. ({ userId } = await UsersModule.runJob(
  461. "OIDC_AUTHORIZE_CALLBACK_REGISTER",
  462. { userInfoResponse: userInfoResponse.data, accessToken },
  463. this
  464. ));
  465. }
  466. // Create session for the userId gotten above, as the user existed or was successfully registered
  467. const sessionId = await UtilsModule.runJob("GUID", {}, this);
  468. await CacheModule.runJob(
  469. "HSET",
  470. {
  471. table: "sessions",
  472. key: sessionId,
  473. value: UsersModule.sessionSchema(sessionId, userId.toString())
  474. },
  475. this
  476. );
  477. return { sessionId, userId, redirectUrl: UsersModule.appUrl };
  478. }
  479. /**
  480. * Handles registering the user in the GitHub login/register/link callback/process
  481. * @param {object} payload - object that contains the payload
  482. * @param {string} payload.userInfoResponse - data we got from the OIDC user info API endpoint
  483. * @param {string} payload.accessToken - access token for the GitHub user
  484. * @returns {Promise} - returns a promise (resolve, reject)
  485. */
  486. async OIDC_AUTHORIZE_CALLBACK_REGISTER(payload) {
  487. const { userInfoResponse, accessToken } = payload;
  488. let user;
  489. // Check if username already exists
  490. user = await UsersModule.userModel.findOne({
  491. username: new RegExp(`^${userInfoResponse.preferred_username}$`, "i")
  492. });
  493. 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
  494. const emailAddress = userInfoResponse.email;
  495. if (!emailAddress) throw new Error("No email address found.");
  496. user = await UsersModule.userModel.findOne({ "email.address": emailAddress });
  497. if (user && Object.keys(JSON.parse(user.services.github)).length === 0)
  498. throw new Error(`An account with that email address already exists, but is not linked to OIDC.`);
  499. if (user) throw new Error(`An account with that email address already exists.`);
  500. const userId = await UtilsModule.runJob(
  501. "GENERATE_RANDOM_STRING",
  502. {
  503. length: 12
  504. },
  505. this
  506. );
  507. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  508. const gravatarUrl = await UtilsModule.runJob(
  509. "CREATE_GRAVATAR",
  510. {
  511. email: emailAddress
  512. },
  513. this
  514. );
  515. const likedSongsPlaylist = await PlaylistsModule.runJob(
  516. "CREATE_USER_PLAYLIST",
  517. {
  518. userId,
  519. displayName: "Liked Songs",
  520. type: "user-liked"
  521. },
  522. this
  523. );
  524. const dislikedSongsPlaylist = await PlaylistsModule.runJob(
  525. "CREATE_USER_PLAYLIST",
  526. {
  527. userId,
  528. displayName: "Disliked Songs",
  529. type: "user-disliked"
  530. },
  531. this
  532. );
  533. user = {
  534. _id: userId,
  535. username: userInfoResponse.preferred_username,
  536. name: userInfoResponse.name,
  537. location: "",
  538. bio: "",
  539. email: {
  540. address: emailAddress,
  541. verificationToken
  542. },
  543. services: {
  544. oidc: {
  545. sub: userInfoResponse.sub,
  546. access_token: accessToken
  547. }
  548. },
  549. avatar: {
  550. type: "gravatar",
  551. url: gravatarUrl
  552. },
  553. likedSongsPlaylist,
  554. dislikedSongsPlaylist
  555. };
  556. await UsersModule.userModel.create(user);
  557. await UsersModule.verifyEmailSchema(emailAddress, userInfoResponse.preferred_username, verificationToken);
  558. await ActivitiesModule.runJob(
  559. "ADD_ACTIVITY",
  560. {
  561. userId,
  562. type: "user__joined",
  563. payload: { message: "Welcome to Musare!" }
  564. },
  565. this
  566. );
  567. return {
  568. userId
  569. };
  570. }
  571. /**
  572. * Attempts to register a user
  573. * @param {object} payload - object that contains the payload
  574. * @param {string} payload.email - email
  575. * @param {string} payload.username - username
  576. * @param {string} payload.password - plaintext password
  577. * @param {string} payload.recaptcha - recaptcha, if recaptcha is enabled
  578. * @returns {Promise} - returns a promise (resolve, reject)
  579. */
  580. async REGISTER(payload) {
  581. const { username, password, recaptcha } = payload;
  582. let { email } = payload;
  583. email = email.toLowerCase().trim();
  584. if (config.get("registrationDisabled") === true) throw new Error("Registration is not allowed at this time.");
  585. if (Array.isArray(config.get("experimental.registration_email_whitelist"))) {
  586. const experimentalRegistrationEmailWhitelist = config.get("experimental.registration_email_whitelist");
  587. const anyRegexPassed = experimentalRegistrationEmailWhitelist.find(regex => {
  588. const emailWhitelistRegex = new RegExp(regex);
  589. return emailWhitelistRegex.test(email);
  590. });
  591. if (!anyRegexPassed) throw new Error("Your email is not allowed to register.");
  592. }
  593. if (!DBModule.passwordValid(password))
  594. throw new Error("Invalid password. Check if it meets all the requirements.");
  595. if (config.get("apis.recaptcha.enabled") === true) {
  596. const recaptchaBody = await axios.post("https://www.google.com/recaptcha/api/siteverify", {
  597. data: {
  598. secret: config.get("apis").recaptcha.secret,
  599. response: recaptcha
  600. }
  601. });
  602. if (recaptchaBody.success !== true) throw new Error("Response from recaptcha was not successful.");
  603. }
  604. let user = await UsersModule.userModel.findOne({ username: new RegExp(`^${username}$`, "i") });
  605. if (user) throw new Error("A user with that username already exists.");
  606. user = await UsersModule.userModel.findOne({ "email.address": email });
  607. if (user) throw new Error("A user with that email already exists.");
  608. const salt = await bcrypt.genSalt(10);
  609. const hash = await bcrypt.hash(sha256(password), salt);
  610. const userId = await UtilsModule.runJob(
  611. "GENERATE_RANDOM_STRING",
  612. {
  613. length: 12
  614. },
  615. this
  616. );
  617. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  618. const gravatarUrl = await UtilsModule.runJob(
  619. "CREATE_GRAVATAR",
  620. {
  621. email
  622. },
  623. this
  624. );
  625. const likedSongsPlaylist = await PlaylistsModule.runJob(
  626. "CREATE_USER_PLAYLIST",
  627. {
  628. userId,
  629. displayName: "Liked Songs",
  630. type: "user-liked"
  631. },
  632. this
  633. );
  634. const dislikedSongsPlaylist = await PlaylistsModule.runJob(
  635. "CREATE_USER_PLAYLIST",
  636. {
  637. userId,
  638. displayName: "Disliked Songs",
  639. type: "user-disliked"
  640. },
  641. this
  642. );
  643. user = {
  644. _id: userId,
  645. name: username,
  646. username,
  647. email: {
  648. address: email,
  649. verificationToken
  650. },
  651. services: {
  652. password: {
  653. password: hash
  654. }
  655. },
  656. avatar: {
  657. type: "initials",
  658. color: avatarColors[Math.floor(Math.random() * avatarColors.length)],
  659. url: gravatarUrl
  660. },
  661. likedSongsPlaylist,
  662. dislikedSongsPlaylist
  663. };
  664. await UsersModule.userModel.create(user);
  665. await UsersModule.verifyEmailSchema(email, username, verificationToken);
  666. await ActivitiesModule.runJob(
  667. "ADD_ACTIVITY",
  668. {
  669. userId,
  670. type: "user__joined",
  671. payload: { message: "Welcome to Musare!" }
  672. },
  673. this
  674. );
  675. return {
  676. userId
  677. };
  678. }
  679. /**
  680. * Attempts to update the email address of a user
  681. * @param {object} payload - object that contains the payload
  682. * @param {string} payload.userId - userId
  683. * @param {string} payload.email - new email
  684. * @returns {Promise} - returns a promise (resolve, reject)
  685. */
  686. async UPDATE_EMAIL(payload) {
  687. const { userId } = payload;
  688. let { email } = payload;
  689. email = email.toLowerCase().trim();
  690. const user = await UsersModule.userModel.findOne({ _id: userId });
  691. if (!user) throw new Error("User not found.");
  692. if (user.email.address === email) throw new Error("New email can't be the same as your the old email.");
  693. const existingUser = UsersModule.userModel.findOne({ "email.address": email });
  694. if (existingUser) throw new Error("That email is already in use.");
  695. const gravatarUrl = await UtilsModule.runJob("CREATE_GRAVATAR", { email }, this);
  696. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  697. await UsersModule.userModel.updateOne(
  698. { _id: userId },
  699. {
  700. $set: {
  701. "avatar.url": gravatarUrl,
  702. "email.address": email,
  703. "email.verified": false,
  704. "email.verificationToken": verificationToken
  705. }
  706. },
  707. { runValidators: true }
  708. );
  709. await UsersModule.verifyEmailSchema(email, user.username, verificationToken);
  710. }
  711. /**
  712. * Attempts to update the username of a user
  713. * @param {object} payload - object that contains the payload
  714. * @param {string} payload.userId - userId
  715. * @param {string} payload.username - new username
  716. * @returns {Promise} - returns a promise (resolve, reject)
  717. */
  718. async UPDATE_USERNAME(payload) {
  719. const { userId, username } = payload;
  720. const user = await UsersModule.userModel.findOne({ _id: userId });
  721. if (!user) throw new Error("User not found.");
  722. if (user.username === username) throw new Error("New username can't be the same as the old username.");
  723. const existingUser = await UsersModule.userModel.findOne({ username: new RegExp(`^${username}$`, "i") });
  724. if (existingUser) throw new Error("That username is already in use.");
  725. await UsersModule.userModel.updateOne({ _id: userId }, { $set: { username } }, { runValidators: true });
  726. }
  727. // async EXAMPLE_JOB() {
  728. // if (true) return;
  729. // else throw new Error("Nothing changed.");
  730. // }
  731. }
  732. export default new _UsersModule();