users.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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. let error = 'An error occurred.';
  501. if (typeof err === "string") error = err;
  502. else if (err.message) error = err.message;
  503. logger.error("UPDATE_PASSWORD", `Failed updating user password of user '${userId}'. '${error}'.`);
  504. return cb({ status: 'failure', message: error });
  505. }
  506. logger.error("UPDATE_PASSWORD", `User '${userId}' updated their password.`);
  507. cb({
  508. status: 'success',
  509. message: 'Password successfully updated.'
  510. });
  511. });
  512. }),
  513. /**
  514. * Requests a password for a session
  515. *
  516. * @param {Object} session - the session object automatically added by socket.io
  517. * @param {String} email - the email of the user that requests a password reset
  518. * @param {Function} cb - gets called with the result
  519. * @param {String} userId - the userId automatically added by hooks
  520. */
  521. requestPassword: hooks.loginRequired((session, cb, userId) => {
  522. let code = utils.generateRandomString(8);
  523. async.waterfall([
  524. (next) => {
  525. db.models.user.findOne({_id: userId}, next);
  526. },
  527. (user, next) => {
  528. if (!user) return next('User not found.');
  529. if (user.services.password && user.services.password.password) return next('You already have a password set.');
  530. next(null, user);
  531. },
  532. (user, next) => {
  533. let expires = new Date();
  534. expires.setDate(expires.getDate() + 1);
  535. db.models.user.findOneAndUpdate({"email.address": user.email.address}, {$set: {"services.password": {set: {code: code, expires}}}}, next);
  536. },
  537. (user, next) => {
  538. mail.schemas.passwordRequest(user.email.address, user.username, code, next);
  539. }
  540. ], (err) => {
  541. if (err && err !== true) {
  542. let error = 'An error occurred.';
  543. if (typeof err === "string") error = err;
  544. else if (err.message) error = err.message;
  545. logger.error("REQUEST_PASSWORD", `UserId '${userId}' failed to request password. '${error}'`);
  546. cb({status: 'failure', message: error});
  547. } else {
  548. logger.success("REQUEST_PASSWORD", `UserId '${userId}' successfully requested a password.`);
  549. cb({
  550. status: 'success',
  551. message: 'Successfully requested password.'
  552. });
  553. }
  554. });
  555. }),
  556. /**
  557. * Verifies a password code
  558. *
  559. * @param {Object} session - the session object automatically added by socket.io
  560. * @param {String} code - the password code
  561. * @param {Function} cb - gets called with the result
  562. * @param {String} userId - the userId automatically added by hooks
  563. */
  564. verifyPasswordCode: hooks.loginRequired((session, code, cb, userId) => {
  565. async.waterfall([
  566. (next) => {
  567. if (!code || typeof code !== 'string') return next('Invalid code1.');
  568. db.models.user.findOne({"services.password.set.code": code, _id: userId}, next);
  569. },
  570. (user, next) => {
  571. if (!user) return next('Invalid code2.');
  572. if (user.services.password.set.expires < new Date()) return next('That code has expired.');
  573. next(null);
  574. }
  575. ], (err) => {
  576. if (err && err !== true) {
  577. let error = 'An error occurred.';
  578. if (typeof err === "string") error = err;
  579. else if (err.message) error = err.message;
  580. logger.error("VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${error}'`);
  581. cb({status: 'failure', message: error});
  582. } else {
  583. logger.success("VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  584. cb({
  585. status: 'success',
  586. message: 'Successfully verified password code.'
  587. });
  588. }
  589. });
  590. }),
  591. /**
  592. * Adds a password to a user with a code
  593. *
  594. * @param {Object} session - the session object automatically added by socket.io
  595. * @param {String} code - the password code
  596. * @param {String} newPassword - the new password code
  597. * @param {Function} cb - gets called with the result
  598. * @param {String} userId - the userId automatically added by hooks
  599. */
  600. changePasswordWithCode: hooks.loginRequired((session, code, newPassword, cb, userId) => {
  601. async.waterfall([
  602. (next) => {
  603. if (!code || typeof code !== 'string') return next('Invalid code1.');
  604. db.models.user.findOne({"services.password.set.code": code}, next);
  605. },
  606. (user, next) => {
  607. if (!user) return next('Invalid code2.');
  608. if (!user.services.password.set.expires > new Date()) return next('That code has expired.');
  609. next();
  610. },
  611. (next) => {
  612. bcrypt.genSalt(10, next);
  613. },
  614. // hash the password
  615. (salt, next) => {
  616. bcrypt.hash(sha256(newPassword), salt, next);
  617. },
  618. (hashedPassword, next) => {
  619. db.models.user.update({"services.password.set.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.set": ''}}, next);
  620. }
  621. ], (err) => {
  622. if (err && err !== true) {
  623. let error = 'An error occurred.';
  624. if (typeof err === "string") error = err;
  625. else if (err.message) error = err.message;
  626. logger.error("ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${error}'`);
  627. cb({status: 'failure', message: error});
  628. } else {
  629. logger.success("ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  630. cache.pub('user.linkPassword', userId);
  631. cb({
  632. status: 'success',
  633. message: 'Successfully added password.'
  634. });
  635. }
  636. });
  637. }),
  638. /**
  639. * Unlinks password from user
  640. *
  641. * @param {Object} session - the session object automatically added by socket.io
  642. * @param {Function} cb - gets called with the result
  643. * @param {String} userId - the userId automatically added by hooks
  644. */
  645. unlinkPassword: hooks.loginRequired((session, cb, userId) => {
  646. async.waterfall([
  647. (next) => {
  648. db.models.user.findOne({_id: userId}, next);
  649. },
  650. (user, next) => {
  651. if (!user) return next('Not logged in.');
  652. if (!user.services.github || !user.services.github.id) return next('You can\'t remove password login without having GitHub login.');
  653. db.models.user.update({_id: userId}, {$unset: {"services.password": ''}}, next);
  654. }
  655. ], (err) => {
  656. if (err && err !== true) {
  657. let error = 'An error occurred.';
  658. if (typeof err === "string") error = err;
  659. else if (err.message) error = err.message;
  660. logger.error("UNLINK_PASSWORD", `Unlinking password failed for userId '${userId}'. '${error}'`);
  661. cb({status: 'failure', message: error});
  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. let error = 'An error occurred.';
  692. if (typeof err === "string") error = err;
  693. else if (err.message) error = err.message;
  694. logger.error("UNLINK_GITHUB", `Unlinking GitHub failed for userId '${userId}'. '${error}'`);
  695. cb({status: 'failure', message: error});
  696. } else {
  697. logger.success("UNLINK_GITHUB", `Unlinking GitHub successful for userId '${userId}'.`);
  698. cache.pub('user.unlinkGitHub', userId);
  699. cb({
  700. status: 'success',
  701. message: 'Successfully unlinked GitHub.'
  702. });
  703. }
  704. });
  705. }),
  706. /**
  707. * Requests a password reset for an email
  708. *
  709. * @param {Object} session - the session object automatically added by socket.io
  710. * @param {String} email - the email of the user that requests a password reset
  711. * @param {Function} cb - gets called with the result
  712. */
  713. requestPasswordReset: (session, email, cb) => {
  714. let code = utils.generateRandomString(8);
  715. async.waterfall([
  716. (next) => {
  717. if (!email || typeof email !== 'string') return next('Invalid email.');
  718. email = email.toLowerCase();
  719. db.models.user.findOne({"email.address": email}, next);
  720. },
  721. (user, next) => {
  722. if (!user) return next('User not found.');
  723. if (!user.services.password || !user.services.password.password) return next('User does not have a password set, and probably uses GitHub to log in.');
  724. next(null, user);
  725. },
  726. (user, next) => {
  727. let expires = new Date();
  728. expires.setDate(expires.getDate() + 1);
  729. db.models.user.findOneAndUpdate({"email.address": email}, {$set: {"services.password.reset": {code: code, expires}}}, next);
  730. },
  731. (user, next) => {
  732. mail.schemas.resetPasswordRequest(user.email.address, user.username, code, next);
  733. }
  734. ], (err) => {
  735. if (err && err !== true) {
  736. let error = 'An error occurred.';
  737. if (typeof err === "string") error = err;
  738. else if (err.message) error = err.message;
  739. logger.error("REQUEST_PASSWORD_RESET", `Email '${email}' failed to request password reset. '${error}'`);
  740. cb({status: 'failure', message: error});
  741. } else {
  742. logger.success("REQUEST_PASSWORD_RESET", `Email '${email}' successfully requested a password reset.`);
  743. cb({
  744. status: 'success',
  745. message: 'Successfully requested password reset.'
  746. });
  747. }
  748. });
  749. },
  750. /**
  751. * Verifies a reset code
  752. *
  753. * @param {Object} session - the session object automatically added by socket.io
  754. * @param {String} code - the password reset code
  755. * @param {Function} cb - gets called with the result
  756. */
  757. verifyPasswordResetCode: (session, code, cb) => {
  758. async.waterfall([
  759. (next) => {
  760. if (!code || typeof code !== 'string') return next('Invalid code.');
  761. db.models.user.findOne({"services.password.reset.code": code}, next);
  762. },
  763. (user, next) => {
  764. if (!user) return next('Invalid code.');
  765. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  766. next(null);
  767. }
  768. ], (err) => {
  769. if (err && err !== true) {
  770. let error = 'An error occurred.';
  771. if (typeof err === "string") error = err;
  772. else if (err.message) error = err.message;
  773. logger.error("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${error}'`);
  774. cb({status: 'failure', message: error});
  775. } else {
  776. logger.success("VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  777. cb({
  778. status: 'success',
  779. message: 'Successfully verified password reset code.'
  780. });
  781. }
  782. });
  783. },
  784. /**
  785. * Changes a user's password with a reset code
  786. *
  787. * @param {Object} session - the session object automatically added by socket.io
  788. * @param {String} code - the password reset code
  789. * @param {String} newPassword - the new password reset code
  790. * @param {Function} cb - gets called with the result
  791. */
  792. changePasswordWithResetCode: (session, code, newPassword, cb) => {
  793. async.waterfall([
  794. (next) => {
  795. if (!code || typeof code !== 'string') return next('Invalid code.');
  796. db.models.user.findOne({"services.password.reset.code": code}, next);
  797. },
  798. (user, next) => {
  799. if (!user) return next('Invalid code.');
  800. if (!user.services.password.reset.expires > new Date()) return next('That code has expired.');
  801. next();
  802. },
  803. (next) => {
  804. bcrypt.genSalt(10, next);
  805. },
  806. // hash the password
  807. (salt, next) => {
  808. bcrypt.hash(sha256(newPassword), salt, next);
  809. },
  810. (hashedPassword, next) => {
  811. db.models.user.update({"services.password.reset.code": code}, {$set: {"services.password.password": hashedPassword}, $unset: {"services.password.reset": ''}}, next);
  812. }
  813. ], (err) => {
  814. if (err && err !== true) {
  815. let error = 'An error occurred.';
  816. if (typeof err === "string") error = err;
  817. else if (err.message) error = err.message;
  818. logger.error("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' failed to change password. '${error}'`);
  819. cb({status: 'failure', message: error});
  820. } else {
  821. logger.success("CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  822. cb({
  823. status: 'success',
  824. message: 'Successfully changed password.'
  825. });
  826. }
  827. });
  828. }
  829. };