users.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. db.models.user.findOne({ _id: updatingUserId }, next);
  351. },
  352. (user, next) => {
  353. if (!user) return next('User not found.');
  354. if (user.username === newUsername) return next('New username can\'t be the same as the old username.');
  355. next(null);
  356. },
  357. (next) => {
  358. db.models.user.findOne({ username: new RegExp(`^${newUsername}$`, 'i') }, next);
  359. },
  360. (user, next) => {
  361. if (!user) return next();
  362. if (user._id === updatingUserId) return next();
  363. next('That username is already in use.');
  364. },
  365. (next) => {
  366. db.models.user.update({ _id: updatingUserId }, {$set: {username: newUsername}}, next);
  367. }
  368. ], (err) => {
  369. if (err && err !== true) {
  370. err = utils.getError(err);
  371. logger.error("UPDATE_USERNAME", `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`);
  372. cb({status: 'failure', message: err});
  373. } else {
  374. cache.pub('user.updateUsername', {
  375. username: newUsername,
  376. _id: updatingUserId
  377. });
  378. logger.success("UPDATE_USERNAME", `Updated username for user "${updatingUserId}" to username "${newUsername}".`);
  379. cb({ status: 'success', message: 'Username updated successfully' });
  380. }
  381. });
  382. }),
  383. /**
  384. * Updates a user's email
  385. *
  386. * @param {Object} session - the session object automatically added by socket.io
  387. * @param {String} updatingUserId - the updating user's id
  388. * @param {String} newEmail - the new email
  389. * @param {Function} cb - gets called with the result
  390. * @param {String} userId - the userId automatically added by hooks
  391. */
  392. updateEmail: hooks.loginRequired((session, updatingUserId, newEmail, cb, userId) => {
  393. newEmail = newEmail.toLowerCase();
  394. let verificationToken = utils.generateRandomString(64);
  395. async.waterfall([
  396. (next) => {
  397. db.models.user.findOne({ _id: updatingUserId }, next);
  398. },
  399. (user, next) => {
  400. if (!user) return next('User not found.');
  401. if (user.email.address === newEmail) return next('New email can\'t be the same as your the old email.');
  402. next();
  403. },
  404. (next) => {
  405. db.models.user.findOne({"email.address": newEmail}, next);
  406. },
  407. (user, next) => {
  408. if (!user) return next();
  409. if (user._id === updatingUserId) return next();
  410. next('That email is already in use.');
  411. },
  412. (next) => {
  413. db.models.user.update({_id: updatingUserId}, {$set: {"email.address": newEmail, "email.verified": false, "email.verificationToken": verificationToken}}, next);
  414. },
  415. (res, next) => {
  416. db.models.user.findOne({ _id: updatingUserId }, next);
  417. },
  418. (user, next) => {
  419. mail.schemas.verifyEmail(newEmail, user.username, verificationToken, () => {
  420. next();
  421. });
  422. }
  423. ], (err) => {
  424. if (err && err !== true) {
  425. err = utils.getError(err);
  426. logger.error("UPDATE_EMAIL", `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`);
  427. cb({status: 'failure', message: err});
  428. } else {
  429. logger.success("UPDATE_EMAIL", `Updated email for user "${updatingUserId}" to email "${newEmail}".`);
  430. cb({ status: 'success', message: 'Email updated successfully.' });
  431. }
  432. });
  433. }),
  434. /**
  435. * Updates a user's role
  436. *
  437. * @param {Object} session - the session object automatically added by socket.io
  438. * @param {String} updatingUserId - the updating user's id
  439. * @param {String} newRole - the new role
  440. * @param {Function} cb - gets called with the result
  441. * @param {String} userId - the userId automatically added by hooks
  442. */
  443. updateRole: hooks.adminRequired((session, updatingUserId, newRole, cb, userId) => {
  444. newRole = newRole.toLowerCase();
  445. async.waterfall([
  446. (next) => {
  447. db.models.user.findOne({ _id: updatingUserId }, next);
  448. },
  449. (user, next) => {
  450. if (!user) return next('User not found.');
  451. else if (user.role === newRole) return next('New role can\'t be the same as the old role.');
  452. else return next();
  453. },
  454. (next) => {
  455. db.models.user.update({_id: updatingUserId}, {$set: {role: newRole}}, next);
  456. }
  457. ], (err) => {
  458. if (err && err !== true) {
  459. err = utils.getError(err);
  460. logger.error("UPDATE_ROLE", `User "${userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`);
  461. cb({status: 'failure', message: err});
  462. } else {
  463. logger.success("UPDATE_ROLE", `User "${userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`);
  464. cb({
  465. status: 'success',
  466. message: 'Role successfully updated.'
  467. });
  468. }
  469. });
  470. }),
  471. /**
  472. * Updates a user's password
  473. *
  474. * @param {Object} session - the session object automatically added by socket.io
  475. * @param {String} newPassword - the new password
  476. * @param {Function} cb - gets called with the result
  477. * @param {String} userId - the userId automatically added by hooks
  478. */
  479. updatePassword: hooks.loginRequired((session, newPassword, cb, userId) => {
  480. async.waterfall([
  481. (next) => {
  482. db.models.user.findOne({_id: userId}, next);
  483. },
  484. (user, next) => {
  485. if (!user.services.password) return next('This account does not have a password set.');
  486. next();
  487. },
  488. (next) => {
  489. bcrypt.genSalt(10, next);
  490. },
  491. // hash the password
  492. (salt, next) => {
  493. bcrypt.hash(sha256(newPassword), salt, next);
  494. },
  495. (hashedPassword, next) => {
  496. db.models.user.update({_id: userId}, {$set: {"services.password.password": hashedPassword}}, next);
  497. }
  498. ], (err) => {
  499. if (err) {
  500. err = utils.getError(err);
  501. logger.error("UPDATE_PASSWORD", `Failed updating user password of user '${userId}'. '${err}'.`);
  502. return cb({ status: 'failure', message: err });
  503. }
  504. logger.error("UPDATE_PASSWORD", `User '${userId}' updated their password.`);
  505. cb({
  506. status: 'success',
  507. message: 'Password successfully updated.'
  508. });
  509. });
  510. }),
  511. /**
  512. * Requests a password for a session
  513. *
  514. * @param {Object} session - the session object automatically added by socket.io
  515. * @param {String} email - the email of the user that requests a password reset
  516. * @param {Function} cb - gets called with the result
  517. * @param {String} userId - the userId automatically added by hooks
  518. */
  519. requestPassword: hooks.loginRequired((session, cb, userId) => {
  520. let code = utils.generateRandomString(8);
  521. async.waterfall([
  522. (next) => {
  523. db.models.user.findOne({_id: userId}, next);
  524. },
  525. (user, next) => {
  526. if (!user) return next('User not found.');
  527. if (user.services.password && user.services.password.password) return next('You already have a password set.');
  528. next(null, user);
  529. },
  530. (user, next) => {
  531. let expires = new Date();
  532. expires.setDate(expires.getDate() + 1);
  533. db.models.user.findOneAndUpdate({"email.address": user.email.address}, {$set: {"services.password": {set: {code: code, expires}}}}, next);
  534. },
  535. (user, next) => {
  536. mail.schemas.passwordRequest(user.email.address, user.username, code, next);
  537. }
  538. ], (err) => {
  539. if (err && err !== true) {
  540. err = utils.getError(err);
  541. logger.error("REQUEST_PASSWORD", `UserId '${userId}' failed to request password. '${err}'`);
  542. cb({status: 'failure', message: err});
  543. } else {
  544. logger.success("REQUEST_PASSWORD", `UserId '${userId}' successfully requested a password.`);
  545. cb({
  546. status: 'success',
  547. message: 'Successfully requested password.'
  548. });
  549. }
  550. });
  551. }),
  552. /**
  553. * Verifies a password code
  554. *
  555. * @param {Object} session - the session object automatically added by socket.io
  556. * @param {String} code - the password code
  557. * @param {Function} cb - gets called with the result
  558. * @param {String} userId - the userId automatically added by hooks
  559. */
  560. verifyPasswordCode: hooks.loginRequired((session, code, cb, userId) => {
  561. async.waterfall([
  562. (next) => {
  563. if (!code || typeof code !== 'string') return next('Invalid code1.');
  564. db.models.user.findOne({"services.password.set.code": code, _id: userId}, next);
  565. },
  566. (user, next) => {
  567. if (!user) return next('Invalid code2.');
  568. if (user.services.password.set.expires < new Date()) return next('That code has expired.');
  569. next(null);
  570. }
  571. ], (err) => {
  572. if (err && err !== true) {
  573. err = utils.getError(err);
  574. logger.error("VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  575. cb({status: 'failure', message: err});
  576. } else {
  577. logger.success("VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  578. cb({
  579. status: 'success',
  580. message: 'Successfully verified password code.'
  581. });
  582. }
  583. });
  584. }),
  585. /**
  586. * Adds a password to a user with a code
  587. *
  588. * @param {Object} session - the session object automatically added by socket.io
  589. * @param {String} code - the password code
  590. * @param {String} newPassword - the new password code
  591. * @param {Function} cb - gets called with the result
  592. * @param {String} userId - the userId automatically added by hooks
  593. */
  594. changePasswordWithCode: hooks.loginRequired((session, code, newPassword, cb, userId) => {
  595. async.waterfall([
  596. (next) => {
  597. if (!code || typeof code !== 'string') return next('Invalid code1.');
  598. db.models.user.findOne({"services.password.set.code": code}, next);
  599. },
  600. (user, next) => {
  601. if (!user) return next('Invalid code2.');
  602. if (!user.services.password.set.expires > new Date()) return next('That code has expired.');
  603. next();
  604. },
  605. (next) => {
  606. bcrypt.genSalt(10, next);
  607. },
  608. // hash the password
  609. (salt, next) => {
  610. bcrypt.hash(sha256(newPassword), salt, next);
  611. },
  612. (hashedPassword, next) => {
  613. db.models.user.update({"services.password.set.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.set": ''}}, next);
  614. }
  615. ], (err) => {
  616. if (err && err !== true) {
  617. err = utils.getError(err);
  618. logger.error("ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  619. cb({status: 'failure', message: err});
  620. } else {
  621. logger.success("ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  622. cache.pub('user.linkPassword', userId);
  623. cb({
  624. status: 'success',
  625. message: 'Successfully added password.'
  626. });
  627. }
  628. });
  629. }),
  630. /**
  631. * Unlinks password from user
  632. *
  633. * @param {Object} session - the session object automatically added by socket.io
  634. * @param {Function} cb - gets called with the result
  635. * @param {String} userId - the userId automatically added by hooks
  636. */
  637. unlinkPassword: hooks.loginRequired((session, cb, userId) => {
  638. async.waterfall([
  639. (next) => {
  640. db.models.user.findOne({_id: userId}, next);
  641. },
  642. (user, next) => {
  643. if (!user) return next('Not logged in.');
  644. if (!user.services.github || !user.services.github.id) return next('You can\'t remove password login without having GitHub login.');
  645. db.models.user.update({_id: userId}, {$unset: {"services.password": ''}}, next);
  646. }
  647. ], (err) => {
  648. if (err && err !== true) {
  649. err = utils.getError(err);
  650. logger.error("UNLINK_PASSWORD", `Unlinking password failed for userId '${userId}'. '${err}'`);
  651. cb({status: 'failure', message: err});
  652. } else {
  653. logger.success("UNLINK_PASSWORD", `Unlinking password successful for userId '${userId}'.`);
  654. cache.pub('user.unlinkPassword', userId);
  655. cb({
  656. status: 'success',
  657. message: 'Successfully unlinked password.'
  658. });
  659. }
  660. });
  661. }),
  662. /**
  663. * Unlinks GitHub from user
  664. *
  665. * @param {Object} session - the session object automatically added by socket.io
  666. * @param {Function} cb - gets called with the result
  667. * @param {String} userId - the userId automatically added by hooks
  668. */
  669. unlinkGitHub: hooks.loginRequired((session, cb, userId) => {
  670. async.waterfall([
  671. (next) => {
  672. db.models.user.findOne({_id: userId}, next);
  673. },
  674. (user, next) => {
  675. if (!user) return next('Not logged in.');
  676. if (!user.services.password || !user.services.password.password) return next('You can\'t remove GitHub login without having password login.');
  677. db.models.user.update({_id: userId}, {$unset: {"services.github": ''}}, next);
  678. }
  679. ], (err) => {
  680. if (err && err !== true) {
  681. err = utils.getError(err);
  682. logger.error("UNLINK_GITHUB", `Unlinking GitHub failed for userId '${userId}'. '${err}'`);
  683. cb({status: 'failure', message: err});
  684. } else {
  685. logger.success("UNLINK_GITHUB", `Unlinking GitHub successful for userId '${userId}'.`);
  686. cache.pub('user.unlinkGitHub', userId);
  687. cb({
  688. status: 'success',
  689. message: 'Successfully unlinked GitHub.'
  690. });
  691. }
  692. });
  693. }),
  694. /**
  695. * Requests a password reset for an email
  696. *
  697. * @param {Object} session - the session object automatically added by socket.io
  698. * @param {String} email - the email of the user that requests a password reset
  699. * @param {Function} cb - gets called with the result
  700. */
  701. requestPasswordReset: (session, email, cb) => {
  702. let code = utils.generateRandomString(8);
  703. async.waterfall([
  704. (next) => {
  705. if (!email || typeof email !== 'string') return next('Invalid email.');
  706. email = email.toLowerCase();
  707. db.models.user.findOne({"email.address": email}, next);
  708. },
  709. (user, next) => {
  710. if (!user) return next('User not found.');
  711. if (!user.services.password || !user.services.password.password) return next('User does not have a password set, and probably uses GitHub to log in.');
  712. next(null, user);
  713. },
  714. (user, next) => {
  715. let expires = new Date();
  716. expires.setDate(expires.getDate() + 1);
  717. db.models.user.findOneAndUpdate({"email.address": email}, {$set: {"services.password.reset": {code: code, expires}}}, next);
  718. },
  719. (user, next) => {
  720. mail.schemas.resetPasswordRequest(user.email.address, user.username, code, next);
  721. }
  722. ], (err) => {
  723. if (err && err !== true) {
  724. err = utils.getError(err);
  725. logger.error("REQUEST_PASSWORD_RESET", `Email '${email}' failed to request password reset. '${err}'`);
  726. cb({status: 'failure', message: err});
  727. } else {
  728. logger.success("REQUEST_PASSWORD_RESET", `Email '${email}' successfully requested a password reset.`);
  729. cb({
  730. status: 'success',
  731. message: 'Successfully requested password reset.'
  732. });
  733. }
  734. });
  735. },
  736. /**
  737. * Verifies a reset code
  738. *
  739. * @param {Object} session - the session object automatically added by socket.io
  740. * @param {String} code - the password reset code
  741. * @param {Function} cb - gets called with the result
  742. */
  743. verifyPasswordResetCode: (session, code, cb) => {
  744. async.waterfall([
  745. (next) => {
  746. if (!code || typeof code !== 'string') return next('Invalid code.');
  747. db.models.user.findOne({"services.password.reset.code": code}, next);
  748. },
  749. (user, next) => {
  750. if (!user) return next('Invalid code.');
  751. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  752. next(null);
  753. }
  754. ], (err) => {
  755. if (err && err !== true) {
  756. err = utils.getError(err);
  757. logger.error("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  758. cb({status: 'failure', message: err});
  759. } else {
  760. logger.success("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  761. cb({
  762. status: 'success',
  763. message: 'Successfully verified password reset code.'
  764. });
  765. }
  766. });
  767. },
  768. /**
  769. * Changes a user's password with a reset code
  770. *
  771. * @param {Object} session - the session object automatically added by socket.io
  772. * @param {String} code - the password reset code
  773. * @param {String} newPassword - the new password reset code
  774. * @param {Function} cb - gets called with the result
  775. */
  776. changePasswordWithResetCode: (session, code, newPassword, cb) => {
  777. async.waterfall([
  778. (next) => {
  779. if (!code || typeof code !== 'string') return next('Invalid code.');
  780. db.models.user.findOne({"services.password.reset.code": code}, next);
  781. },
  782. (user, next) => {
  783. if (!user) return next('Invalid code.');
  784. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  785. next();
  786. },
  787. (next) => {
  788. bcrypt.genSalt(10, next);
  789. },
  790. // hash the password
  791. (salt, next) => {
  792. bcrypt.hash(sha256(newPassword), salt, next);
  793. },
  794. (hashedPassword, next) => {
  795. db.models.user.update({"services.password.reset.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.reset": ''}}, next);
  796. }
  797. ], (err) => {
  798. if (err && err !== true) {
  799. err = utils.getError(err);
  800. logger.error("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' failed to change password. '${err}'`);
  801. cb({status: 'failure', message: err});
  802. } else {
  803. logger.success("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  804. cb({
  805. status: 'success',
  806. message: 'Successfully changed password.'
  807. });
  808. }
  809. });
  810. }
  811. };