users.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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. logger.error("USER_INDEX", `Indexing users failed. "${err.message}"`);
  67. return cb({status: 'failure', message: 'Something went wrong.'});
  68. } else {
  69. logger.success("USER_INDEX", `Indexing users successful.`);
  70. let filteredUsers = [];
  71. users.forEach(user => {
  72. filteredUsers.push({
  73. _id: user._id,
  74. username: user.username,
  75. role: user.role,
  76. liked: user.liked,
  77. disliked: user.disliked,
  78. songsRequested: user.statistics.songsRequested,
  79. email: {
  80. address: user.email.address,
  81. verified: user.email.verified
  82. },
  83. hasPassword: !!user.services.password,
  84. services: { github: user.services.github }
  85. });
  86. });
  87. return cb({ status: 'success', data: filteredUsers });
  88. }
  89. });
  90. }),
  91. /**
  92. * Logs user in
  93. *
  94. * @param {Object} session - the session object automatically added by socket.io
  95. * @param {String} identifier - the email of the user
  96. * @param {String} password - the plaintext of the user
  97. * @param {Function} cb - gets called with the result
  98. */
  99. login: (session, identifier, password, cb) => {
  100. identifier = identifier.toLowerCase();
  101. async.waterfall([
  102. // check if a user with the requested identifier exists
  103. (next) => {
  104. db.models.user.findOne({
  105. $or: [{ 'email.address': identifier }]
  106. }, next)
  107. },
  108. // if the user doesn't exist, respond with a failure
  109. // otherwise compare the requested password and the actual users password
  110. (user, next) => {
  111. if (!user) return next('User not found');
  112. if (!user.services.password || !user.services.password.password) return next('The account you are trying to access uses GitHub to log in.');
  113. bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  114. if (err) return next(err);
  115. if (!match) return next('Incorrect password');
  116. next(null, user);
  117. });
  118. },
  119. (user, next) => {
  120. let sessionId = utils.guid();
  121. cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), (err) => {
  122. if (err) return next(err);
  123. next(null, sessionId);
  124. });
  125. }
  126. ], (err, sessionId) => {
  127. if (err && err !== true) {
  128. let error = 'An error occurred.';
  129. if (typeof err === "string") error = err;
  130. else if (err.message) error = err.message;
  131. logger.error("USER_PASSWORD_LOGIN", "Login failed with password for user " + identifier + '. "' + error + '"');
  132. return cb({ status: 'failure', message: error });
  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. request({
  155. url: 'https://www.google.com/recaptcha/api/siteverify',
  156. method: 'POST',
  157. form: {
  158. 'secret': config.get("apis").recaptcha.secret,
  159. 'response': recaptcha
  160. }
  161. }, next);
  162. },
  163. // check if the response from Google recaptcha is successful
  164. // if it is, we check if a user with the requested username already exists
  165. (response, body, next) => {
  166. let json = JSON.parse(body);
  167. if (json.success !== true) return next('Response from recaptcha was not successful.');
  168. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, next);
  169. },
  170. // if the user already exists, respond with that
  171. // otherwise check if a user with the requested email already exists
  172. (user, next) => {
  173. if (user) return next('A user with that username already exists.');
  174. db.models.user.findOne({ 'email.address': email }, next);
  175. },
  176. // if the user already exists, respond with that
  177. // otherwise, generate a salt to use with hashing the new users password
  178. (user, next) => {
  179. if (user) return next('A user with that email already exists.');
  180. bcrypt.genSalt(10, next);
  181. },
  182. // hash the password
  183. (salt, next) => {
  184. bcrypt.hash(sha256(password), salt, next)
  185. },
  186. // save the new user to the database
  187. (hash, next) => {
  188. db.models.user.create({
  189. _id: utils.generateRandomString(12),//TODO Check if exists
  190. username,
  191. email: {
  192. address: email,
  193. verificationToken
  194. },
  195. services: {
  196. password: {
  197. password: hash
  198. }
  199. }
  200. }, next);
  201. },
  202. // respond with the new user
  203. (newUser, next) => {
  204. //TODO Send verification email
  205. mail.schemas.verifyEmail(email, username, verificationToken, () => {
  206. next();
  207. });
  208. }
  209. ], (err) => {
  210. if (err && err !== true) {
  211. let error = 'An error occurred.';
  212. if (typeof err === "string") error = err;
  213. else if (err.message) error = err.message;
  214. logger.error("USER_PASSWORD_REGISTER", "Register failed with password for user. " + '"' + error + '"');
  215. cb({status: 'failure', message: error});
  216. } else {
  217. module.exports.login(session, email, password, (result) => {
  218. let obj = {status: 'success', message: 'Successfully registered.'};
  219. if (result.status === 'success') {
  220. obj.SID = result.SID;
  221. }
  222. logger.success("USER_PASSWORD_REGISTER", "Register successful with password for user '" + username + "'.");
  223. cb(obj);
  224. });
  225. }
  226. });
  227. },
  228. /**
  229. * Logs out a user
  230. *
  231. * @param {Object} session - the session object automatically added by socket.io
  232. * @param {Function} cb - gets called with the result
  233. */
  234. logout: (session, cb) => {
  235. async.waterfall([
  236. (next) => {
  237. cache.hget('sessions', session.sessionId, next);
  238. },
  239. (session, next) => {
  240. if (!session) return next('Session not found');
  241. next(null, session);
  242. },
  243. (session, next) => {
  244. cache.hdel('sessions', session.sessionId, next);
  245. }
  246. ], (err) => {
  247. if (err && err !== true) {
  248. let error = 'An error occurred.';
  249. if (typeof err === "string") error = err;
  250. else if (err.message) error = err.message;
  251. logger.error("USER_LOGOUT", `Logout failed. ${error}`);
  252. cb({status: 'failure', message: error});
  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. let error = 'An error occurred.';
  278. if (typeof err === "string") error = err;
  279. else if (err.message) error = err.message;
  280. logger.error("FIND_BY_USERNAME", `User not found for username '${username}'. ${error}`);
  281. cb({status: 'failure', message: error});
  282. } else {
  283. logger.success("FIND_BY_USERNAME", `User found for username '${username}'.`);
  284. return cb({
  285. status: 'success',
  286. data: {
  287. _id: account._id,
  288. username: account.username,
  289. role: account.role,
  290. email: account.email.address,
  291. createdAt: account.createdAt,
  292. statistics: account.statistics,
  293. liked: account.liked,
  294. disliked: account.disliked
  295. }
  296. });
  297. }
  298. });
  299. },
  300. //TODO Fix security issues
  301. /**
  302. * Gets user info from session
  303. *
  304. * @param {Object} session - the session object automatically added by socket.io
  305. * @param {Function} cb - gets called with the result
  306. */
  307. findBySession: (session, cb) => {
  308. async.waterfall([
  309. (next) => {
  310. cache.hget('sessions', session.sessionId, next);
  311. },
  312. (session, next) => {
  313. if (!session) return next('Session not found.');
  314. next(null, session);
  315. },
  316. (session, next) => {
  317. db.models.user.findOne({ _id: session.userId }, next);
  318. },
  319. (user, next) => {
  320. if (!user) return next('User not found.');
  321. next(null, user);
  322. }
  323. ], (err, user) => {
  324. if (err && err !== true) {
  325. let error = 'An error occurred.';
  326. if (typeof err === "string") error = err;
  327. else if (err.message) error = err.message;
  328. logger.error("FIND_BY_SESSION", `User not found. ${error}`);
  329. cb({status: 'failure', message: error});
  330. } else {
  331. let data = {
  332. email: {
  333. address: user.email.address
  334. },
  335. username: user.username
  336. };
  337. if (user.services.password && user.services.password.password) data.password = true;
  338. if (user.services.github && user.services.github.id) data.github = true;
  339. logger.success("FIND_BY_SESSION", `User found. '${user.username}'.`);
  340. return cb({
  341. status: 'success',
  342. data
  343. });
  344. }
  345. });
  346. },
  347. /**
  348. * Updates a user's username
  349. *
  350. * @param {Object} session - the session object automatically added by socket.io
  351. * @param {String} updatingUserId - the updating user's id
  352. * @param {String} newUsername - the new username
  353. * @param {Function} cb - gets called with the result
  354. * @param {String} userId - the userId automatically added by hooks
  355. */
  356. updateUsername: hooks.loginRequired((session, updatingUserId, newUsername, cb, userId) => {
  357. async.waterfall([
  358. (next) => {
  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}}, next);
  376. }
  377. ], (err) => {
  378. if (err && err !== true) {
  379. let error = 'An error occurred.';
  380. if (typeof err === "string") error = err;
  381. else if (err.message) error = err.message;
  382. logger.error("UPDATE_USERNAME", `Couldn't update username for user '${updatingUserId}' to username '${newUsername}'. '${error}'`);
  383. cb({status: 'failure', message: error});
  384. } else {
  385. cache.pub('user.updateUsername', {
  386. username: newUsername,
  387. _id: updatingUserId
  388. });
  389. logger.success("UPDATE_USERNAME", `Updated username for user '${updatingUserId}' to username '${newUsername}'.`);
  390. cb({ status: 'success', message: 'Username updated successfully' });
  391. }
  392. });
  393. }),
  394. /**
  395. * Updates a user's email
  396. *
  397. * @param {Object} session - the session object automatically added by socket.io
  398. * @param {String} updatingUserId - the updating user's id
  399. * @param {String} newEmail - the new email
  400. * @param {Function} cb - gets called with the result
  401. * @param {String} userId - the userId automatically added by hooks
  402. */
  403. updateEmail: hooks.loginRequired((session, updatingUserId, newEmail, cb, userId) => {
  404. newEmail = newEmail.toLowerCase();
  405. let verificationToken = utils.generateRandomString(64);
  406. async.waterfall([
  407. (next) => {
  408. db.models.user.findOne({ _id: updatingUserId }, next);
  409. },
  410. (user, next) => {
  411. if (!user) return next('User not found.');
  412. if (user.email.address === newEmail) return next('New email can\'t be the same as your the old email.');
  413. next();
  414. },
  415. (next) => {
  416. db.models.user.findOne({"email.address": newEmail}, next);
  417. },
  418. (user, next) => {
  419. if (!user) return next();
  420. if (user._id === updatingUserId) return next();
  421. next('That email is already in use.');
  422. },
  423. (next) => {
  424. db.models.user.update({_id: updatingUserId}, {$set: {"email.address": newEmail, "email.verified": false, "email.verificationToken": verificationToken}}, next);
  425. },
  426. (res, next) => {
  427. db.models.user.findOne({ _id: updatingUserId }, next);
  428. },
  429. (user, next) => {
  430. mail.schemas.verifyEmail(newEmail, user.username, verificationToken, () => {
  431. next();
  432. });
  433. }
  434. ], (err) => {
  435. if (err && err !== true) {
  436. let error = 'An error occurred.';
  437. if (typeof err === "string") error = err;
  438. else if (err.message) error = err.message;
  439. logger.error("UPDATE_EMAIL", `Couldn't update email for user '${updatingUserId}' to email '${newEmail}'. '${error}'`);
  440. cb({status: 'failure', message: error});
  441. } else {
  442. logger.success("UPDATE_EMAIL", `Updated email for user '${updatingUserId}' to email '${newEmail}'.`);
  443. cb({ status: 'success', message: 'Email updated successfully.' });
  444. }
  445. });
  446. }),
  447. /**
  448. * Updates a user's role
  449. *
  450. * @param {Object} session - the session object automatically added by socket.io
  451. * @param {String} updatingUserId - the updating user's id
  452. * @param {String} newRole - the new role
  453. * @param {Function} cb - gets called with the result
  454. * @param {String} userId - the userId automatically added by hooks
  455. */
  456. updateRole: hooks.adminRequired((session, updatingUserId, newRole, cb, userId) => {
  457. newRole = newRole.toLowerCase();
  458. async.waterfall([
  459. (next) => {
  460. db.models.user.findOne({ _id: updatingUserId }, next);
  461. },
  462. (user, next) => {
  463. if (!user) return next('User not found.');
  464. else if (user.role === newRole) return next('New role can\'t be the same as the old role.');
  465. else return next();
  466. },
  467. (next) => {
  468. db.models.user.update({_id: updatingUserId}, {$set: {role: newRole}}, next);
  469. }
  470. ], (err) => {
  471. if (err && err !== true) {
  472. let error = 'An error occurred.';
  473. if (typeof err === "string") error = err;
  474. else if (err.message) error = err.message;
  475. logger.error("UPDATE_ROLE", `User '${userId}' couldn't update role for user '${updatingUserId}' to role '${newRole}'. '${error}'`);
  476. cb({status: 'failure', message: error});
  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. bcrypt.genSalt(10, next);
  505. },
  506. // hash the password
  507. (salt, next) => {
  508. bcrypt.hash(sha256(newPassword), salt, next);
  509. },
  510. (hashedPassword, next) => {
  511. db.models.user.update({_id: userId}, {$set: {"services.password.password": hashedPassword}}, next);
  512. }
  513. ], (err) => {
  514. if (err) {
  515. let error = 'An error occurred.';
  516. if (typeof err === "string") error = err;
  517. else if (err.message) error = err.message;
  518. logger.error("UPDATE_PASSWORD", `Failed updating user password of user '${userId}'. '${error}'.`);
  519. return cb({ status: 'failure', message: error });
  520. }
  521. logger.error("UPDATE_PASSWORD", `User '${userId}' updated their password.`);
  522. cb({
  523. status: 'success',
  524. message: 'Password successfully updated.'
  525. });
  526. });
  527. }),
  528. /**
  529. * Requests a password for a session
  530. *
  531. * @param {Object} session - the session object automatically added by socket.io
  532. * @param {String} email - the email of the user that requests a password reset
  533. * @param {Function} cb - gets called with the result
  534. * @param {String} userId - the userId automatically added by hooks
  535. */
  536. requestPassword: hooks.loginRequired((session, cb, userId) => {
  537. let code = utils.generateRandomString(8);
  538. async.waterfall([
  539. (next) => {
  540. db.models.user.findOne({_id: userId}, next);
  541. },
  542. (user, next) => {
  543. if (!user) return next('User not found.');
  544. if (user.services.password && user.services.password.password) return next('You already have a password set.');
  545. next(null, user);
  546. },
  547. (user, next) => {
  548. let expires = new Date();
  549. expires.setDate(expires.getDate() + 1);
  550. db.models.user.findOneAndUpdate({"email.address": user.email.address}, {$set: {"services.password": {set: {code: code, expires}}}}, next);
  551. },
  552. (user, next) => {
  553. mail.schemas.passwordRequest(user.email.address, user.username, code, next);
  554. }
  555. ], (err) => {
  556. if (err && err !== true) {
  557. let error = 'An error occurred.';
  558. if (typeof err === "string") error = err;
  559. else if (err.message) error = err.message;
  560. logger.error("REQUEST_PASSWORD", `UserId '${userId}' failed to request password. '${error}'`);
  561. cb({status: 'failure', message: error});
  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. let error = 'An error occurred.';
  593. if (typeof err === "string") error = err;
  594. else if (err.message) error = err.message;
  595. logger.error("VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${error}'`);
  596. cb({status: 'failure', message: error});
  597. } else {
  598. logger.success("VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  599. cb({
  600. status: 'success',
  601. message: 'Successfully verified password code.'
  602. });
  603. }
  604. });
  605. }),
  606. /**
  607. * Adds a password to a user with a code
  608. *
  609. * @param {Object} session - the session object automatically added by socket.io
  610. * @param {String} code - the password code
  611. * @param {String} newPassword - the new password code
  612. * @param {Function} cb - gets called with the result
  613. * @param {String} userId - the userId automatically added by hooks
  614. */
  615. changePasswordWithCode: hooks.loginRequired((session, code, newPassword, cb, userId) => {
  616. async.waterfall([
  617. (next) => {
  618. if (!code || typeof code !== 'string') return next('Invalid code1.');
  619. db.models.user.findOne({"services.password.set.code": code}, next);
  620. },
  621. (user, next) => {
  622. if (!user) return next('Invalid code2.');
  623. if (!user.services.password.set.expires > new Date()) return next('That code has expired.');
  624. next();
  625. },
  626. (next) => {
  627. bcrypt.genSalt(10, next);
  628. },
  629. // hash the password
  630. (salt, next) => {
  631. bcrypt.hash(sha256(newPassword), salt, next);
  632. },
  633. (hashedPassword, next) => {
  634. db.models.user.update({"services.password.set.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.set": ''}}, next);
  635. }
  636. ], (err) => {
  637. if (err && err !== true) {
  638. let error = 'An error occurred.';
  639. if (typeof err === "string") error = err;
  640. else if (err.message) error = err.message;
  641. logger.error("ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${error}'`);
  642. cb({status: 'failure', message: error});
  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. let error = 'An error occurred.';
  673. if (typeof err === "string") error = err;
  674. else if (err.message) error = err.message;
  675. logger.error("UNLINK_PASSWORD", `Unlinking password failed for userId '${userId}'. '${error}'`);
  676. cb({status: 'failure', message: error});
  677. } else {
  678. logger.success("UNLINK_PASSWORD", `Unlinking password successful for userId '${userId}'.`);
  679. cache.pub('user.unlinkPassword', userId);
  680. cb({
  681. status: 'success',
  682. message: 'Successfully unlinked password.'
  683. });
  684. }
  685. });
  686. }),
  687. /**
  688. * Unlinks GitHub from user
  689. *
  690. * @param {Object} session - the session object automatically added by socket.io
  691. * @param {Function} cb - gets called with the result
  692. * @param {String} userId - the userId automatically added by hooks
  693. */
  694. unlinkGitHub: hooks.loginRequired((session, cb, userId) => {
  695. async.waterfall([
  696. (next) => {
  697. db.models.user.findOne({_id: userId}, next);
  698. },
  699. (user, next) => {
  700. if (!user) return next('Not logged in.');
  701. if (!user.services.password || !user.services.password.password) return next('You can\'t remove GitHub login without having password login.');
  702. db.models.user.update({_id: userId}, {$unset: {"services.github": ''}}, next);
  703. }
  704. ], (err) => {
  705. if (err && err !== true) {
  706. let error = 'An error occurred.';
  707. if (typeof err === "string") error = err;
  708. else if (err.message) error = err.message;
  709. logger.error("UNLINK_GITHUB", `Unlinking GitHub failed for userId '${userId}'. '${error}'`);
  710. cb({status: 'failure', message: error});
  711. } else {
  712. logger.success("UNLINK_GITHUB", `Unlinking GitHub successful for userId '${userId}'.`);
  713. cache.pub('user.unlinkGitHub', userId);
  714. cb({
  715. status: 'success',
  716. message: 'Successfully unlinked GitHub.'
  717. });
  718. }
  719. });
  720. }),
  721. /**
  722. * Requests a password reset for an email
  723. *
  724. * @param {Object} session - the session object automatically added by socket.io
  725. * @param {String} email - the email of the user that requests a password reset
  726. * @param {Function} cb - gets called with the result
  727. */
  728. requestPasswordReset: (session, email, cb) => {
  729. let code = utils.generateRandomString(8);
  730. async.waterfall([
  731. (next) => {
  732. if (!email || typeof email !== 'string') return next('Invalid email.');
  733. email = email.toLowerCase();
  734. db.models.user.findOne({"email.address": email}, next);
  735. },
  736. (user, next) => {
  737. if (!user) return next('User not found.');
  738. if (!user.services.password || !user.services.password.password) return next('User does not have a password set, and probably uses GitHub to log in.');
  739. next(null, user);
  740. },
  741. (user, next) => {
  742. let expires = new Date();
  743. expires.setDate(expires.getDate() + 1);
  744. db.models.user.findOneAndUpdate({"email.address": email}, {$set: {"services.password.reset": {code: code, expires}}}, next);
  745. },
  746. (user, next) => {
  747. mail.schemas.resetPasswordRequest(user.email.address, user.username, code, next);
  748. }
  749. ], (err) => {
  750. if (err && err !== true) {
  751. let error = 'An error occurred.';
  752. if (typeof err === "string") error = err;
  753. else if (err.message) error = err.message;
  754. logger.error("REQUEST_PASSWORD_RESET", `Email '${email}' failed to request password reset. '${error}'`);
  755. cb({status: 'failure', message: error});
  756. } else {
  757. logger.success("REQUEST_PASSWORD_RESET", `Email '${email}' successfully requested a password reset.`);
  758. cb({
  759. status: 'success',
  760. message: 'Successfully requested password reset.'
  761. });
  762. }
  763. });
  764. },
  765. /**
  766. * Verifies a reset code
  767. *
  768. * @param {Object} session - the session object automatically added by socket.io
  769. * @param {String} code - the password reset code
  770. * @param {Function} cb - gets called with the result
  771. */
  772. verifyPasswordResetCode: (session, code, cb) => {
  773. async.waterfall([
  774. (next) => {
  775. if (!code || typeof code !== 'string') return next('Invalid code.');
  776. db.models.user.findOne({"services.password.reset.code": code}, next);
  777. },
  778. (user, next) => {
  779. if (!user) return next('Invalid code.');
  780. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  781. next(null);
  782. }
  783. ], (err) => {
  784. if (err && err !== true) {
  785. let error = 'An error occurred.';
  786. if (typeof err === "string") error = err;
  787. else if (err.message) error = err.message;
  788. logger.error("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${error}'`);
  789. cb({status: 'failure', message: error});
  790. } else {
  791. logger.success("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  792. cb({
  793. status: 'success',
  794. message: 'Successfully verified password reset code.'
  795. });
  796. }
  797. });
  798. },
  799. /**
  800. * Changes a user's password with a reset code
  801. *
  802. * @param {Object} session - the session object automatically added by socket.io
  803. * @param {String} code - the password reset code
  804. * @param {String} newPassword - the new password reset code
  805. * @param {Function} cb - gets called with the result
  806. */
  807. changePasswordWithResetCode: (session, code, newPassword, cb) => {
  808. async.waterfall([
  809. (next) => {
  810. if (!code || typeof code !== 'string') return next('Invalid code.');
  811. db.models.user.findOne({"services.password.reset.code": code}, next);
  812. },
  813. (user, next) => {
  814. if (!user) return next('Invalid code.');
  815. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  816. next();
  817. },
  818. (next) => {
  819. bcrypt.genSalt(10, next);
  820. },
  821. // hash the password
  822. (salt, next) => {
  823. bcrypt.hash(sha256(newPassword), salt, next);
  824. },
  825. (hashedPassword, next) => {
  826. db.models.user.update({"services.password.reset.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.reset": ''}}, next);
  827. }
  828. ], (err) => {
  829. if (err && err !== true) {
  830. let error = 'An error occurred.';
  831. if (typeof err === "string") error = err;
  832. else if (err.message) error = err.message;
  833. logger.error("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' failed to change password. '${error}'`);
  834. cb({status: 'failure', message: error});
  835. } else {
  836. logger.success("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  837. cb({
  838. status: 'success',
  839. message: 'Successfully changed password.'
  840. });
  841. }
  842. });
  843. }
  844. };