users.js 31 KB

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