users.js 28 KB

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