users.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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. console.log("LINK4", 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. console.log("LINK1", userId);
  38. utils.socketsFromUser(userId, sockets => {
  39. sockets.forEach(socket => {
  40. socket.emit('event:user.linkGitHub');
  41. });
  42. });
  43. });
  44. cache.sub('user.unlinkPassword', userId => {
  45. console.log("LINK2", userId);
  46. utils.socketsFromUser(userId, sockets => {
  47. sockets.forEach(socket => {
  48. socket.emit('event:user.unlinkPassword');
  49. });
  50. });
  51. });
  52. cache.sub('user.unlinkGitHub', userId => {
  53. console.log("LINK3", userId);
  54. utils.socketsFromUser(userId, sockets => {
  55. sockets.forEach(socket => {
  56. socket.emit('event:user.unlinkGitHub');
  57. });
  58. });
  59. });
  60. module.exports = {
  61. /**
  62. * Lists all Users
  63. *
  64. * @param {Object} session - the session object automatically added by socket.io
  65. * @param {Function} cb - gets called with the result
  66. */
  67. index: hooks.adminRequired((session, cb) => {
  68. async.waterfall([
  69. (next) => {
  70. db.models.user.find({}).exec(next);
  71. }
  72. ], (err, users) => {
  73. if (err) {
  74. err = utils.getError(err);
  75. logger.error("USER_INDEX", `Indexing users failed. "${err}"`);
  76. return cb({status: 'failure', message: err});
  77. } else {
  78. logger.success("USER_INDEX", `Indexing users successful.`);
  79. let filteredUsers = [];
  80. users.forEach(user => {
  81. filteredUsers.push({
  82. _id: user._id,
  83. username: user.username,
  84. role: user.role,
  85. liked: user.liked,
  86. disliked: user.disliked,
  87. songsRequested: user.statistics.songsRequested,
  88. email: {
  89. address: user.email.address,
  90. verified: user.email.verified
  91. },
  92. hasPassword: !!user.services.password,
  93. services: { github: user.services.github }
  94. });
  95. });
  96. return cb({ status: 'success', data: filteredUsers });
  97. }
  98. });
  99. }),
  100. /**
  101. * Logs user in
  102. *
  103. * @param {Object} session - the session object automatically added by socket.io
  104. * @param {String} identifier - the email of the user
  105. * @param {String} password - the plaintext of the user
  106. * @param {Function} cb - gets called with the result
  107. */
  108. login: (session, identifier, password, cb) => {
  109. identifier = identifier.toLowerCase();
  110. async.waterfall([
  111. // check if a user with the requested identifier exists
  112. (next) => {
  113. db.models.user.findOne({
  114. $or: [{ 'email.address': identifier }]
  115. }, next)
  116. },
  117. // if the user doesn't exist, respond with a failure
  118. // otherwise compare the requested password and the actual users password
  119. (user, next) => {
  120. if (!user) return next('User not found');
  121. if (!user.services.password || !user.services.password.password) return next('The account you are trying to access uses GitHub to log in.');
  122. bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  123. if (err) return next(err);
  124. if (!match) return next('Incorrect password');
  125. next(null, user);
  126. });
  127. },
  128. (user, next) => {
  129. let sessionId = utils.guid();
  130. cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), (err) => {
  131. if (err) return next(err);
  132. next(null, sessionId);
  133. });
  134. }
  135. ], (err, sessionId) => {
  136. if (err && err !== true) {
  137. err = utils.getError(err);
  138. logger.error("USER_PASSWORD_LOGIN", `Login failed with password for user "${identifier}". "${err}"`);
  139. return cb({status: 'failure', message: err});
  140. }
  141. logger.success("USER_PASSWORD_LOGIN", `Login successful with password for user "${identifier}"`);
  142. cb({ status: 'success', message: 'Login successful', user: {}, SID: sessionId });
  143. });
  144. },
  145. /**
  146. * Registers a new user
  147. *
  148. * @param {Object} session - the session object automatically added by socket.io
  149. * @param {String} username - the username for the new user
  150. * @param {String} email - the email for the new user
  151. * @param {String} password - the plaintext password for the new user
  152. * @param {Object} recaptcha - the recaptcha data
  153. * @param {Function} cb - gets called with the result
  154. */
  155. register: function(session, username, email, password, recaptcha, cb) {
  156. email = email.toLowerCase();
  157. let verificationToken = utils.generateRandomString(64);
  158. async.waterfall([
  159. // verify the request with google recaptcha
  160. (next) => {
  161. if (!db.passwordValid(password)) return next('Invalid password. Check if it meets all the requirements.');
  162. return next();
  163. },
  164. (next) => {
  165. request({
  166. url: 'https://www.google.com/recaptcha/api/siteverify',
  167. method: 'POST',
  168. form: {
  169. 'secret': config.get("apis").recaptcha.secret,
  170. 'response': recaptcha
  171. }
  172. }, next);
  173. },
  174. // check if the response from Google recaptcha is successful
  175. // if it is, we check if a user with the requested username already exists
  176. (response, body, next) => {
  177. let json = JSON.parse(body);
  178. if (json.success !== true) return next('Response from recaptcha was not successful.');
  179. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, next);
  180. },
  181. // if the user already exists, respond with that
  182. // otherwise check if a user with the requested email already exists
  183. (user, next) => {
  184. if (user) return next('A user with that username already exists.');
  185. db.models.user.findOne({ 'email.address': email }, next);
  186. },
  187. // if the user already exists, respond with that
  188. // otherwise, generate a salt to use with hashing the new users password
  189. (user, next) => {
  190. if (user) return next('A user with that email already exists.');
  191. bcrypt.genSalt(10, next);
  192. },
  193. // hash the password
  194. (salt, next) => {
  195. bcrypt.hash(sha256(password), salt, next)
  196. },
  197. // save the new user to the database
  198. (hash, next) => {
  199. db.models.user.create({
  200. _id: utils.generateRandomString(12),//TODO Check if exists
  201. username,
  202. email: {
  203. address: email,
  204. verificationToken
  205. },
  206. services: {
  207. password: {
  208. password: hash
  209. }
  210. }
  211. }, next);
  212. },
  213. // respond with the new user
  214. (newUser, next) => {
  215. //TODO Send verification email
  216. mail.schemas.verifyEmail(email, username, verificationToken, () => {
  217. next();
  218. });
  219. }
  220. ], (err) => {
  221. if (err && err !== true) {
  222. err = utils.getError(err);
  223. logger.error("USER_PASSWORD_REGISTER", `Register failed with password for user "${username}"."${err}"`);
  224. cb({status: 'failure', message: err});
  225. } else {
  226. module.exports.login(session, email, password, (result) => {
  227. let obj = {status: 'success', message: 'Successfully registered.'};
  228. if (result.status === 'success') {
  229. obj.SID = result.SID;
  230. }
  231. logger.success("USER_PASSWORD_REGISTER", `Register successful with password for user "${username}".`);
  232. cb(obj);
  233. });
  234. }
  235. });
  236. },
  237. /**
  238. * Logs out a user
  239. *
  240. * @param {Object} session - the session object automatically added by socket.io
  241. * @param {Function} cb - gets called with the result
  242. */
  243. logout: (session, cb) => {
  244. async.waterfall([
  245. (next) => {
  246. cache.hget('sessions', session.sessionId, next);
  247. },
  248. (session, next) => {
  249. if (!session) return next('Session not found');
  250. next(null, session);
  251. },
  252. (session, next) => {
  253. cache.hdel('sessions', session.sessionId, next);
  254. }
  255. ], (err) => {
  256. if (err && err !== true) {
  257. err = utils.getError(err);
  258. logger.error("USER_LOGOUT", `Logout failed. "${err}" `);
  259. cb({ status: 'failure', message: err });
  260. } else {
  261. logger.success("USER_LOGOUT", `Logout successful.`);
  262. cb({ status: 'success', message: 'Successfully logged out.' });
  263. }
  264. });
  265. },
  266. /**
  267. * Removes all sessions for a user
  268. *
  269. * @param {Object} session - the session object automatically added by socket.io
  270. * @param {String} userId - the id of the user we are trying to delete the sessions of
  271. * @param {Function} cb - gets called with the result
  272. * @param {String} loggedInUser - the logged in userId automatically added by hooks
  273. */
  274. removeSessions: hooks.loginRequired((session, userId, cb, loggedInUser) => {
  275. async.waterfall([
  276. (next) => {
  277. db.models.user.findOne({ _id: loggedInUser }, (err, user) => {
  278. if (user.role !== 'admin' && loggedInUser !== userId) return next('Only admins and the owner of the account can remove their sessions.');
  279. else return next();
  280. });
  281. },
  282. (next) => {
  283. cache.hgetall('sessions', next);
  284. },
  285. (sessions, next) => {
  286. if (!sessions) return next('There are no sessions for this user to remove.');
  287. else {
  288. let keys = Object.keys(sessions);
  289. next(null, keys, sessions);
  290. }
  291. },
  292. (keys, sessions, next) => {
  293. cache.pub('user.removeSessions', userId);
  294. async.each(keys, (sessionId, callback) => {
  295. let session = sessions[sessionId];
  296. if (session.userId === userId) {
  297. cache.hdel('sessions', sessionId, err => {
  298. if (err) return callback(err);
  299. else callback(null);
  300. });
  301. }
  302. }, err => {
  303. next(err);
  304. });
  305. }
  306. ], err => {
  307. if (err) {
  308. err = utils.getError(err);
  309. logger.error("REMOVE_SESSIONS_FOR_USER", `Couldn't remove all sessions for user "${userId}". "${err}"`);
  310. return cb({ status: 'failure', message: err });
  311. } else {
  312. logger.success("REMOVE_SESSIONS_FOR_USER", `Removed all sessions for user "${userId}".`);
  313. return cb({ status: 'success', message: 'Successfully removed all sessions.' });
  314. }
  315. });
  316. }),
  317. /**
  318. * Gets user object from username (only a few properties)
  319. *
  320. * @param {Object} session - the session object automatically added by socket.io
  321. * @param {String} username - the username of the user we are trying to find
  322. * @param {Function} cb - gets called with the result
  323. */
  324. findByUsername: (session, username, cb) => {
  325. async.waterfall([
  326. (next) => {
  327. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, next);
  328. },
  329. (account, next) => {
  330. if (!account) return next('User not found.');
  331. next(null, account);
  332. }
  333. ], (err, account) => {
  334. if (err && err !== true) {
  335. err = utils.getError(err);
  336. logger.error("FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  337. cb({status: 'failure', message: err});
  338. } else {
  339. logger.success("FIND_BY_USERNAME", `User found for username "${username}".`);
  340. return cb({
  341. status: 'success',
  342. data: {
  343. _id: account._id,
  344. username: account.username,
  345. role: account.role,
  346. email: account.email.address,
  347. createdAt: account.createdAt,
  348. statistics: account.statistics,
  349. liked: account.liked,
  350. disliked: account.disliked
  351. }
  352. });
  353. }
  354. });
  355. },
  356. /**
  357. * Gets a username from an userId
  358. *
  359. * @param {Object} session - the session object automatically added by socket.io
  360. * @param {String} userId - the userId of the person we are trying to get the username from
  361. * @param {Function} cb - gets called with the result
  362. */
  363. getUsernameFromId: (session, userId, cb) => {
  364. async.waterfall([
  365. (next) => {
  366. db.models.user.findOne({ _id: userId }, next);
  367. },
  368. ], (err, user) => {
  369. if (err && err !== true) {
  370. err = utils.getError(err);
  371. logger.error("GET_USERNAME_FROM_ID", `Getting the username from userId "${userId}" failed. "${err}"`);
  372. cb({status: 'failure', message: err});
  373. } else {
  374. logger.success("GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  375. return cb({
  376. status: 'success',
  377. data: user.username
  378. });
  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.update({ _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.update({_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.update({_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.update({_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.update({"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.update({_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.update({_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.update({"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 (!expiresAt || typeof expiresAt !== 'string') return next('Invalid expire date.');
  936. let date = new Date();
  937. switch(expiresAt) {
  938. case '1h':
  939. //expiresAt = date.setHours(date.getHours() + 1);
  940. expiresAt = date.setMinutes(date.getMinutes() + 1);
  941. break;
  942. case '12h':
  943. expiresAt = date.setHours(date.getHours() + 12);
  944. break;
  945. case '1d':
  946. expiresAt = date.setDate(date.getDate() + 1);
  947. break;
  948. case '1w':
  949. expiresAt = date.setDate(date.getDate() + 7);
  950. break;
  951. case '1m':
  952. expiresAt = date.setMonth(date.getMonth() + 1);
  953. break;
  954. case '3m':
  955. expiresAt = date.setMonth(date.getMonth() + 3);
  956. break;
  957. case '6m':
  958. expiresAt = date.setMonth(date.getMonth() + 6);
  959. break;
  960. case '1y':
  961. expiresAt = date.setFullYear(date.getFullYear() + 1);
  962. break;
  963. case 'never':
  964. expiresAt = new Date(3093527980800000);
  965. break;
  966. default:
  967. return next('Invalid expire date.');
  968. }
  969. next();
  970. },
  971. (next) => {
  972. punishments.addPunishment('banUserId', value, reason, expiresAt, userId, next)
  973. },
  974. (next) => {
  975. //TODO Emit to all users with userId as value
  976. next();
  977. },
  978. ], (err) => {
  979. if (err && err !== true) {
  980. err = utils.getError(err);
  981. logger.error("BAN_USER_BY_ID", `User ${userId} failed to ban user ${value} with the reason ${reason}. '${err}'`);
  982. cb({status: 'failure', message: err});
  983. } else {
  984. logger.success("BAN_USER_BY_ID", `User ${userId} has successfully banned user ${value} with the reason ${reason}.`);
  985. cb({
  986. status: 'success',
  987. message: 'Successfully banned user.'
  988. });
  989. }
  990. });
  991. })
  992. };