users.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. 'use strict';
  2. const async = require('async');
  3. const config = require('config');
  4. const request = require('request');
  5. const bcrypt = require('bcrypt');
  6. const sha256 = require('sha256');
  7. const hooks = require('./hooks');
  8. const moduleManager = require("../../index");
  9. const db = moduleManager.modules["db"];
  10. const mail = moduleManager.modules["mail"];
  11. const cache = moduleManager.modules["cache"];
  12. const punishments = moduleManager.modules["punishments"];
  13. const utils = moduleManager.modules["utils"];
  14. const logger = moduleManager.modules["logger"];
  15. cache.sub('user.updateUsername', user => {
  16. utils.socketsFromUser(user._id, sockets => {
  17. sockets.forEach(socket => {
  18. socket.emit('event:user.username.changed', user.username);
  19. });
  20. });
  21. });
  22. cache.sub('user.removeSessions', userId => {
  23. utils.socketsFromUserWithoutCache(userId, sockets => {
  24. sockets.forEach(socket => {
  25. socket.emit('keep.event:user.session.removed');
  26. });
  27. });
  28. });
  29. cache.sub('user.linkPassword', userId => {
  30. utils.socketsFromUser(userId, sockets => {
  31. sockets.forEach(socket => {
  32. socket.emit('event:user.linkPassword');
  33. });
  34. });
  35. });
  36. cache.sub('user.linkGitHub', userId => {
  37. utils.socketsFromUser(userId, sockets => {
  38. sockets.forEach(socket => {
  39. socket.emit('event:user.linkGitHub');
  40. });
  41. });
  42. });
  43. cache.sub('user.unlinkPassword', userId => {
  44. utils.socketsFromUser(userId, sockets => {
  45. sockets.forEach(socket => {
  46. socket.emit('event:user.unlinkPassword');
  47. });
  48. });
  49. });
  50. cache.sub('user.unlinkGitHub', userId => {
  51. utils.socketsFromUser(userId, sockets => {
  52. sockets.forEach(socket => {
  53. socket.emit('event:user.unlinkGitHub');
  54. });
  55. });
  56. });
  57. cache.sub('user.ban', data => {
  58. utils.socketsFromUser(data.userId, sockets => {
  59. sockets.forEach(socket => {
  60. socket.emit('keep.event:banned', data.punishment);
  61. socket.disconnect(true);
  62. });
  63. });
  64. });
  65. cache.sub('user.favoritedStation', data => {
  66. utils.socketsFromUser(data.userId, sockets => {
  67. sockets.forEach(socket => {
  68. socket.emit('event:user.favoritedStation', data.stationId);
  69. });
  70. });
  71. });
  72. cache.sub('user.unfavoritedStation', data => {
  73. utils.socketsFromUser(data.userId, sockets => {
  74. sockets.forEach(socket => {
  75. socket.emit('event:user.unfavoritedStation', data.stationId);
  76. });
  77. });
  78. });
  79. module.exports = {
  80. /**
  81. * Lists all Users
  82. *
  83. * @param {Object} session - the session object automatically added by socket.io
  84. * @param {Function} cb - gets called with the result
  85. */
  86. index: hooks.adminRequired((session, cb) => {
  87. async.waterfall([
  88. (next) => {
  89. db.models.user.find({}).exec(next);
  90. }
  91. ], async (err, users) => {
  92. if (err) {
  93. err = await utils.getError(err);
  94. logger.error("USER_INDEX", `Indexing users failed. "${err}"`);
  95. return cb({status: 'failure', message: err});
  96. } else {
  97. logger.success("USER_INDEX", `Indexing users successful.`);
  98. let filteredUsers = [];
  99. users.forEach(user => {
  100. filteredUsers.push({
  101. _id: user._id,
  102. username: user.username,
  103. role: user.role,
  104. liked: user.liked,
  105. disliked: user.disliked,
  106. songsRequested: user.statistics.songsRequested,
  107. email: {
  108. address: user.email.address,
  109. verified: user.email.verified
  110. },
  111. hasPassword: !!user.services.password,
  112. services: { github: user.services.github }
  113. });
  114. });
  115. return cb({ status: 'success', data: filteredUsers });
  116. }
  117. });
  118. }),
  119. /**
  120. * Logs user in
  121. *
  122. * @param {Object} session - the session object automatically added by socket.io
  123. * @param {String} identifier - the email of the user
  124. * @param {String} password - the plaintext of the user
  125. * @param {Function} cb - gets called with the result
  126. */
  127. login: (session, identifier, password, cb) => {
  128. identifier = identifier.toLowerCase();
  129. async.waterfall([
  130. // check if a user with the requested identifier exists
  131. (next) => {
  132. db.models.user.findOne({
  133. $or: [{ 'email.address': identifier }]
  134. }, next)
  135. },
  136. // if the user doesn't exist, respond with a failure
  137. // otherwise compare the requested password and the actual users password
  138. (user, next) => {
  139. if (!user) return next('User not found');
  140. if (!user.services.password || !user.services.password.password) return next('The account you are trying to access uses GitHub to log in.');
  141. bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  142. if (err) return next(err);
  143. if (!match) return next('Incorrect password');
  144. next(null, user);
  145. });
  146. },
  147. (user, next) => {
  148. utils.guid().then((sessionId) => {
  149. next(null, user, sessionId);
  150. });
  151. },
  152. (user, sessionId, next) => {
  153. cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), (err) => {
  154. if (err) return next(err);
  155. next(null, sessionId);
  156. });
  157. }
  158. ], async (err, sessionId) => {
  159. if (err && err !== true) {
  160. err = await utils.getError(err);
  161. logger.error("USER_PASSWORD_LOGIN", `Login failed with password for user "${identifier}". "${err}"`);
  162. return cb({status: 'failure', message: err});
  163. }
  164. logger.success("USER_PASSWORD_LOGIN", `Login successful with password for user "${identifier}"`);
  165. cb({ status: 'success', message: 'Login successful', user: {}, SID: sessionId });
  166. });
  167. },
  168. /**
  169. * Registers a new user
  170. *
  171. * @param {Object} session - the session object automatically added by socket.io
  172. * @param {String} username - the username for the new user
  173. * @param {String} email - the email for the new user
  174. * @param {String} password - the plaintext password for the new user
  175. * @param {Object} recaptcha - the recaptcha data
  176. * @param {Function} cb - gets called with the result
  177. */
  178. register: async function(session, username, email, password, recaptcha, cb) {
  179. email = email.toLowerCase();
  180. let verificationToken = await utils.generateRandomString(64);
  181. async.waterfall([
  182. // verify the request with google recaptcha
  183. (next) => {
  184. if (!db.passwordValid(password)) return next('Invalid password. Check if it meets all the requirements.');
  185. return next();
  186. },
  187. (next) => {
  188. request({
  189. url: 'https://www.google.com/recaptcha/api/siteverify',
  190. method: 'POST',
  191. form: {
  192. 'secret': config.get("apis").recaptcha.secret,
  193. 'response': recaptcha
  194. }
  195. }, next);
  196. },
  197. // check if the response from Google recaptcha is successful
  198. // if it is, we check if a user with the requested username already exists
  199. (response, body, next) => {
  200. let json = JSON.parse(body);
  201. if (json.success !== true) return next('Response from recaptcha was not successful.');
  202. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, next);
  203. },
  204. // if the user already exists, respond with that
  205. // otherwise check if a user with the requested email already exists
  206. (user, next) => {
  207. if (user) return next('A user with that username already exists.');
  208. db.models.user.findOne({ 'email.address': email }, next);
  209. },
  210. // if the user already exists, respond with that
  211. // otherwise, generate a salt to use with hashing the new users password
  212. (user, next) => {
  213. if (user) return next('A user with that email already exists.');
  214. bcrypt.genSalt(10, next);
  215. },
  216. // hash the password
  217. (salt, next) => {
  218. bcrypt.hash(sha256(password), salt, next)
  219. },
  220. (hash, next) => {
  221. utils.generateRandomString(12).then((_id) => {
  222. next(null, hash, _id);
  223. });
  224. },
  225. // save the new user to the database
  226. (hash, _id, next) => {
  227. db.models.user.create({
  228. _id,
  229. username,
  230. email: {
  231. address: email,
  232. verificationToken
  233. },
  234. services: {
  235. password: {
  236. password: hash
  237. }
  238. }
  239. }, next);
  240. },
  241. // respond with the new user
  242. (newUser, next) => {
  243. //TODO Send verification email
  244. mail.schemas.verifyEmail(email, username, verificationToken, () => {
  245. next();
  246. });
  247. }
  248. ], async (err) => {
  249. if (err && err !== true) {
  250. err = await utils.getError(err);
  251. logger.error("USER_PASSWORD_REGISTER", `Register failed with password for user "${username}"."${err}"`);
  252. cb({status: 'failure', message: err});
  253. } else {
  254. module.exports.login(session, email, password, (result) => {
  255. let obj = {status: 'success', message: 'Successfully registered.'};
  256. if (result.status === 'success') {
  257. obj.SID = result.SID;
  258. }
  259. logger.success("USER_PASSWORD_REGISTER", `Register successful with password for user "${username}".`);
  260. cb(obj);
  261. });
  262. }
  263. });
  264. },
  265. /**
  266. * Logs out a user
  267. *
  268. * @param {Object} session - the session object automatically added by socket.io
  269. * @param {Function} cb - gets called with the result
  270. */
  271. logout: (session, cb) => {
  272. async.waterfall([
  273. (next) => {
  274. cache.hget('sessions', session.sessionId, next);
  275. },
  276. (session, next) => {
  277. if (!session) return next('Session not found');
  278. next(null, session);
  279. },
  280. (session, next) => {
  281. cache.hdel('sessions', session.sessionId, next);
  282. }
  283. ], async (err) => {
  284. if (err && err !== true) {
  285. err = await utils.getError(err);
  286. logger.error("USER_LOGOUT", `Logout failed. "${err}" `);
  287. cb({ status: 'failure', message: err });
  288. } else {
  289. logger.success("USER_LOGOUT", `Logout successful.`);
  290. cb({ status: 'success', message: 'Successfully logged out.' });
  291. }
  292. });
  293. },
  294. /**
  295. * Removes all sessions for a user
  296. *
  297. * @param {Object} session - the session object automatically added by socket.io
  298. * @param {String} userId - the id of the user we are trying to delete the sessions of
  299. * @param {Function} cb - gets called with the result
  300. */
  301. removeSessions: hooks.loginRequired((session, userId, cb) => {
  302. async.waterfall([
  303. (next) => {
  304. db.models.user.findOne({ _id: session.userId }, (err, user) => {
  305. if (err) return next(err);
  306. if (user.role !== 'admin' && session.userId !== userId) return next('Only admins and the owner of the account can remove their sessions.');
  307. else return next();
  308. });
  309. },
  310. (next) => {
  311. cache.hgetall('sessions', next);
  312. },
  313. (sessions, next) => {
  314. if (!sessions) return next('There are no sessions for this user to remove.');
  315. else {
  316. let keys = Object.keys(sessions);
  317. next(null, keys, sessions);
  318. }
  319. },
  320. (keys, sessions, next) => {
  321. cache.pub('user.removeSessions', userId);
  322. async.each(keys, (sessionId, callback) => {
  323. let session = sessions[sessionId];
  324. if (session.userId === userId) {
  325. cache.hdel('sessions', sessionId, err => {
  326. if (err) return callback(err);
  327. else callback(null);
  328. });
  329. }
  330. }, err => {
  331. next(err);
  332. });
  333. }
  334. ], async err => {
  335. if (err) {
  336. err = await utils.getError(err);
  337. logger.error("REMOVE_SESSIONS_FOR_USER", `Couldn't remove all sessions for user "${userId}". "${err}"`);
  338. return cb({ status: 'failure', message: err });
  339. } else {
  340. logger.success("REMOVE_SESSIONS_FOR_USER", `Removed all sessions for user "${userId}".`);
  341. return cb({ status: 'success', message: 'Successfully removed all sessions.' });
  342. }
  343. });
  344. }),
  345. /**
  346. * Gets user object from username (only a few properties)
  347. *
  348. * @param {Object} session - the session object automatically added by socket.io
  349. * @param {String} username - the username of the user we are trying to find
  350. * @param {Function} cb - gets called with the result
  351. */
  352. findByUsername: (session, username, cb) => {
  353. async.waterfall([
  354. (next) => {
  355. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, next);
  356. },
  357. (account, next) => {
  358. if (!account) return next('User not found.');
  359. next(null, account);
  360. }
  361. ], async (err, account) => {
  362. if (err && err !== true) {
  363. err = await utils.getError(err);
  364. logger.error("FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  365. cb({status: 'failure', message: err});
  366. } else {
  367. logger.success("FIND_BY_USERNAME", `User found for username "${username}".`);
  368. return cb({
  369. status: 'success',
  370. data: {
  371. _id: account._id,
  372. username: account.username,
  373. role: account.role,
  374. email: account.email.address,
  375. createdAt: account.createdAt,
  376. statistics: account.statistics,
  377. liked: account.liked,
  378. disliked: account.disliked
  379. }
  380. });
  381. }
  382. });
  383. },
  384. /**
  385. * Gets a username from an userId
  386. *
  387. * @param {Object} session - the session object automatically added by socket.io
  388. * @param {String} userId - the userId of the person we are trying to get the username from
  389. * @param {Function} cb - gets called with the result
  390. */
  391. getUsernameFromId: (session, userId, cb) => {
  392. db.models.user.findById(userId).then(user => {
  393. if (user) {
  394. logger.success("GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  395. return cb({
  396. status: 'success',
  397. data: user.username
  398. });
  399. } else {
  400. logger.error("GET_USERNAME_FROM_ID", `Getting the username from userId "${userId}" failed. User not found.`);
  401. cb({
  402. status: 'failure',
  403. message: "Couldn't find the user."
  404. });
  405. }
  406. }).catch(async err => {
  407. if (err && err !== true) {
  408. err = await utils.getError(err);
  409. logger.error("GET_USERNAME_FROM_ID", `Getting the username from userId "${userId}" failed. "${err}"`);
  410. cb({ status: 'failure', message: err });
  411. }
  412. });
  413. },
  414. //TODO Fix security issues
  415. /**
  416. * Gets user info from session
  417. *
  418. * @param {Object} session - the session object automatically added by socket.io
  419. * @param {Function} cb - gets called with the result
  420. */
  421. findBySession: (session, cb) => {
  422. async.waterfall([
  423. (next) => {
  424. cache.hget('sessions', session.sessionId, next);
  425. },
  426. (session, next) => {
  427. if (!session) return next('Session not found.');
  428. next(null, session);
  429. },
  430. (session, next) => {
  431. db.models.user.findOne({ _id: session.userId }, next);
  432. },
  433. (user, next) => {
  434. if (!user) return next('User not found.');
  435. next(null, user);
  436. }
  437. ], async (err, user) => {
  438. if (err && err !== true) {
  439. err = await utils.getError(err);
  440. logger.error("FIND_BY_SESSION", `User not found. "${err}"`);
  441. cb({status: 'failure', message: err});
  442. } else {
  443. let data = {
  444. email: {
  445. address: user.email.address
  446. },
  447. username: user.username
  448. };
  449. if (user.services.password && user.services.password.password) data.password = true;
  450. if (user.services.github && user.services.github.id) data.github = true;
  451. logger.success("FIND_BY_SESSION", `User found. "${user.username}".`);
  452. return cb({
  453. status: 'success',
  454. data
  455. });
  456. }
  457. });
  458. },
  459. /**
  460. * Updates a user's username
  461. *
  462. * @param {Object} session - the session object automatically added by socket.io
  463. * @param {String} updatingUserId - the updating user's id
  464. * @param {String} newUsername - the new username
  465. * @param {Function} cb - gets called with the result
  466. */
  467. updateUsername: hooks.loginRequired((session, updatingUserId, newUsername, cb) => {
  468. async.waterfall([
  469. (next) => {
  470. if (updatingUserId === session.userId) return next(null, true);
  471. db.models.user.findOne({_id: session.userId}, next);
  472. },
  473. (user, next) => {
  474. if (user !== true && (!user || user.role !== 'admin')) return next('Invalid permissions.');
  475. db.models.user.findOne({ _id: updatingUserId }, next);
  476. },
  477. (user, next) => {
  478. if (!user) return next('User not found.');
  479. if (user.username === newUsername) return next('New username can\'t be the same as the old username.');
  480. next(null);
  481. },
  482. (next) => {
  483. db.models.user.findOne({ username: new RegExp(`^${newUsername}$`, 'i') }, next);
  484. },
  485. (user, next) => {
  486. if (!user) return next();
  487. if (user._id === updatingUserId) return next();
  488. next('That username is already in use.');
  489. },
  490. (next) => {
  491. db.models.user.updateOne({ _id: updatingUserId }, {$set: {username: newUsername}}, {runValidators: true}, next);
  492. }
  493. ], async (err) => {
  494. if (err && err !== true) {
  495. err = await utils.getError(err);
  496. logger.error("UPDATE_USERNAME", `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`);
  497. cb({status: 'failure', message: err});
  498. } else {
  499. cache.pub('user.updateUsername', {
  500. username: newUsername,
  501. _id: updatingUserId
  502. });
  503. logger.success("UPDATE_USERNAME", `Updated username for user "${updatingUserId}" to username "${newUsername}".`);
  504. cb({ status: 'success', message: 'Username updated successfully' });
  505. }
  506. });
  507. }),
  508. /**
  509. * Updates a user's email
  510. *
  511. * @param {Object} session - the session object automatically added by socket.io
  512. * @param {String} updatingUserId - the updating user's id
  513. * @param {String} newEmail - the new email
  514. * @param {Function} cb - gets called with the result
  515. */
  516. updateEmail: hooks.loginRequired(async (session, updatingUserId, newEmail, cb) => {
  517. newEmail = newEmail.toLowerCase();
  518. let verificationToken = await utils.generateRandomString(64);
  519. async.waterfall([
  520. (next) => {
  521. if (updatingUserId === session.userId) return next(null, true);
  522. db.models.user.findOne({_id: session.userId}, next);
  523. },
  524. (user, next) => {
  525. if (user !== true && (!user || user.role !== 'admin')) return next('Invalid permissions.');
  526. db.models.user.findOne({ _id: updatingUserId }, next);
  527. },
  528. (user, next) => {
  529. if (!user) return next('User not found.');
  530. if (user.email.address === newEmail) return next('New email can\'t be the same as your the old email.');
  531. next();
  532. },
  533. (next) => {
  534. db.models.user.findOne({"email.address": newEmail}, next);
  535. },
  536. (user, next) => {
  537. if (!user) return next();
  538. if (user._id === updatingUserId) return next();
  539. next('That email is already in use.');
  540. },
  541. (next) => {
  542. db.models.user.updateOne({_id: updatingUserId}, {$set: {"email.address": newEmail, "email.verified": false, "email.verificationToken": verificationToken}}, {runValidators: true}, next);
  543. },
  544. (res, next) => {
  545. db.models.user.findOne({ _id: updatingUserId }, next);
  546. },
  547. (user, next) => {
  548. mail.schemas.verifyEmail(newEmail, user.username, verificationToken, () => {
  549. next();
  550. });
  551. }
  552. ], async (err) => {
  553. if (err && err !== true) {
  554. err = await utils.getError(err);
  555. logger.error("UPDATE_EMAIL", `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`);
  556. cb({status: 'failure', message: err});
  557. } else {
  558. logger.success("UPDATE_EMAIL", `Updated email for user "${updatingUserId}" to email "${newEmail}".`);
  559. cb({ status: 'success', message: 'Email updated successfully.' });
  560. }
  561. });
  562. }),
  563. /**
  564. * Updates a user's role
  565. *
  566. * @param {Object} session - the session object automatically added by socket.io
  567. * @param {String} updatingUserId - the updating user's id
  568. * @param {String} newRole - the new role
  569. * @param {Function} cb - gets called with the result
  570. */
  571. updateRole: hooks.adminRequired((session, updatingUserId, newRole, cb) => {
  572. newRole = newRole.toLowerCase();
  573. async.waterfall([
  574. (next) => {
  575. db.models.user.findOne({ _id: updatingUserId }, next);
  576. },
  577. (user, next) => {
  578. if (!user) return next('User not found.');
  579. else if (user.role === newRole) return next('New role can\'t be the same as the old role.');
  580. else return next();
  581. },
  582. (next) => {
  583. db.models.user.updateOne({_id: updatingUserId}, {$set: {role: newRole}}, {runValidators: true}, next);
  584. }
  585. ], async (err) => {
  586. if (err && err !== true) {
  587. err = await utils.getError(err);
  588. logger.error("UPDATE_ROLE", `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`);
  589. cb({status: 'failure', message: err});
  590. } else {
  591. logger.success("UPDATE_ROLE", `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`);
  592. cb({
  593. status: 'success',
  594. message: 'Role successfully updated.'
  595. });
  596. }
  597. });
  598. }),
  599. /**
  600. * Updates a user's password
  601. *
  602. * @param {Object} session - the session object automatically added by socket.io
  603. * @param {String} newPassword - the new password
  604. * @param {Function} cb - gets called with the result
  605. */
  606. updatePassword: hooks.loginRequired((session, newPassword, cb) => {
  607. async.waterfall([
  608. (next) => {
  609. db.models.user.findOne({_id: session.userId}, next);
  610. },
  611. (user, next) => {
  612. if (!user.services.password) return next('This account does not have a password set.');
  613. next();
  614. },
  615. (next) => {
  616. if (!db.passwordValid(newPassword)) return next('Invalid password. Check if it meets all the requirements.');
  617. return next();
  618. },
  619. (next) => {
  620. bcrypt.genSalt(10, next);
  621. },
  622. // hash the password
  623. (salt, next) => {
  624. bcrypt.hash(sha256(newPassword), salt, next);
  625. },
  626. (hashedPassword, next) => {
  627. db.models.user.updateOne({_id: session.userId}, {$set: {"services.password.password": hashedPassword}}, next);
  628. }
  629. ], async (err) => {
  630. if (err) {
  631. err = await utils.getError(err);
  632. logger.error("UPDATE_PASSWORD", `Failed updating user password of user '${session.userId}'. '${err}'.`);
  633. return cb({ status: 'failure', message: err });
  634. }
  635. logger.success("UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  636. cb({
  637. status: 'success',
  638. message: 'Password successfully updated.'
  639. });
  640. });
  641. }),
  642. /**
  643. * Requests a password for a session
  644. *
  645. * @param {Object} session - the session object automatically added by socket.io
  646. * @param {String} email - the email of the user that requests a password reset
  647. * @param {Function} cb - gets called with the result
  648. */
  649. requestPassword: hooks.loginRequired(async (session, cb) => {
  650. let code = await utils.generateRandomString(8);
  651. async.waterfall([
  652. (next) => {
  653. db.models.user.findOne({_id: session.userId}, next);
  654. },
  655. (user, next) => {
  656. if (!user) return next('User not found.');
  657. if (user.services.password && user.services.password.password) return next('You already have a password set.');
  658. next(null, user);
  659. },
  660. (user, next) => {
  661. let expires = new Date();
  662. expires.setDate(expires.getDate() + 1);
  663. db.models.user.findOneAndUpdate({"email.address": user.email.address}, {$set: {"services.password": {set: {code: code, expires}}}}, {runValidators: true}, next);
  664. },
  665. (user, next) => {
  666. mail.schemas.passwordRequest(user.email.address, user.username, code, next);
  667. }
  668. ], async (err) => {
  669. if (err && err !== true) {
  670. err = await utils.getError(err);
  671. logger.error("REQUEST_PASSWORD", `UserId '${session.userId}' failed to request password. '${err}'`);
  672. cb({status: 'failure', message: err});
  673. } else {
  674. logger.success("REQUEST_PASSWORD", `UserId '${session.userId}' successfully requested a password.`);
  675. cb({
  676. status: 'success',
  677. message: 'Successfully requested password.'
  678. });
  679. }
  680. });
  681. }),
  682. /**
  683. * Verifies a password code
  684. *
  685. * @param {Object} session - the session object automatically added by socket.io
  686. * @param {String} code - the password code
  687. * @param {Function} cb - gets called with the result
  688. */
  689. verifyPasswordCode: hooks.loginRequired((session, code, cb) => {
  690. async.waterfall([
  691. (next) => {
  692. if (!code || typeof code !== 'string') return next('Invalid code1.');
  693. db.models.user.findOne({"services.password.set.code": code, _id: session.userId}, next);
  694. },
  695. (user, next) => {
  696. if (!user) return next('Invalid code2.');
  697. if (user.services.password.set.expires < new Date()) return next('That code has expired.');
  698. next(null);
  699. }
  700. ], async(err) => {
  701. if (err && err !== true) {
  702. err = await utils.getError(err);
  703. logger.error("VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  704. cb({status: 'failure', message: err});
  705. } else {
  706. logger.success("VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  707. cb({
  708. status: 'success',
  709. message: 'Successfully verified password code.'
  710. });
  711. }
  712. });
  713. }),
  714. /**
  715. * Adds a password to a user with a code
  716. *
  717. * @param {Object} session - the session object automatically added by socket.io
  718. * @param {String} code - the password code
  719. * @param {String} newPassword - the new password code
  720. * @param {Function} cb - gets called with the result
  721. */
  722. changePasswordWithCode: hooks.loginRequired((session, code, newPassword, cb) => {
  723. async.waterfall([
  724. (next) => {
  725. if (!code || typeof code !== 'string') return next('Invalid code1.');
  726. db.models.user.findOne({"services.password.set.code": code}, next);
  727. },
  728. (user, next) => {
  729. if (!user) return next('Invalid code2.');
  730. if (!user.services.password.set.expires > new Date()) return next('That code has expired.');
  731. next();
  732. },
  733. (next) => {
  734. if (!db.passwordValid(newPassword)) return next('Invalid password. Check if it meets all the requirements.');
  735. return next();
  736. },
  737. (next) => {
  738. bcrypt.genSalt(10, next);
  739. },
  740. // hash the password
  741. (salt, next) => {
  742. bcrypt.hash(sha256(newPassword), salt, next);
  743. },
  744. (hashedPassword, next) => {
  745. db.models.user.updateOne({"services.password.set.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.set": ''}}, {runValidators: true}, next);
  746. }
  747. ], async (err) => {
  748. if (err && err !== true) {
  749. err = await utils.getError(err);
  750. logger.error("ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  751. cb({status: 'failure', message: err});
  752. } else {
  753. logger.success("ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  754. cache.pub('user.linkPassword', session.userId);
  755. cb({
  756. status: 'success',
  757. message: 'Successfully added password.'
  758. });
  759. }
  760. });
  761. }),
  762. /**
  763. * Unlinks password from user
  764. *
  765. * @param {Object} session - the session object automatically added by socket.io
  766. * @param {Function} cb - gets called with the result
  767. */
  768. unlinkPassword: hooks.loginRequired((session, cb) => {
  769. async.waterfall([
  770. (next) => {
  771. db.models.user.findOne({_id: session.userId}, next);
  772. },
  773. (user, next) => {
  774. if (!user) return next('Not logged in.');
  775. if (!user.services.github || !user.services.github.id) return next('You can\'t remove password login without having GitHub login.');
  776. db.models.user.updateOne({_id: session.userId}, {$unset: {"services.password": ''}}, next);
  777. }
  778. ], async (err) => {
  779. if (err && err !== true) {
  780. err = await utils.getError(err);
  781. logger.error("UNLINK_PASSWORD", `Unlinking password failed for userId '${session.userId}'. '${err}'`);
  782. cb({status: 'failure', message: err});
  783. } else {
  784. logger.success("UNLINK_PASSWORD", `Unlinking password successful for userId '${session.userId}'.`);
  785. cache.pub('user.unlinkPassword', session.userId);
  786. cb({
  787. status: 'success',
  788. message: 'Successfully unlinked password.'
  789. });
  790. }
  791. });
  792. }),
  793. /**
  794. * Unlinks GitHub from user
  795. *
  796. * @param {Object} session - the session object automatically added by socket.io
  797. * @param {Function} cb - gets called with the result
  798. */
  799. unlinkGitHub: hooks.loginRequired((session, cb) => {
  800. async.waterfall([
  801. (next) => {
  802. db.models.user.findOne({_id: session.userId}, next);
  803. },
  804. (user, next) => {
  805. if (!user) return next('Not logged in.');
  806. if (!user.services.password || !user.services.password.password) return next('You can\'t remove GitHub login without having password login.');
  807. db.models.user.updateOne({_id: session.userId}, {$unset: {"services.github": ''}}, next);
  808. }
  809. ], async (err) => {
  810. if (err && err !== true) {
  811. err = await utils.getError(err);
  812. logger.error("UNLINK_GITHUB", `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`);
  813. cb({status: 'failure', message: err});
  814. } else {
  815. logger.success("UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  816. cache.pub('user.unlinkGitHub', session.userId);
  817. cb({
  818. status: 'success',
  819. message: 'Successfully unlinked GitHub.'
  820. });
  821. }
  822. });
  823. }),
  824. /**
  825. * Requests a password reset for an email
  826. *
  827. * @param {Object} session - the session object automatically added by socket.io
  828. * @param {String} email - the email of the user that requests a password reset
  829. * @param {Function} cb - gets called with the result
  830. */
  831. requestPasswordReset: async (session, email, cb) => {
  832. let code = await utils.generateRandomString(8);
  833. async.waterfall([
  834. (next) => {
  835. if (!email || typeof email !== 'string') return next('Invalid email.');
  836. email = email.toLowerCase();
  837. db.models.user.findOne({"email.address": email}, next);
  838. },
  839. (user, next) => {
  840. if (!user) return next('User not found.');
  841. if (!user.services.password || !user.services.password.password) return next('User does not have a password set, and probably uses GitHub to log in.');
  842. next(null, user);
  843. },
  844. (user, next) => {
  845. let expires = new Date();
  846. expires.setDate(expires.getDate() + 1);
  847. db.models.user.findOneAndUpdate({"email.address": email}, {$set: {"services.password.reset": {code: code, expires}}}, {runValidators: true}, next);
  848. },
  849. (user, next) => {
  850. mail.schemas.resetPasswordRequest(user.email.address, user.username, code, next);
  851. }
  852. ], async (err) => {
  853. if (err && err !== true) {
  854. err = await utils.getError(err);
  855. logger.error("REQUEST_PASSWORD_RESET", `Email '${email}' failed to request password reset. '${err}'`);
  856. cb({status: 'failure', message: err});
  857. } else {
  858. logger.success("REQUEST_PASSWORD_RESET", `Email '${email}' successfully requested a password reset.`);
  859. cb({
  860. status: 'success',
  861. message: 'Successfully requested password reset.'
  862. });
  863. }
  864. });
  865. },
  866. /**
  867. * Verifies a reset code
  868. *
  869. * @param {Object} session - the session object automatically added by socket.io
  870. * @param {String} code - the password reset code
  871. * @param {Function} cb - gets called with the result
  872. */
  873. verifyPasswordResetCode: (session, code, cb) => {
  874. async.waterfall([
  875. (next) => {
  876. if (!code || typeof code !== 'string') return next('Invalid code.');
  877. db.models.user.findOne({"services.password.reset.code": code}, next);
  878. },
  879. (user, next) => {
  880. if (!user) return next('Invalid code.');
  881. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  882. next(null);
  883. }
  884. ], async (err) => {
  885. if (err && err !== true) {
  886. err = await utils.getError(err);
  887. logger.error("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  888. cb({status: 'failure', message: err});
  889. } else {
  890. logger.success("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  891. cb({
  892. status: 'success',
  893. message: 'Successfully verified password reset code.'
  894. });
  895. }
  896. });
  897. },
  898. /**
  899. * Changes a user's password with a reset code
  900. *
  901. * @param {Object} session - the session object automatically added by socket.io
  902. * @param {String} code - the password reset code
  903. * @param {String} newPassword - the new password reset code
  904. * @param {Function} cb - gets called with the result
  905. */
  906. changePasswordWithResetCode: (session, code, newPassword, cb) => {
  907. async.waterfall([
  908. (next) => {
  909. if (!code || typeof code !== 'string') return next('Invalid code.');
  910. db.models.user.findOne({"services.password.reset.code": code}, next);
  911. },
  912. (user, next) => {
  913. if (!user) return next('Invalid code.');
  914. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  915. next();
  916. },
  917. (next) => {
  918. if (!db.passwordValid(newPassword)) return next('Invalid password. Check if it meets all the requirements.');
  919. return next();
  920. },
  921. (next) => {
  922. bcrypt.genSalt(10, next);
  923. },
  924. // hash the password
  925. (salt, next) => {
  926. bcrypt.hash(sha256(newPassword), salt, next);
  927. },
  928. (hashedPassword, next) => {
  929. db.models.user.updateOne({"services.password.reset.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.reset": ''}}, {runValidators: true}, next);
  930. }
  931. ], async (err) => {
  932. if (err && err !== true) {
  933. err = await utils.getError(err);
  934. logger.error("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' failed to change password. '${err}'`);
  935. cb({status: 'failure', message: err});
  936. } else {
  937. logger.success("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  938. cb({
  939. status: 'success',
  940. message: 'Successfully changed password.'
  941. });
  942. }
  943. });
  944. },
  945. /**
  946. * Bans a user by userId
  947. *
  948. * @param {Object} session - the session object automatically added by socket.io
  949. * @param {String} value - the user id that is going to be banned
  950. * @param {String} reason - the reason for the ban
  951. * @param {String} expiresAt - the time the ban expires
  952. * @param {Function} cb - gets called with the result
  953. */
  954. banUserById: hooks.adminRequired((session, userId, reason, expiresAt, cb) => {
  955. async.waterfall([
  956. (next) => {
  957. if (!userId) return next('You must provide a userId to ban.');
  958. else if (!reason) return next('You must provide a reason for the ban.');
  959. else return next();
  960. },
  961. (next) => {
  962. if (!expiresAt || typeof expiresAt !== 'string') return next('Invalid expire date.');
  963. let date = new Date();
  964. switch(expiresAt) {
  965. case '1h':
  966. expiresAt = date.setHours(date.getHours() + 1);
  967. break;
  968. case '12h':
  969. expiresAt = date.setHours(date.getHours() + 12);
  970. break;
  971. case '1d':
  972. expiresAt = date.setDate(date.getDate() + 1);
  973. break;
  974. case '1w':
  975. expiresAt = date.setDate(date.getDate() + 7);
  976. break;
  977. case '1m':
  978. expiresAt = date.setMonth(date.getMonth() + 1);
  979. break;
  980. case '3m':
  981. expiresAt = date.setMonth(date.getMonth() + 3);
  982. break;
  983. case '6m':
  984. expiresAt = date.setMonth(date.getMonth() + 6);
  985. break;
  986. case '1y':
  987. expiresAt = date.setFullYear(date.getFullYear() + 1);
  988. break;
  989. case 'never':
  990. expiresAt = new Date(3093527980800000);
  991. break;
  992. default:
  993. return next('Invalid expire date.');
  994. }
  995. next();
  996. },
  997. (next) => {
  998. punishments.addPunishment('banUserId', userId, reason, expiresAt, userId, next)
  999. },
  1000. (punishment, next) => {
  1001. cache.pub('user.ban', { userId, punishment });
  1002. next();
  1003. },
  1004. ], async (err) => {
  1005. if (err && err !== true) {
  1006. err = await utils.getError(err);
  1007. logger.error("BAN_USER_BY_ID", `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`);
  1008. cb({status: 'failure', message: err});
  1009. } else {
  1010. logger.success("BAN_USER_BY_ID", `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`);
  1011. cb({
  1012. status: 'success',
  1013. message: 'Successfully banned user.'
  1014. });
  1015. }
  1016. });
  1017. }),
  1018. getFavoriteStations: hooks.loginRequired((session, cb) => {
  1019. async.waterfall([
  1020. (next) => {
  1021. db.models.user.findOne({ _id: session.userId }, next);
  1022. },
  1023. (user, next) => {
  1024. if (!user) return next("User not found.");
  1025. next(null, user);
  1026. }
  1027. ], async (err, user) => {
  1028. if (err && err !== true) {
  1029. err = await utils.getError(err);
  1030. logger.error("GET_FAVORITE_STATIONS", `User ${session.userId} failed to get favorite stations. '${err}'`);
  1031. cb({status: 'failure', message: err});
  1032. } else {
  1033. logger.success("GET_FAVORITE_STATIONS", `User ${session.userId} got favorite stations.`);
  1034. cb({
  1035. status: 'success',
  1036. favoriteStations: user.favoriteStations
  1037. });
  1038. }
  1039. });
  1040. })
  1041. };