users.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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. async.waterfall([
  369. (next) => {
  370. db.models.user.findOne({ _id: userId }, next);
  371. },
  372. ], (err, user) => {
  373. if (err && err !== true) {
  374. err = utils.getError(err);
  375. logger.error("GET_USERNAME_FROM_ID", `Getting the username from userId "${userId}" failed. "${err}"`);
  376. cb({status: 'failure', message: err});
  377. } else {
  378. logger.success("GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  379. return cb({
  380. status: 'success',
  381. data: user.username
  382. });
  383. }
  384. });
  385. },
  386. //TODO Fix security issues
  387. /**
  388. * Gets user info from session
  389. *
  390. * @param {Object} session - the session object automatically added by socket.io
  391. * @param {Function} cb - gets called with the result
  392. */
  393. findBySession: (session, cb) => {
  394. async.waterfall([
  395. (next) => {
  396. cache.hget('sessions', session.sessionId, next);
  397. },
  398. (session, next) => {
  399. if (!session) return next('Session not found.');
  400. next(null, session);
  401. },
  402. (session, next) => {
  403. db.models.user.findOne({ _id: session.userId }, next);
  404. },
  405. (user, next) => {
  406. if (!user) return next('User not found.');
  407. next(null, user);
  408. }
  409. ], (err, user) => {
  410. if (err && err !== true) {
  411. err = utils.getError(err);
  412. logger.error("FIND_BY_SESSION", `User not found. "${err}"`);
  413. cb({status: 'failure', message: err});
  414. } else {
  415. let data = {
  416. email: {
  417. address: user.email.address
  418. },
  419. username: user.username
  420. };
  421. if (user.services.password && user.services.password.password) data.password = true;
  422. if (user.services.github && user.services.github.id) data.github = true;
  423. logger.success("FIND_BY_SESSION", `User found. "${user.username}".`);
  424. return cb({
  425. status: 'success',
  426. data
  427. });
  428. }
  429. });
  430. },
  431. /**
  432. * Updates a user's username
  433. *
  434. * @param {Object} session - the session object automatically added by socket.io
  435. * @param {String} updatingUserId - the updating user's id
  436. * @param {String} newUsername - the new username
  437. * @param {Function} cb - gets called with the result
  438. * @param {String} userId - the userId automatically added by hooks
  439. */
  440. updateUsername: hooks.loginRequired((session, updatingUserId, newUsername, cb, userId) => {
  441. async.waterfall([
  442. (next) => {
  443. if (updatingUserId === userId) return next(null, true);
  444. db.models.user.findOne({_id: userId}, next);
  445. },
  446. (user, next) => {
  447. if (user !== true && (!user || user.role !== 'admin')) return next('Invalid permissions.');
  448. db.models.user.findOne({ _id: updatingUserId }, next);
  449. },
  450. (user, next) => {
  451. if (!user) return next('User not found.');
  452. if (user.username === newUsername) return next('New username can\'t be the same as the old username.');
  453. next(null);
  454. },
  455. (next) => {
  456. db.models.user.findOne({ username: new RegExp(`^${newUsername}$`, 'i') }, next);
  457. },
  458. (user, next) => {
  459. if (!user) return next();
  460. if (user._id === updatingUserId) return next();
  461. next('That username is already in use.');
  462. },
  463. (next) => {
  464. db.models.user.update({ _id: updatingUserId }, {$set: {username: newUsername}}, {runValidators: true}, next);
  465. }
  466. ], (err) => {
  467. if (err && err !== true) {
  468. err = utils.getError(err);
  469. logger.error("UPDATE_USERNAME", `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`);
  470. cb({status: 'failure', message: err});
  471. } else {
  472. cache.pub('user.updateUsername', {
  473. username: newUsername,
  474. _id: updatingUserId
  475. });
  476. logger.success("UPDATE_USERNAME", `Updated username for user "${updatingUserId}" to username "${newUsername}".`);
  477. cb({ status: 'success', message: 'Username updated successfully' });
  478. }
  479. });
  480. }),
  481. /**
  482. * Updates a user's email
  483. *
  484. * @param {Object} session - the session object automatically added by socket.io
  485. * @param {String} updatingUserId - the updating user's id
  486. * @param {String} newEmail - the new email
  487. * @param {Function} cb - gets called with the result
  488. * @param {String} userId - the userId automatically added by hooks
  489. */
  490. updateEmail: hooks.loginRequired((session, updatingUserId, newEmail, cb, userId) => {
  491. newEmail = newEmail.toLowerCase();
  492. let verificationToken = utils.generateRandomString(64);
  493. async.waterfall([
  494. (next) => {
  495. if (updatingUserId === userId) return next(null, true);
  496. db.models.user.findOne({_id: userId}, next);
  497. },
  498. (user, next) => {
  499. if (user !== true && (!user || user.role !== 'admin')) return next('Invalid permissions.');
  500. db.models.user.findOne({ _id: updatingUserId }, next);
  501. },
  502. (user, next) => {
  503. if (!user) return next('User not found.');
  504. if (user.email.address === newEmail) return next('New email can\'t be the same as your the old email.');
  505. next();
  506. },
  507. (next) => {
  508. db.models.user.findOne({"email.address": newEmail}, next);
  509. },
  510. (user, next) => {
  511. if (!user) return next();
  512. if (user._id === updatingUserId) return next();
  513. next('That email is already in use.');
  514. },
  515. (next) => {
  516. db.models.user.update({_id: updatingUserId}, {$set: {"email.address": newEmail, "email.verified": false, "email.verificationToken": verificationToken}}, {runValidators: true}, next);
  517. },
  518. (res, next) => {
  519. db.models.user.findOne({ _id: updatingUserId }, next);
  520. },
  521. (user, next) => {
  522. mail.schemas.verifyEmail(newEmail, user.username, verificationToken, () => {
  523. next();
  524. });
  525. }
  526. ], (err) => {
  527. if (err && err !== true) {
  528. err = utils.getError(err);
  529. logger.error("UPDATE_EMAIL", `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`);
  530. cb({status: 'failure', message: err});
  531. } else {
  532. logger.success("UPDATE_EMAIL", `Updated email for user "${updatingUserId}" to email "${newEmail}".`);
  533. cb({ status: 'success', message: 'Email updated successfully.' });
  534. }
  535. });
  536. }),
  537. /**
  538. * Updates a user's role
  539. *
  540. * @param {Object} session - the session object automatically added by socket.io
  541. * @param {String} updatingUserId - the updating user's id
  542. * @param {String} newRole - the new role
  543. * @param {Function} cb - gets called with the result
  544. * @param {String} userId - the userId automatically added by hooks
  545. */
  546. updateRole: hooks.adminRequired((session, updatingUserId, newRole, cb, userId) => {
  547. newRole = newRole.toLowerCase();
  548. async.waterfall([
  549. (next) => {
  550. db.models.user.findOne({ _id: updatingUserId }, next);
  551. },
  552. (user, next) => {
  553. if (!user) return next('User not found.');
  554. else if (user.role === newRole) return next('New role can\'t be the same as the old role.');
  555. else return next();
  556. },
  557. (next) => {
  558. db.models.user.update({_id: updatingUserId}, {$set: {role: newRole}}, {runValidators: true}, next);
  559. }
  560. ], (err) => {
  561. if (err && err !== true) {
  562. err = utils.getError(err);
  563. logger.error("UPDATE_ROLE", `User "${userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`);
  564. cb({status: 'failure', message: err});
  565. } else {
  566. logger.success("UPDATE_ROLE", `User "${userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`);
  567. cb({
  568. status: 'success',
  569. message: 'Role successfully updated.'
  570. });
  571. }
  572. });
  573. }),
  574. /**
  575. * Updates a user's password
  576. *
  577. * @param {Object} session - the session object automatically added by socket.io
  578. * @param {String} newPassword - the new password
  579. * @param {Function} cb - gets called with the result
  580. * @param {String} userId - the userId automatically added by hooks
  581. */
  582. updatePassword: hooks.loginRequired((session, newPassword, cb, userId) => {
  583. async.waterfall([
  584. (next) => {
  585. db.models.user.findOne({_id: userId}, next);
  586. },
  587. (user, next) => {
  588. if (!user.services.password) return next('This account does not have a password set.');
  589. next();
  590. },
  591. (next) => {
  592. if (!db.passwordValid(newPassword)) return next('Invalid password. Check if it meets all the requirements.');
  593. return next();
  594. },
  595. (next) => {
  596. bcrypt.genSalt(10, next);
  597. },
  598. // hash the password
  599. (salt, next) => {
  600. bcrypt.hash(sha256(newPassword), salt, next);
  601. },
  602. (hashedPassword, next) => {
  603. db.models.user.update({_id: userId}, {$set: {"services.password.password": hashedPassword}}, next);
  604. }
  605. ], (err) => {
  606. if (err) {
  607. err = utils.getError(err);
  608. logger.error("UPDATE_PASSWORD", `Failed updating user password of user '${userId}'. '${err}'.`);
  609. return cb({ status: 'failure', message: err });
  610. }
  611. logger.success("UPDATE_PASSWORD", `User '${userId}' updated their password.`);
  612. cb({
  613. status: 'success',
  614. message: 'Password successfully updated.'
  615. });
  616. });
  617. }),
  618. /**
  619. * Requests a password for a session
  620. *
  621. * @param {Object} session - the session object automatically added by socket.io
  622. * @param {String} email - the email of the user that requests a password reset
  623. * @param {Function} cb - gets called with the result
  624. * @param {String} userId - the userId automatically added by hooks
  625. */
  626. requestPassword: hooks.loginRequired((session, cb, userId) => {
  627. let code = utils.generateRandomString(8);
  628. async.waterfall([
  629. (next) => {
  630. db.models.user.findOne({_id: userId}, next);
  631. },
  632. (user, next) => {
  633. if (!user) return next('User not found.');
  634. if (user.services.password && user.services.password.password) return next('You already have a password set.');
  635. next(null, user);
  636. },
  637. (user, next) => {
  638. let expires = new Date();
  639. expires.setDate(expires.getDate() + 1);
  640. db.models.user.findOneAndUpdate({"email.address": user.email.address}, {$set: {"services.password": {set: {code: code, expires}}}}, {runValidators: true}, next);
  641. },
  642. (user, next) => {
  643. mail.schemas.passwordRequest(user.email.address, user.username, code, next);
  644. }
  645. ], (err) => {
  646. if (err && err !== true) {
  647. err = utils.getError(err);
  648. logger.error("REQUEST_PASSWORD", `UserId '${userId}' failed to request password. '${err}'`);
  649. cb({status: 'failure', message: err});
  650. } else {
  651. logger.success("REQUEST_PASSWORD", `UserId '${userId}' successfully requested a password.`);
  652. cb({
  653. status: 'success',
  654. message: 'Successfully requested password.'
  655. });
  656. }
  657. });
  658. }),
  659. /**
  660. * Verifies a password code
  661. *
  662. * @param {Object} session - the session object automatically added by socket.io
  663. * @param {String} code - the password code
  664. * @param {Function} cb - gets called with the result
  665. * @param {String} userId - the userId automatically added by hooks
  666. */
  667. verifyPasswordCode: hooks.loginRequired((session, code, cb, userId) => {
  668. async.waterfall([
  669. (next) => {
  670. if (!code || typeof code !== 'string') return next('Invalid code1.');
  671. db.models.user.findOne({"services.password.set.code": code, _id: userId}, next);
  672. },
  673. (user, next) => {
  674. if (!user) return next('Invalid code2.');
  675. if (user.services.password.set.expires < new Date()) return next('That code has expired.');
  676. next(null);
  677. }
  678. ], (err) => {
  679. if (err && err !== true) {
  680. err = utils.getError(err);
  681. logger.error("VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  682. cb({status: 'failure', message: err});
  683. } else {
  684. logger.success("VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  685. cb({
  686. status: 'success',
  687. message: 'Successfully verified password code.'
  688. });
  689. }
  690. });
  691. }),
  692. /**
  693. * Adds a password to a user with a code
  694. *
  695. * @param {Object} session - the session object automatically added by socket.io
  696. * @param {String} code - the password code
  697. * @param {String} newPassword - the new password code
  698. * @param {Function} cb - gets called with the result
  699. * @param {String} userId - the userId automatically added by hooks
  700. */
  701. changePasswordWithCode: hooks.loginRequired((session, code, newPassword, cb, userId) => {
  702. async.waterfall([
  703. (next) => {
  704. if (!code || typeof code !== 'string') return next('Invalid code1.');
  705. db.models.user.findOne({"services.password.set.code": code}, next);
  706. },
  707. (user, next) => {
  708. if (!user) return next('Invalid code2.');
  709. if (!user.services.password.set.expires > new Date()) return next('That code has expired.');
  710. next();
  711. },
  712. (next) => {
  713. if (!db.passwordValid(newPassword)) return next('Invalid password. Check if it meets all the requirements.');
  714. return next();
  715. },
  716. (next) => {
  717. bcrypt.genSalt(10, next);
  718. },
  719. // hash the password
  720. (salt, next) => {
  721. bcrypt.hash(sha256(newPassword), salt, next);
  722. },
  723. (hashedPassword, next) => {
  724. db.models.user.update({"services.password.set.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.set": ''}}, {runValidators: true}, next);
  725. }
  726. ], (err) => {
  727. if (err && err !== true) {
  728. err = utils.getError(err);
  729. logger.error("ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  730. cb({status: 'failure', message: err});
  731. } else {
  732. logger.success("ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  733. cache.pub('user.linkPassword', userId);
  734. cb({
  735. status: 'success',
  736. message: 'Successfully added password.'
  737. });
  738. }
  739. });
  740. }),
  741. /**
  742. * Unlinks password from user
  743. *
  744. * @param {Object} session - the session object automatically added by socket.io
  745. * @param {Function} cb - gets called with the result
  746. * @param {String} userId - the userId automatically added by hooks
  747. */
  748. unlinkPassword: hooks.loginRequired((session, cb, userId) => {
  749. async.waterfall([
  750. (next) => {
  751. db.models.user.findOne({_id: userId}, next);
  752. },
  753. (user, next) => {
  754. if (!user) return next('Not logged in.');
  755. if (!user.services.github || !user.services.github.id) return next('You can\'t remove password login without having GitHub login.');
  756. db.models.user.update({_id: userId}, {$unset: {"services.password": ''}}, next);
  757. }
  758. ], (err) => {
  759. if (err && err !== true) {
  760. err = utils.getError(err);
  761. logger.error("UNLINK_PASSWORD", `Unlinking password failed for userId '${userId}'. '${err}'`);
  762. cb({status: 'failure', message: err});
  763. } else {
  764. logger.success("UNLINK_PASSWORD", `Unlinking password successful for userId '${userId}'.`);
  765. cache.pub('user.unlinkPassword', userId);
  766. cb({
  767. status: 'success',
  768. message: 'Successfully unlinked password.'
  769. });
  770. }
  771. });
  772. }),
  773. /**
  774. * Unlinks GitHub from user
  775. *
  776. * @param {Object} session - the session object automatically added by socket.io
  777. * @param {Function} cb - gets called with the result
  778. * @param {String} userId - the userId automatically added by hooks
  779. */
  780. unlinkGitHub: hooks.loginRequired((session, cb, userId) => {
  781. async.waterfall([
  782. (next) => {
  783. db.models.user.findOne({_id: userId}, next);
  784. },
  785. (user, next) => {
  786. if (!user) return next('Not logged in.');
  787. if (!user.services.password || !user.services.password.password) return next('You can\'t remove GitHub login without having password login.');
  788. db.models.user.update({_id: userId}, {$unset: {"services.github": ''}}, next);
  789. }
  790. ], (err) => {
  791. if (err && err !== true) {
  792. err = utils.getError(err);
  793. logger.error("UNLINK_GITHUB", `Unlinking GitHub failed for userId '${userId}'. '${err}'`);
  794. cb({status: 'failure', message: err});
  795. } else {
  796. logger.success("UNLINK_GITHUB", `Unlinking GitHub successful for userId '${userId}'.`);
  797. cache.pub('user.unlinkGitHub', userId);
  798. cb({
  799. status: 'success',
  800. message: 'Successfully unlinked GitHub.'
  801. });
  802. }
  803. });
  804. }),
  805. /**
  806. * Requests a password reset for an email
  807. *
  808. * @param {Object} session - the session object automatically added by socket.io
  809. * @param {String} email - the email of the user that requests a password reset
  810. * @param {Function} cb - gets called with the result
  811. */
  812. requestPasswordReset: (session, email, cb) => {
  813. let code = utils.generateRandomString(8);
  814. async.waterfall([
  815. (next) => {
  816. if (!email || typeof email !== 'string') return next('Invalid email.');
  817. email = email.toLowerCase();
  818. db.models.user.findOne({"email.address": email}, next);
  819. },
  820. (user, next) => {
  821. if (!user) return next('User not found.');
  822. if (!user.services.password || !user.services.password.password) return next('User does not have a password set, and probably uses GitHub to log in.');
  823. next(null, user);
  824. },
  825. (user, next) => {
  826. let expires = new Date();
  827. expires.setDate(expires.getDate() + 1);
  828. db.models.user.findOneAndUpdate({"email.address": email}, {$set: {"services.password.reset": {code: code, expires}}}, {runValidators: true}, next);
  829. },
  830. (user, next) => {
  831. mail.schemas.resetPasswordRequest(user.email.address, user.username, code, next);
  832. }
  833. ], (err) => {
  834. if (err && err !== true) {
  835. err = utils.getError(err);
  836. logger.error("REQUEST_PASSWORD_RESET", `Email '${email}' failed to request password reset. '${err}'`);
  837. cb({status: 'failure', message: err});
  838. } else {
  839. logger.success("REQUEST_PASSWORD_RESET", `Email '${email}' successfully requested a password reset.`);
  840. cb({
  841. status: 'success',
  842. message: 'Successfully requested password reset.'
  843. });
  844. }
  845. });
  846. },
  847. /**
  848. * Verifies a reset code
  849. *
  850. * @param {Object} session - the session object automatically added by socket.io
  851. * @param {String} code - the password reset code
  852. * @param {Function} cb - gets called with the result
  853. */
  854. verifyPasswordResetCode: (session, code, cb) => {
  855. async.waterfall([
  856. (next) => {
  857. if (!code || typeof code !== 'string') return next('Invalid code.');
  858. db.models.user.findOne({"services.password.reset.code": code}, next);
  859. },
  860. (user, next) => {
  861. if (!user) return next('Invalid code.');
  862. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  863. next(null);
  864. }
  865. ], (err) => {
  866. if (err && err !== true) {
  867. err = utils.getError(err);
  868. logger.error("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  869. cb({status: 'failure', message: err});
  870. } else {
  871. logger.success("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  872. cb({
  873. status: 'success',
  874. message: 'Successfully verified password reset code.'
  875. });
  876. }
  877. });
  878. },
  879. /**
  880. * Changes a user's password with a reset code
  881. *
  882. * @param {Object} session - the session object automatically added by socket.io
  883. * @param {String} code - the password reset code
  884. * @param {String} newPassword - the new password reset code
  885. * @param {Function} cb - gets called with the result
  886. */
  887. changePasswordWithResetCode: (session, code, newPassword, cb) => {
  888. async.waterfall([
  889. (next) => {
  890. if (!code || typeof code !== 'string') return next('Invalid code.');
  891. db.models.user.findOne({"services.password.reset.code": code}, next);
  892. },
  893. (user, next) => {
  894. if (!user) return next('Invalid code.');
  895. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  896. next();
  897. },
  898. (next) => {
  899. if (!db.passwordValid(newPassword)) return next('Invalid password. Check if it meets all the requirements.');
  900. return next();
  901. },
  902. (next) => {
  903. bcrypt.genSalt(10, next);
  904. },
  905. // hash the password
  906. (salt, next) => {
  907. bcrypt.hash(sha256(newPassword), salt, next);
  908. },
  909. (hashedPassword, next) => {
  910. db.models.user.update({"services.password.reset.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.reset": ''}}, {runValidators: true}, next);
  911. }
  912. ], (err) => {
  913. if (err && err !== true) {
  914. err = utils.getError(err);
  915. logger.error("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' failed to change password. '${err}'`);
  916. cb({status: 'failure', message: err});
  917. } else {
  918. logger.success("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  919. cb({
  920. status: 'success',
  921. message: 'Successfully changed password.'
  922. });
  923. }
  924. });
  925. },
  926. /**
  927. * Bans a user by userId
  928. *
  929. * @param {Object} session - the session object automatically added by socket.io
  930. * @param {String} value - the user id that is going to be banned
  931. * @param {String} reason - the reason for the ban
  932. * @param {String} expiresAt - the time the ban expires
  933. * @param {Function} cb - gets called with the result
  934. * @param {String} userId - the userId automatically added by hooks
  935. */
  936. banUserById: hooks.adminRequired((session, value, reason, expiresAt, cb, userId) => {
  937. async.waterfall([
  938. (next) => {
  939. if (value === '') return next('You must provide an IP address to ban.');
  940. else if (reason === '') return next('You must provide a reason for the ban.');
  941. else return next();
  942. },
  943. (next) => {
  944. if (!expiresAt || typeof expiresAt !== 'string') return next('Invalid expire date.');
  945. let date = new Date();
  946. switch(expiresAt) {
  947. case '1h':
  948. expiresAt = date.setHours(date.getHours() + 1);
  949. break;
  950. case '12h':
  951. expiresAt = date.setHours(date.getHours() + 12);
  952. break;
  953. case '1d':
  954. expiresAt = date.setDate(date.getDate() + 1);
  955. break;
  956. case '1w':
  957. expiresAt = date.setDate(date.getDate() + 7);
  958. break;
  959. case '1m':
  960. expiresAt = date.setMonth(date.getMonth() + 1);
  961. break;
  962. case '3m':
  963. expiresAt = date.setMonth(date.getMonth() + 3);
  964. break;
  965. case '6m':
  966. expiresAt = date.setMonth(date.getMonth() + 6);
  967. break;
  968. case '1y':
  969. expiresAt = date.setFullYear(date.getFullYear() + 1);
  970. break;
  971. case 'never':
  972. expiresAt = new Date(3093527980800000);
  973. break;
  974. default:
  975. return next('Invalid expire date.');
  976. }
  977. next();
  978. },
  979. (next) => {
  980. punishments.addPunishment('banUserId', value, reason, expiresAt, userId, next)
  981. },
  982. (punishment, next) => {
  983. cache.pub('user.ban', {userId: value, punishment});
  984. next();
  985. },
  986. ], (err) => {
  987. if (err && err !== true) {
  988. err = utils.getError(err);
  989. logger.error("BAN_USER_BY_ID", `User ${userId} failed to ban user ${value} with the reason ${reason}. '${err}'`);
  990. cb({status: 'failure', message: err});
  991. } else {
  992. logger.success("BAN_USER_BY_ID", `User ${userId} has successfully banned user ${value} with the reason ${reason}.`);
  993. cb({
  994. status: 'success',
  995. message: 'Successfully banned user.'
  996. });
  997. }
  998. });
  999. })
  1000. };