users.js 34 KB

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