users.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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. // create the user object
  226. (hash, _id, next) => {
  227. next(null, {
  228. _id,
  229. username,
  230. email: {
  231. address: email,
  232. verificationToken
  233. },
  234. services: {
  235. password: {
  236. password: hash
  237. }
  238. }
  239. });
  240. },
  241. // generate the url for gravatar avatar
  242. (user, next) => {
  243. this.utils.createGravatar(user.email.address).then(url => {
  244. user.avatar = url;
  245. next(null, user);
  246. });
  247. },
  248. // save the new user to the database
  249. (user, next) => {
  250. db.models.user.create(user, next);
  251. },
  252. // respond with the new user
  253. (newUser, next) => {
  254. mail.schemas.verifyEmail(email, username, verificationToken, () => {
  255. next();
  256. });
  257. }
  258. ], async (err) => {
  259. if (err && err !== true) {
  260. err = await utils.getError(err);
  261. logger.error("USER_PASSWORD_REGISTER", `Register failed with password for user "${username}"."${err}"`);
  262. cb({status: 'failure', message: err});
  263. } else {
  264. module.exports.login(session, email, password, (result) => {
  265. let obj = {status: 'success', message: 'Successfully registered.'};
  266. if (result.status === 'success') {
  267. obj.SID = result.SID;
  268. }
  269. logger.success("USER_PASSWORD_REGISTER", `Register successful with password for user "${username}".`);
  270. cb(obj);
  271. });
  272. }
  273. });
  274. },
  275. /**
  276. * Logs out a user
  277. *
  278. * @param {Object} session - the session object automatically added by socket.io
  279. * @param {Function} cb - gets called with the result
  280. */
  281. logout: (session, cb) => {
  282. async.waterfall([
  283. (next) => {
  284. cache.hget('sessions', session.sessionId, next);
  285. },
  286. (session, next) => {
  287. if (!session) return next('Session not found');
  288. next(null, session);
  289. },
  290. (session, next) => {
  291. cache.hdel('sessions', session.sessionId, next);
  292. }
  293. ], async (err) => {
  294. if (err && err !== true) {
  295. err = await utils.getError(err);
  296. logger.error("USER_LOGOUT", `Logout failed. "${err}" `);
  297. cb({ status: 'failure', message: err });
  298. } else {
  299. logger.success("USER_LOGOUT", `Logout successful.`);
  300. cb({ status: 'success', message: 'Successfully logged out.' });
  301. }
  302. });
  303. },
  304. /**
  305. * Removes all sessions for a user
  306. *
  307. * @param {Object} session - the session object automatically added by socket.io
  308. * @param {String} userId - the id of the user we are trying to delete the sessions of
  309. * @param {Function} cb - gets called with the result
  310. */
  311. removeSessions: hooks.loginRequired((session, userId, cb) => {
  312. async.waterfall([
  313. (next) => {
  314. db.models.user.findOne({ _id: session.userId }, (err, user) => {
  315. if (err) return next(err);
  316. if (user.role !== 'admin' && session.userId !== userId) return next('Only admins and the owner of the account can remove their sessions.');
  317. else return next();
  318. });
  319. },
  320. (next) => {
  321. cache.hgetall('sessions', next);
  322. },
  323. (sessions, next) => {
  324. if (!sessions) return next('There are no sessions for this user to remove.');
  325. else {
  326. let keys = Object.keys(sessions);
  327. next(null, keys, sessions);
  328. }
  329. },
  330. (keys, sessions, next) => {
  331. cache.pub('user.removeSessions', userId);
  332. async.each(keys, (sessionId, callback) => {
  333. let session = sessions[sessionId];
  334. if (session.userId === userId) {
  335. cache.hdel('sessions', sessionId, err => {
  336. if (err) return callback(err);
  337. else callback(null);
  338. });
  339. }
  340. }, err => {
  341. next(err);
  342. });
  343. }
  344. ], async err => {
  345. if (err) {
  346. err = await utils.getError(err);
  347. logger.error("REMOVE_SESSIONS_FOR_USER", `Couldn't remove all sessions for user "${userId}". "${err}"`);
  348. return cb({ status: 'failure', message: err });
  349. } else {
  350. logger.success("REMOVE_SESSIONS_FOR_USER", `Removed all sessions for user "${userId}".`);
  351. return cb({ status: 'success', message: 'Successfully removed all sessions.' });
  352. }
  353. });
  354. }),
  355. /**
  356. * Gets user object from username (only a few properties)
  357. *
  358. * @param {Object} session - the session object automatically added by socket.io
  359. * @param {String} username - the username of the user we are trying to find
  360. * @param {Function} cb - gets called with the result
  361. */
  362. findByUsername: (session, username, cb) => {
  363. async.waterfall([
  364. (next) => {
  365. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, next);
  366. },
  367. (account, next) => {
  368. if (!account) return next('User not found.');
  369. next(null, account);
  370. }
  371. ], async (err, account) => {
  372. if (err && err !== true) {
  373. err = await utils.getError(err);
  374. logger.error("FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  375. cb({status: 'failure', message: err});
  376. } else {
  377. logger.success("FIND_BY_USERNAME", `User found for username "${username}".`);
  378. return cb({
  379. status: 'success',
  380. data: {
  381. _id: account._id,
  382. name: "Name goes here",
  383. username: account.username,
  384. location: account.location,
  385. bio: account.bio,
  386. role: account.role,
  387. avatar: account.avatar,
  388. createdAt: account.createdAt
  389. }
  390. });
  391. }
  392. });
  393. },
  394. /**
  395. * Gets a username from an userId
  396. *
  397. * @param {Object} session - the session object automatically added by socket.io
  398. * @param {String} userId - the userId of the person we are trying to get the username from
  399. * @param {Function} cb - gets called with the result
  400. */
  401. getUsernameFromId: (session, userId, cb) => {
  402. db.models.user.findById(userId).then(user => {
  403. if (user) {
  404. logger.success("GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  405. return cb({
  406. status: 'success',
  407. data: user.username
  408. });
  409. } else {
  410. logger.error("GET_USERNAME_FROM_ID", `Getting the username from userId "${userId}" failed. User not found.`);
  411. cb({
  412. status: 'failure',
  413. message: "Couldn't find the user."
  414. });
  415. }
  416. }).catch(async err => {
  417. if (err && err !== true) {
  418. err = await utils.getError(err);
  419. logger.error("GET_USERNAME_FROM_ID", `Getting the username from userId "${userId}" failed. "${err}"`);
  420. cb({ status: 'failure', message: err });
  421. }
  422. });
  423. },
  424. //TODO Fix security issues
  425. /**
  426. * Gets user info from session
  427. *
  428. * @param {Object} session - the session object automatically added by socket.io
  429. * @param {Function} cb - gets called with the result
  430. */
  431. findBySession: (session, cb) => {
  432. async.waterfall([
  433. (next) => {
  434. cache.hget('sessions', session.sessionId, next);
  435. },
  436. (session, next) => {
  437. if (!session) return next('Session not found.');
  438. next(null, session);
  439. },
  440. (session, next) => {
  441. db.models.user.findOne({ _id: session.userId }, next);
  442. },
  443. (user, next) => {
  444. if (!user) return next('User not found.');
  445. next(null, user);
  446. }
  447. ], async (err, user) => {
  448. if (err && err !== true) {
  449. err = await utils.getError(err);
  450. logger.error("FIND_BY_SESSION", `User not found. "${err}"`);
  451. cb({status: 'failure', message: err});
  452. } else {
  453. let data = {
  454. email: {
  455. address: user.email.address
  456. },
  457. username: user.username,
  458. location: user.location,
  459. bio: user.bio
  460. };
  461. if (user.services.password && user.services.password.password) data.password = true;
  462. if (user.services.github && user.services.github.id) data.github = true;
  463. logger.success("FIND_BY_SESSION", `User found. "${user.username}".`);
  464. return cb({
  465. status: 'success',
  466. data
  467. });
  468. }
  469. });
  470. },
  471. /**
  472. * Updates a user's username
  473. *
  474. * @param {Object} session - the session object automatically added by socket.io
  475. * @param {String} updatingUserId - the updating user's id
  476. * @param {String} newUsername - the new username
  477. * @param {Function} cb - gets called with the result
  478. */
  479. updateUsername: hooks.loginRequired((session, updatingUserId, newUsername, cb) => {
  480. async.waterfall([
  481. (next) => {
  482. if (updatingUserId === session.userId) return next(null, true);
  483. db.models.user.findOne({_id: session.userId}, next);
  484. },
  485. (user, next) => {
  486. if (user !== true && (!user || user.role !== 'admin')) return next('Invalid permissions.');
  487. db.models.user.findOne({ _id: updatingUserId }, next);
  488. },
  489. (user, next) => {
  490. if (!user) return next('User not found.');
  491. if (user.username === newUsername) return next('New username can\'t be the same as the old username.');
  492. next(null);
  493. },
  494. (next) => {
  495. db.models.user.findOne({ username: new RegExp(`^${newUsername}$`, 'i') }, next);
  496. },
  497. (user, next) => {
  498. if (!user) return next();
  499. if (user._id === updatingUserId) return next();
  500. next('That username is already in use.');
  501. },
  502. (next) => {
  503. db.models.user.updateOne({ _id: updatingUserId }, {$set: {username: newUsername}}, {runValidators: true}, next);
  504. }
  505. ], async (err) => {
  506. if (err && err !== true) {
  507. err = await utils.getError(err);
  508. logger.error("UPDATE_USERNAME", `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`);
  509. cb({status: 'failure', message: err});
  510. } else {
  511. cache.pub('user.updateUsername', {
  512. username: newUsername,
  513. _id: updatingUserId
  514. });
  515. logger.success("UPDATE_USERNAME", `Updated username for user "${updatingUserId}" to username "${newUsername}".`);
  516. cb({ status: 'success', message: 'Username updated successfully' });
  517. }
  518. });
  519. }),
  520. /**
  521. * Updates a user's email
  522. *
  523. * @param {Object} session - the session object automatically added by socket.io
  524. * @param {String} updatingUserId - the updating user's id
  525. * @param {String} newEmail - the new email
  526. * @param {Function} cb - gets called with the result
  527. */
  528. updateEmail: hooks.loginRequired(async (session, updatingUserId, newEmail, cb) => {
  529. newEmail = newEmail.toLowerCase();
  530. let verificationToken = await utils.generateRandomString(64);
  531. async.waterfall([
  532. (next) => {
  533. if (updatingUserId === session.userId) return next(null, true);
  534. db.models.user.findOne({_id: session.userId}, next);
  535. },
  536. (user, next) => {
  537. if (user !== true && (!user || user.role !== 'admin')) return next('Invalid permissions.');
  538. db.models.user.findOne({ _id: updatingUserId }, next);
  539. },
  540. (user, next) => {
  541. if (!user) return next('User not found.');
  542. if (user.email.address === newEmail) return next('New email can\'t be the same as your the old email.');
  543. next();
  544. },
  545. (next) => {
  546. db.models.user.findOne({"email.address": newEmail}, next);
  547. },
  548. (user, next) => {
  549. if (!user) return next();
  550. if (user._id === updatingUserId) return next();
  551. next('That email is already in use.');
  552. },
  553. // regenerate the url for gravatar avatar
  554. (next) => {
  555. utils.createGravatar(newEmail).then(url => next(null, url));
  556. },
  557. (avatar, next) => {
  558. db.models.user.updateOne({ _id: updatingUserId }, {
  559. $set: {
  560. "avatar": avatar,
  561. "email.address": newEmail,
  562. "email.verified": false,
  563. "email.verificationToken": verificationToken
  564. }
  565. }, { runValidators: true }, next);
  566. },
  567. (res, next) => {
  568. db.models.user.findOne({ _id: updatingUserId }, next);
  569. },
  570. (user, next) => {
  571. mail.schemas.verifyEmail(newEmail, user.username, verificationToken, () => {
  572. next();
  573. });
  574. }
  575. ], async (err) => {
  576. if (err && err !== true) {
  577. err = await utils.getError(err);
  578. logger.error("UPDATE_EMAIL", `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`);
  579. cb({status: 'failure', message: err});
  580. } else {
  581. logger.success("UPDATE_EMAIL", `Updated email for user "${updatingUserId}" to email "${newEmail}".`);
  582. cb({ status: 'success', message: 'Email updated successfully.' });
  583. }
  584. });
  585. }),
  586. /**
  587. * Updates a user's location
  588. *
  589. * @param {Object} session - the session object automatically added by socket.io
  590. * @param {String} updatingUserId - the updating user's id
  591. * @param {String} newLocation - the new location
  592. * @param {Function} cb - gets called with the result
  593. */
  594. updateLocation: hooks.loginRequired((session, updatingUserId, newLocation, cb) => {
  595. async.waterfall([
  596. (next) => {
  597. if (updatingUserId === session.userId) return next(null, true);
  598. db.models.user.findOne({_id: session.userId}, next);
  599. },
  600. (user, next) => {
  601. if (user !== true && (!user || user.role !== 'admin')) return next('Invalid permissions.');
  602. db.models.user.findOne({ _id: updatingUserId }, next);
  603. },
  604. (user, next) => {
  605. if (!user) return next('User not found.');
  606. db.models.user.updateOne({ _id: updatingUserId }, {$set: {location: newLocation}}, {runValidators: true}, next);
  607. }
  608. ], async (err) => {
  609. if (err && err !== true) {
  610. err = await utils.getError(err);
  611. logger.error("UPDATE_LOCATION", `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`);
  612. cb({status: 'failure', message: err});
  613. } else {
  614. logger.success("UPDATE_LOCATION", `Updated location for user "${updatingUserId}" to location "${newLocation}".`);
  615. cb({ status: 'success', message: 'Location updated successfully' });
  616. }
  617. });
  618. }),
  619. /**
  620. * Updates a user's bio
  621. *
  622. * @param {Object} session - the session object automatically added by socket.io
  623. * @param {String} updatingUserId - the updating user's id
  624. * @param {String} newBio - the new bio
  625. * @param {Function} cb - gets called with the result
  626. */
  627. updateBio: hooks.loginRequired((session, updatingUserId, newBio, cb) => {
  628. async.waterfall([
  629. (next) => {
  630. if (updatingUserId === session.userId) return next(null, true);
  631. db.models.user.findOne({_id: session.userId}, next);
  632. },
  633. (user, next) => {
  634. if (user !== true && (!user || user.role !== 'admin')) return next('Invalid permissions.');
  635. db.models.user.findOne({ _id: updatingUserId }, next);
  636. },
  637. (user, next) => {
  638. if (!user) return next('User not found.');
  639. db.models.user.updateOne({ _id: updatingUserId }, {$set: {bio: newBio}}, {runValidators: true}, next);
  640. }
  641. ], async (err) => {
  642. if (err && err !== true) {
  643. err = await utils.getError(err);
  644. logger.error("UPDATE_BIO", `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`);
  645. cb({status: 'failure', message: err});
  646. } else {
  647. logger.success("UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  648. cb({ status: 'success', message: 'Bio updated successfully' });
  649. }
  650. });
  651. }),
  652. /**
  653. * Updates a user's role
  654. *
  655. * @param {Object} session - the session object automatically added by socket.io
  656. * @param {String} updatingUserId - the updating user's id
  657. * @param {String} newRole - the new role
  658. * @param {Function} cb - gets called with the result
  659. */
  660. updateRole: hooks.adminRequired((session, updatingUserId, newRole, cb) => {
  661. newRole = newRole.toLowerCase();
  662. async.waterfall([
  663. (next) => {
  664. db.models.user.findOne({ _id: updatingUserId }, next);
  665. },
  666. (user, next) => {
  667. if (!user) return next('User not found.');
  668. else if (user.role === newRole) return next('New role can\'t be the same as the old role.');
  669. else return next();
  670. },
  671. (next) => {
  672. db.models.user.updateOne({_id: updatingUserId}, {$set: {role: newRole}}, {runValidators: true}, next);
  673. }
  674. ], async (err) => {
  675. if (err && err !== true) {
  676. err = await utils.getError(err);
  677. logger.error("UPDATE_ROLE", `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`);
  678. cb({status: 'failure', message: err});
  679. } else {
  680. logger.success("UPDATE_ROLE", `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`);
  681. cb({
  682. status: 'success',
  683. message: 'Role successfully updated.'
  684. });
  685. }
  686. });
  687. }),
  688. /**
  689. * Updates a user's password
  690. *
  691. * @param {Object} session - the session object automatically added by socket.io
  692. * @param {String} newPassword - the new password
  693. * @param {Function} cb - gets called with the result
  694. */
  695. updatePassword: hooks.loginRequired((session, newPassword, cb) => {
  696. async.waterfall([
  697. (next) => {
  698. db.models.user.findOne({_id: session.userId}, next);
  699. },
  700. (user, next) => {
  701. if (!user.services.password) return next('This account does not have a password set.');
  702. next();
  703. },
  704. (next) => {
  705. if (!db.passwordValid(newPassword)) return next('Invalid password. Check if it meets all the requirements.');
  706. return next();
  707. },
  708. (next) => {
  709. bcrypt.genSalt(10, next);
  710. },
  711. // hash the password
  712. (salt, next) => {
  713. bcrypt.hash(sha256(newPassword), salt, next);
  714. },
  715. (hashedPassword, next) => {
  716. db.models.user.updateOne({_id: session.userId}, {$set: {"services.password.password": hashedPassword}}, next);
  717. }
  718. ], async (err) => {
  719. if (err) {
  720. err = await utils.getError(err);
  721. logger.error("UPDATE_PASSWORD", `Failed updating user password of user '${session.userId}'. '${err}'.`);
  722. return cb({ status: 'failure', message: err });
  723. }
  724. logger.success("UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  725. cb({
  726. status: 'success',
  727. message: 'Password successfully updated.'
  728. });
  729. });
  730. }),
  731. /**
  732. * Requests a password for a session
  733. *
  734. * @param {Object} session - the session object automatically added by socket.io
  735. * @param {String} email - the email of the user that requests a password reset
  736. * @param {Function} cb - gets called with the result
  737. */
  738. requestPassword: hooks.loginRequired(async (session, cb) => {
  739. let code = await utils.generateRandomString(8);
  740. async.waterfall([
  741. (next) => {
  742. db.models.user.findOne({_id: session.userId}, next);
  743. },
  744. (user, next) => {
  745. if (!user) return next('User not found.');
  746. if (user.services.password && user.services.password.password) return next('You already have a password set.');
  747. next(null, user);
  748. },
  749. (user, next) => {
  750. let expires = new Date();
  751. expires.setDate(expires.getDate() + 1);
  752. db.models.user.findOneAndUpdate({"email.address": user.email.address}, {$set: {"services.password": {set: {code: code, expires}}}}, {runValidators: true}, next);
  753. },
  754. (user, next) => {
  755. mail.schemas.passwordRequest(user.email.address, user.username, code, next);
  756. }
  757. ], async (err) => {
  758. if (err && err !== true) {
  759. err = await utils.getError(err);
  760. logger.error("REQUEST_PASSWORD", `UserId '${session.userId}' failed to request password. '${err}'`);
  761. cb({status: 'failure', message: err});
  762. } else {
  763. logger.success("REQUEST_PASSWORD", `UserId '${session.userId}' successfully requested a password.`);
  764. cb({
  765. status: 'success',
  766. message: 'Successfully requested password.'
  767. });
  768. }
  769. });
  770. }),
  771. /**
  772. * Verifies a password code
  773. *
  774. * @param {Object} session - the session object automatically added by socket.io
  775. * @param {String} code - the password code
  776. * @param {Function} cb - gets called with the result
  777. */
  778. verifyPasswordCode: hooks.loginRequired((session, code, cb) => {
  779. async.waterfall([
  780. (next) => {
  781. if (!code || typeof code !== 'string') return next('Invalid code1.');
  782. db.models.user.findOne({"services.password.set.code": code, _id: session.userId}, next);
  783. },
  784. (user, next) => {
  785. if (!user) return next('Invalid code2.');
  786. if (user.services.password.set.expires < new Date()) return next('That code has expired.');
  787. next(null);
  788. }
  789. ], async(err) => {
  790. if (err && err !== true) {
  791. err = await utils.getError(err);
  792. logger.error("VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  793. cb({status: 'failure', message: err});
  794. } else {
  795. logger.success("VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  796. cb({
  797. status: 'success',
  798. message: 'Successfully verified password code.'
  799. });
  800. }
  801. });
  802. }),
  803. /**
  804. * Adds a password to a user with a code
  805. *
  806. * @param {Object} session - the session object automatically added by socket.io
  807. * @param {String} code - the password code
  808. * @param {String} newPassword - the new password code
  809. * @param {Function} cb - gets called with the result
  810. */
  811. changePasswordWithCode: hooks.loginRequired((session, code, newPassword, cb) => {
  812. async.waterfall([
  813. (next) => {
  814. if (!code || typeof code !== 'string') return next('Invalid code1.');
  815. db.models.user.findOne({"services.password.set.code": code}, next);
  816. },
  817. (user, next) => {
  818. if (!user) return next('Invalid code2.');
  819. if (!user.services.password.set.expires > new Date()) return next('That code has expired.');
  820. next();
  821. },
  822. (next) => {
  823. if (!db.passwordValid(newPassword)) return next('Invalid password. Check if it meets all the requirements.');
  824. return next();
  825. },
  826. (next) => {
  827. bcrypt.genSalt(10, next);
  828. },
  829. // hash the password
  830. (salt, next) => {
  831. bcrypt.hash(sha256(newPassword), salt, next);
  832. },
  833. (hashedPassword, next) => {
  834. db.models.user.updateOne({"services.password.set.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.set": ''}}, {runValidators: true}, next);
  835. }
  836. ], async (err) => {
  837. if (err && err !== true) {
  838. err = await utils.getError(err);
  839. logger.error("ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  840. cb({status: 'failure', message: err});
  841. } else {
  842. logger.success("ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  843. cache.pub('user.linkPassword', session.userId);
  844. cb({
  845. status: 'success',
  846. message: 'Successfully added password.'
  847. });
  848. }
  849. });
  850. }),
  851. /**
  852. * Unlinks password from user
  853. *
  854. * @param {Object} session - the session object automatically added by socket.io
  855. * @param {Function} cb - gets called with the result
  856. */
  857. unlinkPassword: hooks.loginRequired((session, cb) => {
  858. async.waterfall([
  859. (next) => {
  860. db.models.user.findOne({_id: session.userId}, next);
  861. },
  862. (user, next) => {
  863. if (!user) return next('Not logged in.');
  864. if (!user.services.github || !user.services.github.id) return next('You can\'t remove password login without having GitHub login.');
  865. db.models.user.updateOne({_id: session.userId}, {$unset: {"services.password": ''}}, next);
  866. }
  867. ], async (err) => {
  868. if (err && err !== true) {
  869. err = await utils.getError(err);
  870. logger.error("UNLINK_PASSWORD", `Unlinking password failed for userId '${session.userId}'. '${err}'`);
  871. cb({status: 'failure', message: err});
  872. } else {
  873. logger.success("UNLINK_PASSWORD", `Unlinking password successful for userId '${session.userId}'.`);
  874. cache.pub('user.unlinkPassword', session.userId);
  875. cb({
  876. status: 'success',
  877. message: 'Successfully unlinked password.'
  878. });
  879. }
  880. });
  881. }),
  882. /**
  883. * Unlinks GitHub from user
  884. *
  885. * @param {Object} session - the session object automatically added by socket.io
  886. * @param {Function} cb - gets called with the result
  887. */
  888. unlinkGitHub: hooks.loginRequired((session, cb) => {
  889. async.waterfall([
  890. (next) => {
  891. db.models.user.findOne({_id: session.userId}, next);
  892. },
  893. (user, next) => {
  894. if (!user) return next('Not logged in.');
  895. if (!user.services.password || !user.services.password.password) return next('You can\'t remove GitHub login without having password login.');
  896. db.models.user.updateOne({_id: session.userId}, {$unset: {"services.github": ''}}, next);
  897. }
  898. ], async (err) => {
  899. if (err && err !== true) {
  900. err = await utils.getError(err);
  901. logger.error("UNLINK_GITHUB", `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`);
  902. cb({status: 'failure', message: err});
  903. } else {
  904. logger.success("UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  905. cache.pub('user.unlinkGitHub', session.userId);
  906. cb({
  907. status: 'success',
  908. message: 'Successfully unlinked GitHub.'
  909. });
  910. }
  911. });
  912. }),
  913. /**
  914. * Requests a password reset for an email
  915. *
  916. * @param {Object} session - the session object automatically added by socket.io
  917. * @param {String} email - the email of the user that requests a password reset
  918. * @param {Function} cb - gets called with the result
  919. */
  920. requestPasswordReset: async (session, email, cb) => {
  921. let code = await utils.generateRandomString(8);
  922. async.waterfall([
  923. (next) => {
  924. if (!email || typeof email !== 'string') return next('Invalid email.');
  925. email = email.toLowerCase();
  926. db.models.user.findOne({"email.address": email}, next);
  927. },
  928. (user, next) => {
  929. if (!user) return next('User not found.');
  930. if (!user.services.password || !user.services.password.password) return next('User does not have a password set, and probably uses GitHub to log in.');
  931. next(null, user);
  932. },
  933. (user, next) => {
  934. let expires = new Date();
  935. expires.setDate(expires.getDate() + 1);
  936. db.models.user.findOneAndUpdate({"email.address": email}, {$set: {"services.password.reset": {code: code, expires}}}, {runValidators: true}, next);
  937. },
  938. (user, next) => {
  939. mail.schemas.resetPasswordRequest(user.email.address, user.username, code, next);
  940. }
  941. ], async (err) => {
  942. if (err && err !== true) {
  943. err = await utils.getError(err);
  944. logger.error("REQUEST_PASSWORD_RESET", `Email '${email}' failed to request password reset. '${err}'`);
  945. cb({status: 'failure', message: err});
  946. } else {
  947. logger.success("REQUEST_PASSWORD_RESET", `Email '${email}' successfully requested a password reset.`);
  948. cb({
  949. status: 'success',
  950. message: 'Successfully requested password reset.'
  951. });
  952. }
  953. });
  954. },
  955. /**
  956. * Verifies a reset code
  957. *
  958. * @param {Object} session - the session object automatically added by socket.io
  959. * @param {String} code - the password reset code
  960. * @param {Function} cb - gets called with the result
  961. */
  962. verifyPasswordResetCode: (session, code, cb) => {
  963. async.waterfall([
  964. (next) => {
  965. if (!code || typeof code !== 'string') return next('Invalid code.');
  966. db.models.user.findOne({"services.password.reset.code": code}, next);
  967. },
  968. (user, next) => {
  969. if (!user) return next('Invalid code.');
  970. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  971. next(null);
  972. }
  973. ], async (err) => {
  974. if (err && err !== true) {
  975. err = await utils.getError(err);
  976. logger.error("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  977. cb({status: 'failure', message: err});
  978. } else {
  979. logger.success("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  980. cb({
  981. status: 'success',
  982. message: 'Successfully verified password reset code.'
  983. });
  984. }
  985. });
  986. },
  987. /**
  988. * Changes a user's password with a reset code
  989. *
  990. * @param {Object} session - the session object automatically added by socket.io
  991. * @param {String} code - the password reset code
  992. * @param {String} newPassword - the new password reset code
  993. * @param {Function} cb - gets called with the result
  994. */
  995. changePasswordWithResetCode: (session, code, newPassword, cb) => {
  996. async.waterfall([
  997. (next) => {
  998. if (!code || typeof code !== 'string') return next('Invalid code.');
  999. db.models.user.findOne({"services.password.reset.code": code}, next);
  1000. },
  1001. (user, next) => {
  1002. if (!user) return next('Invalid code.');
  1003. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  1004. next();
  1005. },
  1006. (next) => {
  1007. if (!db.passwordValid(newPassword)) return next('Invalid password. Check if it meets all the requirements.');
  1008. return next();
  1009. },
  1010. (next) => {
  1011. bcrypt.genSalt(10, next);
  1012. },
  1013. // hash the password
  1014. (salt, next) => {
  1015. bcrypt.hash(sha256(newPassword), salt, next);
  1016. },
  1017. (hashedPassword, next) => {
  1018. db.models.user.updateOne({"services.password.reset.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.reset": ''}}, {runValidators: true}, next);
  1019. }
  1020. ], async (err) => {
  1021. if (err && err !== true) {
  1022. err = await utils.getError(err);
  1023. logger.error("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' failed to change password. '${err}'`);
  1024. cb({status: 'failure', message: err});
  1025. } else {
  1026. logger.success("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  1027. cb({
  1028. status: 'success',
  1029. message: 'Successfully changed password.'
  1030. });
  1031. }
  1032. });
  1033. },
  1034. /**
  1035. * Bans a user by userId
  1036. *
  1037. * @param {Object} session - the session object automatically added by socket.io
  1038. * @param {String} value - the user id that is going to be banned
  1039. * @param {String} reason - the reason for the ban
  1040. * @param {String} expiresAt - the time the ban expires
  1041. * @param {Function} cb - gets called with the result
  1042. */
  1043. banUserById: hooks.adminRequired((session, userId, reason, expiresAt, cb) => {
  1044. async.waterfall([
  1045. (next) => {
  1046. if (!userId) return next('You must provide a userId to ban.');
  1047. else if (!reason) return next('You must provide a reason for the ban.');
  1048. else return next();
  1049. },
  1050. (next) => {
  1051. if (!expiresAt || typeof expiresAt !== 'string') return next('Invalid expire date.');
  1052. let date = new Date();
  1053. switch(expiresAt) {
  1054. case '1h':
  1055. expiresAt = date.setHours(date.getHours() + 1);
  1056. break;
  1057. case '12h':
  1058. expiresAt = date.setHours(date.getHours() + 12);
  1059. break;
  1060. case '1d':
  1061. expiresAt = date.setDate(date.getDate() + 1);
  1062. break;
  1063. case '1w':
  1064. expiresAt = date.setDate(date.getDate() + 7);
  1065. break;
  1066. case '1m':
  1067. expiresAt = date.setMonth(date.getMonth() + 1);
  1068. break;
  1069. case '3m':
  1070. expiresAt = date.setMonth(date.getMonth() + 3);
  1071. break;
  1072. case '6m':
  1073. expiresAt = date.setMonth(date.getMonth() + 6);
  1074. break;
  1075. case '1y':
  1076. expiresAt = date.setFullYear(date.getFullYear() + 1);
  1077. break;
  1078. case 'never':
  1079. expiresAt = new Date(3093527980800000);
  1080. break;
  1081. default:
  1082. return next('Invalid expire date.');
  1083. }
  1084. next();
  1085. },
  1086. (next) => {
  1087. punishments.addPunishment('banUserId', userId, reason, expiresAt, userId, next)
  1088. },
  1089. (punishment, next) => {
  1090. cache.pub('user.ban', { userId, punishment });
  1091. next();
  1092. },
  1093. ], async (err) => {
  1094. if (err && err !== true) {
  1095. err = await utils.getError(err);
  1096. logger.error("BAN_USER_BY_ID", `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`);
  1097. cb({status: 'failure', message: err});
  1098. } else {
  1099. logger.success("BAN_USER_BY_ID", `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`);
  1100. cb({
  1101. status: 'success',
  1102. message: 'Successfully banned user.'
  1103. });
  1104. }
  1105. });
  1106. }),
  1107. getFavoriteStations: hooks.loginRequired((session, cb) => {
  1108. async.waterfall([
  1109. (next) => {
  1110. db.models.user.findOne({ _id: session.userId }, next);
  1111. },
  1112. (user, next) => {
  1113. if (!user) return next("User not found.");
  1114. next(null, user);
  1115. }
  1116. ], async (err, user) => {
  1117. if (err && err !== true) {
  1118. err = await utils.getError(err);
  1119. logger.error("GET_FAVORITE_STATIONS", `User ${session.userId} failed to get favorite stations. '${err}'`);
  1120. cb({status: 'failure', message: err});
  1121. } else {
  1122. logger.success("GET_FAVORITE_STATIONS", `User ${session.userId} got favorite stations.`);
  1123. cb({
  1124. status: 'success',
  1125. favoriteStations: user.favoriteStations
  1126. });
  1127. }
  1128. });
  1129. })
  1130. };