users.js 34 KB

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