users.js 28 KB

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